@crxjs/vite-plugin 2.0.0-beta.1 → 2.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3,6 +3,7 @@ import { createHash } from 'crypto';
3
3
  import debug$2 from 'debug';
4
4
  import v8 from 'v8';
5
5
  import { posix } from 'path';
6
+ import { Subject, filter, ReplaySubject, switchMap, of, startWith, map, mergeMap, firstValueFrom, takeUntil, first, toArray, retry, concatWith, Subscription, buffer } from 'rxjs';
6
7
  import fsx from 'fs-extra';
7
8
  import { performance } from 'perf_hooks';
8
9
  import { rollup } from 'rollup';
@@ -13,7 +14,6 @@ import { createLogger } from 'vite';
13
14
  import { readFileSync, existsSync, promises } from 'fs';
14
15
  import { createRequire } from 'module';
15
16
  import fg from 'fast-glob';
16
- import getPort, { portNumbers } from 'get-port';
17
17
  import { load } from 'cheerio';
18
18
  import jsesc from 'jsesc';
19
19
  import colors from 'picocolors';
@@ -29,12 +29,15 @@ const pluginOptionsProvider = (options) => {
29
29
  }
30
30
  };
31
31
  };
32
- const getOptions = ({ plugins }) => {
32
+ const getOptions = async ({
33
+ plugins
34
+ }) => {
33
35
  if (typeof plugins === "undefined") {
34
36
  throw new Error("config.plugins is undefined");
35
37
  }
38
+ const awaitedPlugins = await Promise.all(plugins);
36
39
  let options;
37
- for (const p of plugins.flat()) {
40
+ for (const p of awaitedPlugins.flat()) {
38
41
  if (isCrxPlugin(p)) {
39
42
  if (p.name === pluginName$1) {
40
43
  const plugin = p;
@@ -160,1875 +163,6 @@ function defineClientValues(code, config) {
160
163
  }
161
164
  }
162
165
 
163
- /******************************************************************************
164
- Copyright (c) Microsoft Corporation.
165
-
166
- Permission to use, copy, modify, and/or distribute this software for any
167
- purpose with or without fee is hereby granted.
168
-
169
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
170
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
171
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
172
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
173
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
174
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
175
- PERFORMANCE OF THIS SOFTWARE.
176
- ***************************************************************************** */
177
- /* global Reflect, Promise */
178
-
179
- var extendStatics = function(d, b) {
180
- extendStatics = Object.setPrototypeOf ||
181
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
182
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
183
- return extendStatics(d, b);
184
- };
185
-
186
- function __extends(d, b) {
187
- if (typeof b !== "function" && b !== null)
188
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
189
- extendStatics(d, b);
190
- function __() { this.constructor = d; }
191
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
192
- }
193
-
194
- function __awaiter(thisArg, _arguments, P, generator) {
195
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
196
- return new (P || (P = Promise))(function (resolve, reject) {
197
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
198
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
199
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
200
- step((generator = generator.apply(thisArg, _arguments || [])).next());
201
- });
202
- }
203
-
204
- function __generator(thisArg, body) {
205
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
206
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
207
- function verb(n) { return function (v) { return step([n, v]); }; }
208
- function step(op) {
209
- if (f) throw new TypeError("Generator is already executing.");
210
- while (_) try {
211
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
212
- if (y = 0, t) op = [op[0] & 2, t.value];
213
- switch (op[0]) {
214
- case 0: case 1: t = op; break;
215
- case 4: _.label++; return { value: op[1], done: false };
216
- case 5: _.label++; y = op[1]; op = [0]; continue;
217
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
218
- default:
219
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
220
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
221
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
222
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
223
- if (t[2]) _.ops.pop();
224
- _.trys.pop(); continue;
225
- }
226
- op = body.call(thisArg, _);
227
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
228
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
229
- }
230
- }
231
-
232
- function __values(o) {
233
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
234
- if (m) return m.call(o);
235
- if (o && typeof o.length === "number") return {
236
- next: function () {
237
- if (o && i >= o.length) o = void 0;
238
- return { value: o && o[i++], done: !o };
239
- }
240
- };
241
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
242
- }
243
-
244
- function __read(o, n) {
245
- var m = typeof Symbol === "function" && o[Symbol.iterator];
246
- if (!m) return o;
247
- var i = m.call(o), r, ar = [], e;
248
- try {
249
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
250
- }
251
- catch (error) { e = { error: error }; }
252
- finally {
253
- try {
254
- if (r && !r.done && (m = i["return"])) m.call(i);
255
- }
256
- finally { if (e) throw e.error; }
257
- }
258
- return ar;
259
- }
260
-
261
- function __spreadArray(to, from, pack) {
262
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
263
- if (ar || !(i in from)) {
264
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
265
- ar[i] = from[i];
266
- }
267
- }
268
- return to.concat(ar || Array.prototype.slice.call(from));
269
- }
270
-
271
- function __await(v) {
272
- return this instanceof __await ? (this.v = v, this) : new __await(v);
273
- }
274
-
275
- function __asyncGenerator(thisArg, _arguments, generator) {
276
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
277
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
278
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
279
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
280
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
281
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
282
- function fulfill(value) { resume("next", value); }
283
- function reject(value) { resume("throw", value); }
284
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
285
- }
286
-
287
- function __asyncValues(o) {
288
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
289
- var m = o[Symbol.asyncIterator], i;
290
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
291
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
292
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
293
- }
294
-
295
- function isFunction(value) {
296
- return typeof value === 'function';
297
- }
298
-
299
- function createErrorClass(createImpl) {
300
- var _super = function (instance) {
301
- Error.call(instance);
302
- instance.stack = new Error().stack;
303
- };
304
- var ctorFunc = createImpl(_super);
305
- ctorFunc.prototype = Object.create(Error.prototype);
306
- ctorFunc.prototype.constructor = ctorFunc;
307
- return ctorFunc;
308
- }
309
-
310
- var UnsubscriptionError = createErrorClass(function (_super) {
311
- return function UnsubscriptionErrorImpl(errors) {
312
- _super(this);
313
- this.message = errors
314
- ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
315
- : '';
316
- this.name = 'UnsubscriptionError';
317
- this.errors = errors;
318
- };
319
- });
320
-
321
- function arrRemove(arr, item) {
322
- if (arr) {
323
- var index = arr.indexOf(item);
324
- 0 <= index && arr.splice(index, 1);
325
- }
326
- }
327
-
328
- var Subscription = (function () {
329
- function Subscription(initialTeardown) {
330
- this.initialTeardown = initialTeardown;
331
- this.closed = false;
332
- this._parentage = null;
333
- this._finalizers = null;
334
- }
335
- Subscription.prototype.unsubscribe = function () {
336
- var e_1, _a, e_2, _b;
337
- var errors;
338
- if (!this.closed) {
339
- this.closed = true;
340
- var _parentage = this._parentage;
341
- if (_parentage) {
342
- this._parentage = null;
343
- if (Array.isArray(_parentage)) {
344
- try {
345
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
346
- var parent_1 = _parentage_1_1.value;
347
- parent_1.remove(this);
348
- }
349
- }
350
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
351
- finally {
352
- try {
353
- if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
354
- }
355
- finally { if (e_1) throw e_1.error; }
356
- }
357
- }
358
- else {
359
- _parentage.remove(this);
360
- }
361
- }
362
- var initialFinalizer = this.initialTeardown;
363
- if (isFunction(initialFinalizer)) {
364
- try {
365
- initialFinalizer();
366
- }
367
- catch (e) {
368
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
369
- }
370
- }
371
- var _finalizers = this._finalizers;
372
- if (_finalizers) {
373
- this._finalizers = null;
374
- try {
375
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
376
- var finalizer = _finalizers_1_1.value;
377
- try {
378
- execFinalizer(finalizer);
379
- }
380
- catch (err) {
381
- errors = errors !== null && errors !== void 0 ? errors : [];
382
- if (err instanceof UnsubscriptionError) {
383
- errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
384
- }
385
- else {
386
- errors.push(err);
387
- }
388
- }
389
- }
390
- }
391
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
392
- finally {
393
- try {
394
- if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
395
- }
396
- finally { if (e_2) throw e_2.error; }
397
- }
398
- }
399
- if (errors) {
400
- throw new UnsubscriptionError(errors);
401
- }
402
- }
403
- };
404
- Subscription.prototype.add = function (teardown) {
405
- var _a;
406
- if (teardown && teardown !== this) {
407
- if (this.closed) {
408
- execFinalizer(teardown);
409
- }
410
- else {
411
- if (teardown instanceof Subscription) {
412
- if (teardown.closed || teardown._hasParent(this)) {
413
- return;
414
- }
415
- teardown._addParent(this);
416
- }
417
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
418
- }
419
- }
420
- };
421
- Subscription.prototype._hasParent = function (parent) {
422
- var _parentage = this._parentage;
423
- return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
424
- };
425
- Subscription.prototype._addParent = function (parent) {
426
- var _parentage = this._parentage;
427
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
428
- };
429
- Subscription.prototype._removeParent = function (parent) {
430
- var _parentage = this._parentage;
431
- if (_parentage === parent) {
432
- this._parentage = null;
433
- }
434
- else if (Array.isArray(_parentage)) {
435
- arrRemove(_parentage, parent);
436
- }
437
- };
438
- Subscription.prototype.remove = function (teardown) {
439
- var _finalizers = this._finalizers;
440
- _finalizers && arrRemove(_finalizers, teardown);
441
- if (teardown instanceof Subscription) {
442
- teardown._removeParent(this);
443
- }
444
- };
445
- Subscription.EMPTY = (function () {
446
- var empty = new Subscription();
447
- empty.closed = true;
448
- return empty;
449
- })();
450
- return Subscription;
451
- }());
452
- var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
453
- function isSubscription(value) {
454
- return (value instanceof Subscription ||
455
- (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
456
- }
457
- function execFinalizer(finalizer) {
458
- if (isFunction(finalizer)) {
459
- finalizer();
460
- }
461
- else {
462
- finalizer.unsubscribe();
463
- }
464
- }
465
-
466
- var config = {
467
- onUnhandledError: null,
468
- onStoppedNotification: null,
469
- Promise: undefined,
470
- useDeprecatedSynchronousErrorHandling: false,
471
- useDeprecatedNextContext: false,
472
- };
473
-
474
- var timeoutProvider = {
475
- setTimeout: function (handler, timeout) {
476
- var args = [];
477
- for (var _i = 2; _i < arguments.length; _i++) {
478
- args[_i - 2] = arguments[_i];
479
- }
480
- var delegate = timeoutProvider.delegate;
481
- if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
482
- return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
483
- }
484
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
485
- },
486
- clearTimeout: function (handle) {
487
- var delegate = timeoutProvider.delegate;
488
- return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
489
- },
490
- delegate: undefined,
491
- };
492
-
493
- function reportUnhandledError(err) {
494
- timeoutProvider.setTimeout(function () {
495
- {
496
- throw err;
497
- }
498
- });
499
- }
500
-
501
- function noop() { }
502
-
503
- var COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();
504
- function errorNotification(error) {
505
- return createNotification('E', undefined, error);
506
- }
507
- function nextNotification(value) {
508
- return createNotification('N', value, undefined);
509
- }
510
- function createNotification(kind, value, error) {
511
- return {
512
- kind: kind,
513
- value: value,
514
- error: error,
515
- };
516
- }
517
-
518
- var context = null;
519
- function errorContext(cb) {
520
- if (config.useDeprecatedSynchronousErrorHandling) {
521
- var isRoot = !context;
522
- if (isRoot) {
523
- context = { errorThrown: false, error: null };
524
- }
525
- cb();
526
- if (isRoot) {
527
- var _a = context, errorThrown = _a.errorThrown, error = _a.error;
528
- context = null;
529
- if (errorThrown) {
530
- throw error;
531
- }
532
- }
533
- }
534
- else {
535
- cb();
536
- }
537
- }
538
-
539
- var Subscriber = (function (_super) {
540
- __extends(Subscriber, _super);
541
- function Subscriber(destination) {
542
- var _this = _super.call(this) || this;
543
- _this.isStopped = false;
544
- if (destination) {
545
- _this.destination = destination;
546
- if (isSubscription(destination)) {
547
- destination.add(_this);
548
- }
549
- }
550
- else {
551
- _this.destination = EMPTY_OBSERVER;
552
- }
553
- return _this;
554
- }
555
- Subscriber.create = function (next, error, complete) {
556
- return new SafeSubscriber(next, error, complete);
557
- };
558
- Subscriber.prototype.next = function (value) {
559
- if (this.isStopped) {
560
- handleStoppedNotification(nextNotification(value), this);
561
- }
562
- else {
563
- this._next(value);
564
- }
565
- };
566
- Subscriber.prototype.error = function (err) {
567
- if (this.isStopped) {
568
- handleStoppedNotification(errorNotification(err), this);
569
- }
570
- else {
571
- this.isStopped = true;
572
- this._error(err);
573
- }
574
- };
575
- Subscriber.prototype.complete = function () {
576
- if (this.isStopped) {
577
- handleStoppedNotification(COMPLETE_NOTIFICATION, this);
578
- }
579
- else {
580
- this.isStopped = true;
581
- this._complete();
582
- }
583
- };
584
- Subscriber.prototype.unsubscribe = function () {
585
- if (!this.closed) {
586
- this.isStopped = true;
587
- _super.prototype.unsubscribe.call(this);
588
- this.destination = null;
589
- }
590
- };
591
- Subscriber.prototype._next = function (value) {
592
- this.destination.next(value);
593
- };
594
- Subscriber.prototype._error = function (err) {
595
- try {
596
- this.destination.error(err);
597
- }
598
- finally {
599
- this.unsubscribe();
600
- }
601
- };
602
- Subscriber.prototype._complete = function () {
603
- try {
604
- this.destination.complete();
605
- }
606
- finally {
607
- this.unsubscribe();
608
- }
609
- };
610
- return Subscriber;
611
- }(Subscription));
612
- var _bind = Function.prototype.bind;
613
- function bind(fn, thisArg) {
614
- return _bind.call(fn, thisArg);
615
- }
616
- var ConsumerObserver = (function () {
617
- function ConsumerObserver(partialObserver) {
618
- this.partialObserver = partialObserver;
619
- }
620
- ConsumerObserver.prototype.next = function (value) {
621
- var partialObserver = this.partialObserver;
622
- if (partialObserver.next) {
623
- try {
624
- partialObserver.next(value);
625
- }
626
- catch (error) {
627
- handleUnhandledError(error);
628
- }
629
- }
630
- };
631
- ConsumerObserver.prototype.error = function (err) {
632
- var partialObserver = this.partialObserver;
633
- if (partialObserver.error) {
634
- try {
635
- partialObserver.error(err);
636
- }
637
- catch (error) {
638
- handleUnhandledError(error);
639
- }
640
- }
641
- else {
642
- handleUnhandledError(err);
643
- }
644
- };
645
- ConsumerObserver.prototype.complete = function () {
646
- var partialObserver = this.partialObserver;
647
- if (partialObserver.complete) {
648
- try {
649
- partialObserver.complete();
650
- }
651
- catch (error) {
652
- handleUnhandledError(error);
653
- }
654
- }
655
- };
656
- return ConsumerObserver;
657
- }());
658
- var SafeSubscriber = (function (_super) {
659
- __extends(SafeSubscriber, _super);
660
- function SafeSubscriber(observerOrNext, error, complete) {
661
- var _this = _super.call(this) || this;
662
- var partialObserver;
663
- if (isFunction(observerOrNext) || !observerOrNext) {
664
- partialObserver = {
665
- next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
666
- error: error !== null && error !== void 0 ? error : undefined,
667
- complete: complete !== null && complete !== void 0 ? complete : undefined,
668
- };
669
- }
670
- else {
671
- var context_1;
672
- if (_this && config.useDeprecatedNextContext) {
673
- context_1 = Object.create(observerOrNext);
674
- context_1.unsubscribe = function () { return _this.unsubscribe(); };
675
- partialObserver = {
676
- next: observerOrNext.next && bind(observerOrNext.next, context_1),
677
- error: observerOrNext.error && bind(observerOrNext.error, context_1),
678
- complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
679
- };
680
- }
681
- else {
682
- partialObserver = observerOrNext;
683
- }
684
- }
685
- _this.destination = new ConsumerObserver(partialObserver);
686
- return _this;
687
- }
688
- return SafeSubscriber;
689
- }(Subscriber));
690
- function handleUnhandledError(error) {
691
- {
692
- reportUnhandledError(error);
693
- }
694
- }
695
- function defaultErrorHandler(err) {
696
- throw err;
697
- }
698
- function handleStoppedNotification(notification, subscriber) {
699
- var onStoppedNotification = config.onStoppedNotification;
700
- onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });
701
- }
702
- var EMPTY_OBSERVER = {
703
- closed: true,
704
- next: noop,
705
- error: defaultErrorHandler,
706
- complete: noop,
707
- };
708
-
709
- var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
710
-
711
- function identity(x) {
712
- return x;
713
- }
714
-
715
- function pipeFromArray(fns) {
716
- if (fns.length === 0) {
717
- return identity;
718
- }
719
- if (fns.length === 1) {
720
- return fns[0];
721
- }
722
- return function piped(input) {
723
- return fns.reduce(function (prev, fn) { return fn(prev); }, input);
724
- };
725
- }
726
-
727
- var Observable = (function () {
728
- function Observable(subscribe) {
729
- if (subscribe) {
730
- this._subscribe = subscribe;
731
- }
732
- }
733
- Observable.prototype.lift = function (operator) {
734
- var observable = new Observable();
735
- observable.source = this;
736
- observable.operator = operator;
737
- return observable;
738
- };
739
- Observable.prototype.subscribe = function (observerOrNext, error, complete) {
740
- var _this = this;
741
- var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
742
- errorContext(function () {
743
- var _a = _this, operator = _a.operator, source = _a.source;
744
- subscriber.add(operator
745
- ?
746
- operator.call(subscriber, source)
747
- : source
748
- ?
749
- _this._subscribe(subscriber)
750
- :
751
- _this._trySubscribe(subscriber));
752
- });
753
- return subscriber;
754
- };
755
- Observable.prototype._trySubscribe = function (sink) {
756
- try {
757
- return this._subscribe(sink);
758
- }
759
- catch (err) {
760
- sink.error(err);
761
- }
762
- };
763
- Observable.prototype.forEach = function (next, promiseCtor) {
764
- var _this = this;
765
- promiseCtor = getPromiseCtor(promiseCtor);
766
- return new promiseCtor(function (resolve, reject) {
767
- var subscriber = new SafeSubscriber({
768
- next: function (value) {
769
- try {
770
- next(value);
771
- }
772
- catch (err) {
773
- reject(err);
774
- subscriber.unsubscribe();
775
- }
776
- },
777
- error: reject,
778
- complete: resolve,
779
- });
780
- _this.subscribe(subscriber);
781
- });
782
- };
783
- Observable.prototype._subscribe = function (subscriber) {
784
- var _a;
785
- return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
786
- };
787
- Observable.prototype[observable] = function () {
788
- return this;
789
- };
790
- Observable.prototype.pipe = function () {
791
- var operations = [];
792
- for (var _i = 0; _i < arguments.length; _i++) {
793
- operations[_i] = arguments[_i];
794
- }
795
- return pipeFromArray(operations)(this);
796
- };
797
- Observable.prototype.toPromise = function (promiseCtor) {
798
- var _this = this;
799
- promiseCtor = getPromiseCtor(promiseCtor);
800
- return new promiseCtor(function (resolve, reject) {
801
- var value;
802
- _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
803
- });
804
- };
805
- Observable.create = function (subscribe) {
806
- return new Observable(subscribe);
807
- };
808
- return Observable;
809
- }());
810
- function getPromiseCtor(promiseCtor) {
811
- var _a;
812
- return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
813
- }
814
- function isObserver(value) {
815
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
816
- }
817
- function isSubscriber(value) {
818
- return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
819
- }
820
-
821
- function hasLift(source) {
822
- return isFunction(source === null || source === void 0 ? void 0 : source.lift);
823
- }
824
- function operate(init) {
825
- return function (source) {
826
- if (hasLift(source)) {
827
- return source.lift(function (liftedSource) {
828
- try {
829
- return init(liftedSource, this);
830
- }
831
- catch (err) {
832
- this.error(err);
833
- }
834
- });
835
- }
836
- throw new TypeError('Unable to lift unknown Observable type');
837
- };
838
- }
839
-
840
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
841
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
842
- }
843
- var OperatorSubscriber = (function (_super) {
844
- __extends(OperatorSubscriber, _super);
845
- function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
846
- var _this = _super.call(this, destination) || this;
847
- _this.onFinalize = onFinalize;
848
- _this.shouldUnsubscribe = shouldUnsubscribe;
849
- _this._next = onNext
850
- ? function (value) {
851
- try {
852
- onNext(value);
853
- }
854
- catch (err) {
855
- destination.error(err);
856
- }
857
- }
858
- : _super.prototype._next;
859
- _this._error = onError
860
- ? function (err) {
861
- try {
862
- onError(err);
863
- }
864
- catch (err) {
865
- destination.error(err);
866
- }
867
- finally {
868
- this.unsubscribe();
869
- }
870
- }
871
- : _super.prototype._error;
872
- _this._complete = onComplete
873
- ? function () {
874
- try {
875
- onComplete();
876
- }
877
- catch (err) {
878
- destination.error(err);
879
- }
880
- finally {
881
- this.unsubscribe();
882
- }
883
- }
884
- : _super.prototype._complete;
885
- return _this;
886
- }
887
- OperatorSubscriber.prototype.unsubscribe = function () {
888
- var _a;
889
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
890
- var closed_1 = this.closed;
891
- _super.prototype.unsubscribe.call(this);
892
- !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
893
- }
894
- };
895
- return OperatorSubscriber;
896
- }(Subscriber));
897
-
898
- var ObjectUnsubscribedError = createErrorClass(function (_super) {
899
- return function ObjectUnsubscribedErrorImpl() {
900
- _super(this);
901
- this.name = 'ObjectUnsubscribedError';
902
- this.message = 'object unsubscribed';
903
- };
904
- });
905
-
906
- var Subject = (function (_super) {
907
- __extends(Subject, _super);
908
- function Subject() {
909
- var _this = _super.call(this) || this;
910
- _this.closed = false;
911
- _this.currentObservers = null;
912
- _this.observers = [];
913
- _this.isStopped = false;
914
- _this.hasError = false;
915
- _this.thrownError = null;
916
- return _this;
917
- }
918
- Subject.prototype.lift = function (operator) {
919
- var subject = new AnonymousSubject(this, this);
920
- subject.operator = operator;
921
- return subject;
922
- };
923
- Subject.prototype._throwIfClosed = function () {
924
- if (this.closed) {
925
- throw new ObjectUnsubscribedError();
926
- }
927
- };
928
- Subject.prototype.next = function (value) {
929
- var _this = this;
930
- errorContext(function () {
931
- var e_1, _a;
932
- _this._throwIfClosed();
933
- if (!_this.isStopped) {
934
- if (!_this.currentObservers) {
935
- _this.currentObservers = Array.from(_this.observers);
936
- }
937
- try {
938
- for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
939
- var observer = _c.value;
940
- observer.next(value);
941
- }
942
- }
943
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
944
- finally {
945
- try {
946
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
947
- }
948
- finally { if (e_1) throw e_1.error; }
949
- }
950
- }
951
- });
952
- };
953
- Subject.prototype.error = function (err) {
954
- var _this = this;
955
- errorContext(function () {
956
- _this._throwIfClosed();
957
- if (!_this.isStopped) {
958
- _this.hasError = _this.isStopped = true;
959
- _this.thrownError = err;
960
- var observers = _this.observers;
961
- while (observers.length) {
962
- observers.shift().error(err);
963
- }
964
- }
965
- });
966
- };
967
- Subject.prototype.complete = function () {
968
- var _this = this;
969
- errorContext(function () {
970
- _this._throwIfClosed();
971
- if (!_this.isStopped) {
972
- _this.isStopped = true;
973
- var observers = _this.observers;
974
- while (observers.length) {
975
- observers.shift().complete();
976
- }
977
- }
978
- });
979
- };
980
- Subject.prototype.unsubscribe = function () {
981
- this.isStopped = this.closed = true;
982
- this.observers = this.currentObservers = null;
983
- };
984
- Object.defineProperty(Subject.prototype, "observed", {
985
- get: function () {
986
- var _a;
987
- return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
988
- },
989
- enumerable: false,
990
- configurable: true
991
- });
992
- Subject.prototype._trySubscribe = function (subscriber) {
993
- this._throwIfClosed();
994
- return _super.prototype._trySubscribe.call(this, subscriber);
995
- };
996
- Subject.prototype._subscribe = function (subscriber) {
997
- this._throwIfClosed();
998
- this._checkFinalizedStatuses(subscriber);
999
- return this._innerSubscribe(subscriber);
1000
- };
1001
- Subject.prototype._innerSubscribe = function (subscriber) {
1002
- var _this = this;
1003
- var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1004
- if (hasError || isStopped) {
1005
- return EMPTY_SUBSCRIPTION;
1006
- }
1007
- this.currentObservers = null;
1008
- observers.push(subscriber);
1009
- return new Subscription(function () {
1010
- _this.currentObservers = null;
1011
- arrRemove(observers, subscriber);
1012
- });
1013
- };
1014
- Subject.prototype._checkFinalizedStatuses = function (subscriber) {
1015
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1016
- if (hasError) {
1017
- subscriber.error(thrownError);
1018
- }
1019
- else if (isStopped) {
1020
- subscriber.complete();
1021
- }
1022
- };
1023
- Subject.prototype.asObservable = function () {
1024
- var observable = new Observable();
1025
- observable.source = this;
1026
- return observable;
1027
- };
1028
- Subject.create = function (destination, source) {
1029
- return new AnonymousSubject(destination, source);
1030
- };
1031
- return Subject;
1032
- }(Observable));
1033
- var AnonymousSubject = (function (_super) {
1034
- __extends(AnonymousSubject, _super);
1035
- function AnonymousSubject(destination, source) {
1036
- var _this = _super.call(this) || this;
1037
- _this.destination = destination;
1038
- _this.source = source;
1039
- return _this;
1040
- }
1041
- AnonymousSubject.prototype.next = function (value) {
1042
- var _a, _b;
1043
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1044
- };
1045
- AnonymousSubject.prototype.error = function (err) {
1046
- var _a, _b;
1047
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1048
- };
1049
- AnonymousSubject.prototype.complete = function () {
1050
- var _a, _b;
1051
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1052
- };
1053
- AnonymousSubject.prototype._subscribe = function (subscriber) {
1054
- var _a, _b;
1055
- return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1056
- };
1057
- return AnonymousSubject;
1058
- }(Subject));
1059
-
1060
- var dateTimestampProvider = {
1061
- now: function () {
1062
- return (dateTimestampProvider.delegate || Date).now();
1063
- },
1064
- delegate: undefined,
1065
- };
1066
-
1067
- var ReplaySubject = (function (_super) {
1068
- __extends(ReplaySubject, _super);
1069
- function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
1070
- if (_bufferSize === void 0) { _bufferSize = Infinity; }
1071
- if (_windowTime === void 0) { _windowTime = Infinity; }
1072
- if (_timestampProvider === void 0) { _timestampProvider = dateTimestampProvider; }
1073
- var _this = _super.call(this) || this;
1074
- _this._bufferSize = _bufferSize;
1075
- _this._windowTime = _windowTime;
1076
- _this._timestampProvider = _timestampProvider;
1077
- _this._buffer = [];
1078
- _this._infiniteTimeWindow = true;
1079
- _this._infiniteTimeWindow = _windowTime === Infinity;
1080
- _this._bufferSize = Math.max(1, _bufferSize);
1081
- _this._windowTime = Math.max(1, _windowTime);
1082
- return _this;
1083
- }
1084
- ReplaySubject.prototype.next = function (value) {
1085
- var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
1086
- if (!isStopped) {
1087
- _buffer.push(value);
1088
- !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
1089
- }
1090
- this._trimBuffer();
1091
- _super.prototype.next.call(this, value);
1092
- };
1093
- ReplaySubject.prototype._subscribe = function (subscriber) {
1094
- this._throwIfClosed();
1095
- this._trimBuffer();
1096
- var subscription = this._innerSubscribe(subscriber);
1097
- var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
1098
- var copy = _buffer.slice();
1099
- for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
1100
- subscriber.next(copy[i]);
1101
- }
1102
- this._checkFinalizedStatuses(subscriber);
1103
- return subscription;
1104
- };
1105
- ReplaySubject.prototype._trimBuffer = function () {
1106
- var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
1107
- var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
1108
- _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
1109
- if (!_infiniteTimeWindow) {
1110
- var now = _timestampProvider.now();
1111
- var last = 0;
1112
- for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
1113
- last = i;
1114
- }
1115
- last && _buffer.splice(0, last + 1);
1116
- }
1117
- };
1118
- return ReplaySubject;
1119
- }(Subject));
1120
-
1121
- var Action = (function (_super) {
1122
- __extends(Action, _super);
1123
- function Action(scheduler, work) {
1124
- return _super.call(this) || this;
1125
- }
1126
- Action.prototype.schedule = function (state, delay) {
1127
- return this;
1128
- };
1129
- return Action;
1130
- }(Subscription));
1131
-
1132
- var intervalProvider = {
1133
- setInterval: function (handler, timeout) {
1134
- var args = [];
1135
- for (var _i = 2; _i < arguments.length; _i++) {
1136
- args[_i - 2] = arguments[_i];
1137
- }
1138
- var delegate = intervalProvider.delegate;
1139
- if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
1140
- return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args)));
1141
- }
1142
- return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1143
- },
1144
- clearInterval: function (handle) {
1145
- var delegate = intervalProvider.delegate;
1146
- return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
1147
- },
1148
- delegate: undefined,
1149
- };
1150
-
1151
- var AsyncAction = (function (_super) {
1152
- __extends(AsyncAction, _super);
1153
- function AsyncAction(scheduler, work) {
1154
- var _this = _super.call(this, scheduler, work) || this;
1155
- _this.scheduler = scheduler;
1156
- _this.work = work;
1157
- _this.pending = false;
1158
- return _this;
1159
- }
1160
- AsyncAction.prototype.schedule = function (state, delay) {
1161
- if (delay === void 0) { delay = 0; }
1162
- if (this.closed) {
1163
- return this;
1164
- }
1165
- this.state = state;
1166
- var id = this.id;
1167
- var scheduler = this.scheduler;
1168
- if (id != null) {
1169
- this.id = this.recycleAsyncId(scheduler, id, delay);
1170
- }
1171
- this.pending = true;
1172
- this.delay = delay;
1173
- this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
1174
- return this;
1175
- };
1176
- AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
1177
- if (delay === void 0) { delay = 0; }
1178
- return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
1179
- };
1180
- AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
1181
- if (delay === void 0) { delay = 0; }
1182
- if (delay != null && this.delay === delay && this.pending === false) {
1183
- return id;
1184
- }
1185
- intervalProvider.clearInterval(id);
1186
- return undefined;
1187
- };
1188
- AsyncAction.prototype.execute = function (state, delay) {
1189
- if (this.closed) {
1190
- return new Error('executing a cancelled action');
1191
- }
1192
- this.pending = false;
1193
- var error = this._execute(state, delay);
1194
- if (error) {
1195
- return error;
1196
- }
1197
- else if (this.pending === false && this.id != null) {
1198
- this.id = this.recycleAsyncId(this.scheduler, this.id, null);
1199
- }
1200
- };
1201
- AsyncAction.prototype._execute = function (state, _delay) {
1202
- var errored = false;
1203
- var errorValue;
1204
- try {
1205
- this.work(state);
1206
- }
1207
- catch (e) {
1208
- errored = true;
1209
- errorValue = e ? e : new Error('Scheduled action threw falsy error');
1210
- }
1211
- if (errored) {
1212
- this.unsubscribe();
1213
- return errorValue;
1214
- }
1215
- };
1216
- AsyncAction.prototype.unsubscribe = function () {
1217
- if (!this.closed) {
1218
- var _a = this, id = _a.id, scheduler = _a.scheduler;
1219
- var actions = scheduler.actions;
1220
- this.work = this.state = this.scheduler = null;
1221
- this.pending = false;
1222
- arrRemove(actions, this);
1223
- if (id != null) {
1224
- this.id = this.recycleAsyncId(scheduler, id, null);
1225
- }
1226
- this.delay = null;
1227
- _super.prototype.unsubscribe.call(this);
1228
- }
1229
- };
1230
- return AsyncAction;
1231
- }(Action));
1232
-
1233
- var Scheduler = (function () {
1234
- function Scheduler(schedulerActionCtor, now) {
1235
- if (now === void 0) { now = Scheduler.now; }
1236
- this.schedulerActionCtor = schedulerActionCtor;
1237
- this.now = now;
1238
- }
1239
- Scheduler.prototype.schedule = function (work, delay, state) {
1240
- if (delay === void 0) { delay = 0; }
1241
- return new this.schedulerActionCtor(this, work).schedule(state, delay);
1242
- };
1243
- Scheduler.now = dateTimestampProvider.now;
1244
- return Scheduler;
1245
- }());
1246
-
1247
- var AsyncScheduler = (function (_super) {
1248
- __extends(AsyncScheduler, _super);
1249
- function AsyncScheduler(SchedulerAction, now) {
1250
- if (now === void 0) { now = Scheduler.now; }
1251
- var _this = _super.call(this, SchedulerAction, now) || this;
1252
- _this.actions = [];
1253
- _this._active = false;
1254
- _this._scheduled = undefined;
1255
- return _this;
1256
- }
1257
- AsyncScheduler.prototype.flush = function (action) {
1258
- var actions = this.actions;
1259
- if (this._active) {
1260
- actions.push(action);
1261
- return;
1262
- }
1263
- var error;
1264
- this._active = true;
1265
- do {
1266
- if ((error = action.execute(action.state, action.delay))) {
1267
- break;
1268
- }
1269
- } while ((action = actions.shift()));
1270
- this._active = false;
1271
- if (error) {
1272
- while ((action = actions.shift())) {
1273
- action.unsubscribe();
1274
- }
1275
- throw error;
1276
- }
1277
- };
1278
- return AsyncScheduler;
1279
- }(Scheduler));
1280
-
1281
- var asyncScheduler = new AsyncScheduler(AsyncAction);
1282
- var async = asyncScheduler;
1283
-
1284
- var EMPTY = new Observable(function (subscriber) { return subscriber.complete(); });
1285
-
1286
- function isScheduler(value) {
1287
- return value && isFunction(value.schedule);
1288
- }
1289
-
1290
- function last(arr) {
1291
- return arr[arr.length - 1];
1292
- }
1293
- function popScheduler(args) {
1294
- return isScheduler(last(args)) ? args.pop() : undefined;
1295
- }
1296
-
1297
- var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
1298
-
1299
- function isPromise(value) {
1300
- return isFunction(value === null || value === void 0 ? void 0 : value.then);
1301
- }
1302
-
1303
- function isInteropObservable(input) {
1304
- return isFunction(input[observable]);
1305
- }
1306
-
1307
- function isAsyncIterable(obj) {
1308
- return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
1309
- }
1310
-
1311
- function createInvalidObservableTypeError(input) {
1312
- return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
1313
- }
1314
-
1315
- function getSymbolIterator() {
1316
- if (typeof Symbol !== 'function' || !Symbol.iterator) {
1317
- return '@@iterator';
1318
- }
1319
- return Symbol.iterator;
1320
- }
1321
- var iterator = getSymbolIterator();
1322
-
1323
- function isIterable(input) {
1324
- return isFunction(input === null || input === void 0 ? void 0 : input[iterator]);
1325
- }
1326
-
1327
- function readableStreamLikeToAsyncGenerator(readableStream) {
1328
- return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
1329
- var reader, _a, value, done;
1330
- return __generator(this, function (_b) {
1331
- switch (_b.label) {
1332
- case 0:
1333
- reader = readableStream.getReader();
1334
- _b.label = 1;
1335
- case 1:
1336
- _b.trys.push([1, , 9, 10]);
1337
- _b.label = 2;
1338
- case 2:
1339
- return [4, __await(reader.read())];
1340
- case 3:
1341
- _a = _b.sent(), value = _a.value, done = _a.done;
1342
- if (!done) return [3, 5];
1343
- return [4, __await(void 0)];
1344
- case 4: return [2, _b.sent()];
1345
- case 5: return [4, __await(value)];
1346
- case 6: return [4, _b.sent()];
1347
- case 7:
1348
- _b.sent();
1349
- return [3, 2];
1350
- case 8: return [3, 10];
1351
- case 9:
1352
- reader.releaseLock();
1353
- return [7];
1354
- case 10: return [2];
1355
- }
1356
- });
1357
- });
1358
- }
1359
- function isReadableStreamLike(obj) {
1360
- return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
1361
- }
1362
-
1363
- function innerFrom(input) {
1364
- if (input instanceof Observable) {
1365
- return input;
1366
- }
1367
- if (input != null) {
1368
- if (isInteropObservable(input)) {
1369
- return fromInteropObservable(input);
1370
- }
1371
- if (isArrayLike(input)) {
1372
- return fromArrayLike(input);
1373
- }
1374
- if (isPromise(input)) {
1375
- return fromPromise(input);
1376
- }
1377
- if (isAsyncIterable(input)) {
1378
- return fromAsyncIterable(input);
1379
- }
1380
- if (isIterable(input)) {
1381
- return fromIterable(input);
1382
- }
1383
- if (isReadableStreamLike(input)) {
1384
- return fromReadableStreamLike(input);
1385
- }
1386
- }
1387
- throw createInvalidObservableTypeError(input);
1388
- }
1389
- function fromInteropObservable(obj) {
1390
- return new Observable(function (subscriber) {
1391
- var obs = obj[observable]();
1392
- if (isFunction(obs.subscribe)) {
1393
- return obs.subscribe(subscriber);
1394
- }
1395
- throw new TypeError('Provided object does not correctly implement Symbol.observable');
1396
- });
1397
- }
1398
- function fromArrayLike(array) {
1399
- return new Observable(function (subscriber) {
1400
- for (var i = 0; i < array.length && !subscriber.closed; i++) {
1401
- subscriber.next(array[i]);
1402
- }
1403
- subscriber.complete();
1404
- });
1405
- }
1406
- function fromPromise(promise) {
1407
- return new Observable(function (subscriber) {
1408
- promise
1409
- .then(function (value) {
1410
- if (!subscriber.closed) {
1411
- subscriber.next(value);
1412
- subscriber.complete();
1413
- }
1414
- }, function (err) { return subscriber.error(err); })
1415
- .then(null, reportUnhandledError);
1416
- });
1417
- }
1418
- function fromIterable(iterable) {
1419
- return new Observable(function (subscriber) {
1420
- var e_1, _a;
1421
- try {
1422
- for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
1423
- var value = iterable_1_1.value;
1424
- subscriber.next(value);
1425
- if (subscriber.closed) {
1426
- return;
1427
- }
1428
- }
1429
- }
1430
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1431
- finally {
1432
- try {
1433
- if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
1434
- }
1435
- finally { if (e_1) throw e_1.error; }
1436
- }
1437
- subscriber.complete();
1438
- });
1439
- }
1440
- function fromAsyncIterable(asyncIterable) {
1441
- return new Observable(function (subscriber) {
1442
- process$1(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
1443
- });
1444
- }
1445
- function fromReadableStreamLike(readableStream) {
1446
- return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1447
- }
1448
- function process$1(asyncIterable, subscriber) {
1449
- var asyncIterable_1, asyncIterable_1_1;
1450
- var e_2, _a;
1451
- return __awaiter(this, void 0, void 0, function () {
1452
- var value, e_2_1;
1453
- return __generator(this, function (_b) {
1454
- switch (_b.label) {
1455
- case 0:
1456
- _b.trys.push([0, 5, 6, 11]);
1457
- asyncIterable_1 = __asyncValues(asyncIterable);
1458
- _b.label = 1;
1459
- case 1: return [4, asyncIterable_1.next()];
1460
- case 2:
1461
- if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
1462
- value = asyncIterable_1_1.value;
1463
- subscriber.next(value);
1464
- if (subscriber.closed) {
1465
- return [2];
1466
- }
1467
- _b.label = 3;
1468
- case 3: return [3, 1];
1469
- case 4: return [3, 11];
1470
- case 5:
1471
- e_2_1 = _b.sent();
1472
- e_2 = { error: e_2_1 };
1473
- return [3, 11];
1474
- case 6:
1475
- _b.trys.push([6, , 9, 10]);
1476
- if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
1477
- return [4, _a.call(asyncIterable_1)];
1478
- case 7:
1479
- _b.sent();
1480
- _b.label = 8;
1481
- case 8: return [3, 10];
1482
- case 9:
1483
- if (e_2) throw e_2.error;
1484
- return [7];
1485
- case 10: return [7];
1486
- case 11:
1487
- subscriber.complete();
1488
- return [2];
1489
- }
1490
- });
1491
- });
1492
- }
1493
-
1494
- function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
1495
- if (delay === void 0) { delay = 0; }
1496
- if (repeat === void 0) { repeat = false; }
1497
- var scheduleSubscription = scheduler.schedule(function () {
1498
- work();
1499
- if (repeat) {
1500
- parentSubscription.add(this.schedule(null, delay));
1501
- }
1502
- else {
1503
- this.unsubscribe();
1504
- }
1505
- }, delay);
1506
- parentSubscription.add(scheduleSubscription);
1507
- if (!repeat) {
1508
- return scheduleSubscription;
1509
- }
1510
- }
1511
-
1512
- function observeOn(scheduler, delay) {
1513
- if (delay === void 0) { delay = 0; }
1514
- return operate(function (source, subscriber) {
1515
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));
1516
- });
1517
- }
1518
-
1519
- function subscribeOn(scheduler, delay) {
1520
- if (delay === void 0) { delay = 0; }
1521
- return operate(function (source, subscriber) {
1522
- subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
1523
- });
1524
- }
1525
-
1526
- function scheduleObservable(input, scheduler) {
1527
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1528
- }
1529
-
1530
- function schedulePromise(input, scheduler) {
1531
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1532
- }
1533
-
1534
- function scheduleArray(input, scheduler) {
1535
- return new Observable(function (subscriber) {
1536
- var i = 0;
1537
- return scheduler.schedule(function () {
1538
- if (i === input.length) {
1539
- subscriber.complete();
1540
- }
1541
- else {
1542
- subscriber.next(input[i++]);
1543
- if (!subscriber.closed) {
1544
- this.schedule();
1545
- }
1546
- }
1547
- });
1548
- });
1549
- }
1550
-
1551
- function scheduleIterable(input, scheduler) {
1552
- return new Observable(function (subscriber) {
1553
- var iterator$1;
1554
- executeSchedule(subscriber, scheduler, function () {
1555
- iterator$1 = input[iterator]();
1556
- executeSchedule(subscriber, scheduler, function () {
1557
- var _a;
1558
- var value;
1559
- var done;
1560
- try {
1561
- (_a = iterator$1.next(), value = _a.value, done = _a.done);
1562
- }
1563
- catch (err) {
1564
- subscriber.error(err);
1565
- return;
1566
- }
1567
- if (done) {
1568
- subscriber.complete();
1569
- }
1570
- else {
1571
- subscriber.next(value);
1572
- }
1573
- }, 0, true);
1574
- });
1575
- return function () { return isFunction(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return(); };
1576
- });
1577
- }
1578
-
1579
- function scheduleAsyncIterable(input, scheduler) {
1580
- if (!input) {
1581
- throw new Error('Iterable cannot be null');
1582
- }
1583
- return new Observable(function (subscriber) {
1584
- executeSchedule(subscriber, scheduler, function () {
1585
- var iterator = input[Symbol.asyncIterator]();
1586
- executeSchedule(subscriber, scheduler, function () {
1587
- iterator.next().then(function (result) {
1588
- if (result.done) {
1589
- subscriber.complete();
1590
- }
1591
- else {
1592
- subscriber.next(result.value);
1593
- }
1594
- });
1595
- }, 0, true);
1596
- });
1597
- });
1598
- }
1599
-
1600
- function scheduleReadableStreamLike(input, scheduler) {
1601
- return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
1602
- }
1603
-
1604
- function scheduled(input, scheduler) {
1605
- if (input != null) {
1606
- if (isInteropObservable(input)) {
1607
- return scheduleObservable(input, scheduler);
1608
- }
1609
- if (isArrayLike(input)) {
1610
- return scheduleArray(input, scheduler);
1611
- }
1612
- if (isPromise(input)) {
1613
- return schedulePromise(input, scheduler);
1614
- }
1615
- if (isAsyncIterable(input)) {
1616
- return scheduleAsyncIterable(input, scheduler);
1617
- }
1618
- if (isIterable(input)) {
1619
- return scheduleIterable(input, scheduler);
1620
- }
1621
- if (isReadableStreamLike(input)) {
1622
- return scheduleReadableStreamLike(input, scheduler);
1623
- }
1624
- }
1625
- throw createInvalidObservableTypeError(input);
1626
- }
1627
-
1628
- function from(input, scheduler) {
1629
- return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1630
- }
1631
-
1632
- function of() {
1633
- var args = [];
1634
- for (var _i = 0; _i < arguments.length; _i++) {
1635
- args[_i] = arguments[_i];
1636
- }
1637
- var scheduler = popScheduler(args);
1638
- return from(args, scheduler);
1639
- }
1640
-
1641
- var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
1642
- _super(this);
1643
- this.name = 'EmptyError';
1644
- this.message = 'no elements in sequence';
1645
- }; });
1646
-
1647
- function firstValueFrom(source, config) {
1648
- var hasConfig = typeof config === 'object';
1649
- return new Promise(function (resolve, reject) {
1650
- var subscriber = new SafeSubscriber({
1651
- next: function (value) {
1652
- resolve(value);
1653
- subscriber.unsubscribe();
1654
- },
1655
- error: reject,
1656
- complete: function () {
1657
- if (hasConfig) {
1658
- resolve(config.defaultValue);
1659
- }
1660
- else {
1661
- reject(new EmptyError());
1662
- }
1663
- },
1664
- });
1665
- source.subscribe(subscriber);
1666
- });
1667
- }
1668
-
1669
- function isValidDate(value) {
1670
- return value instanceof Date && !isNaN(value);
1671
- }
1672
-
1673
- function map(project, thisArg) {
1674
- return operate(function (source, subscriber) {
1675
- var index = 0;
1676
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1677
- subscriber.next(project.call(thisArg, value, index++));
1678
- }));
1679
- });
1680
- }
1681
-
1682
- function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
1683
- var buffer = [];
1684
- var active = 0;
1685
- var index = 0;
1686
- var isComplete = false;
1687
- var checkComplete = function () {
1688
- if (isComplete && !buffer.length && !active) {
1689
- subscriber.complete();
1690
- }
1691
- };
1692
- var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
1693
- var doInnerSub = function (value) {
1694
- expand && subscriber.next(value);
1695
- active++;
1696
- var innerComplete = false;
1697
- innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {
1698
- onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
1699
- if (expand) {
1700
- outerNext(innerValue);
1701
- }
1702
- else {
1703
- subscriber.next(innerValue);
1704
- }
1705
- }, function () {
1706
- innerComplete = true;
1707
- }, undefined, function () {
1708
- if (innerComplete) {
1709
- try {
1710
- active--;
1711
- var _loop_1 = function () {
1712
- var bufferedValue = buffer.shift();
1713
- if (innerSubScheduler) {
1714
- executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });
1715
- }
1716
- else {
1717
- doInnerSub(bufferedValue);
1718
- }
1719
- };
1720
- while (buffer.length && active < concurrent) {
1721
- _loop_1();
1722
- }
1723
- checkComplete();
1724
- }
1725
- catch (err) {
1726
- subscriber.error(err);
1727
- }
1728
- }
1729
- }));
1730
- };
1731
- source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {
1732
- isComplete = true;
1733
- checkComplete();
1734
- }));
1735
- return function () {
1736
- additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
1737
- };
1738
- }
1739
-
1740
- function mergeMap(project, resultSelector, concurrent) {
1741
- if (concurrent === void 0) { concurrent = Infinity; }
1742
- if (isFunction(resultSelector)) {
1743
- return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);
1744
- }
1745
- else if (typeof resultSelector === 'number') {
1746
- concurrent = resultSelector;
1747
- }
1748
- return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });
1749
- }
1750
-
1751
- function mergeAll(concurrent) {
1752
- if (concurrent === void 0) { concurrent = Infinity; }
1753
- return mergeMap(identity, concurrent);
1754
- }
1755
-
1756
- function concatAll() {
1757
- return mergeAll(1);
1758
- }
1759
-
1760
- function concat$1() {
1761
- var args = [];
1762
- for (var _i = 0; _i < arguments.length; _i++) {
1763
- args[_i] = arguments[_i];
1764
- }
1765
- return concatAll()(from(args, popScheduler(args)));
1766
- }
1767
-
1768
- function timer(dueTime, intervalOrScheduler, scheduler) {
1769
- if (dueTime === void 0) { dueTime = 0; }
1770
- if (scheduler === void 0) { scheduler = async; }
1771
- var intervalDuration = -1;
1772
- if (intervalOrScheduler != null) {
1773
- if (isScheduler(intervalOrScheduler)) {
1774
- scheduler = intervalOrScheduler;
1775
- }
1776
- else {
1777
- intervalDuration = intervalOrScheduler;
1778
- }
1779
- }
1780
- return new Observable(function (subscriber) {
1781
- var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
1782
- if (due < 0) {
1783
- due = 0;
1784
- }
1785
- var n = 0;
1786
- return scheduler.schedule(function () {
1787
- if (!subscriber.closed) {
1788
- subscriber.next(n++);
1789
- if (0 <= intervalDuration) {
1790
- this.schedule(undefined, intervalDuration);
1791
- }
1792
- else {
1793
- subscriber.complete();
1794
- }
1795
- }
1796
- }, due);
1797
- });
1798
- }
1799
-
1800
- function filter(predicate, thisArg) {
1801
- return operate(function (source, subscriber) {
1802
- var index = 0;
1803
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
1804
- });
1805
- }
1806
-
1807
- function buffer(closingNotifier) {
1808
- return operate(function (source, subscriber) {
1809
- var currentBuffer = [];
1810
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return currentBuffer.push(value); }, function () {
1811
- subscriber.next(currentBuffer);
1812
- subscriber.complete();
1813
- }));
1814
- closingNotifier.subscribe(createOperatorSubscriber(subscriber, function () {
1815
- var b = currentBuffer;
1816
- currentBuffer = [];
1817
- subscriber.next(b);
1818
- }, noop));
1819
- return function () {
1820
- currentBuffer = null;
1821
- };
1822
- });
1823
- }
1824
-
1825
- function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
1826
- return function (source, subscriber) {
1827
- var hasState = hasSeed;
1828
- var state = seed;
1829
- var index = 0;
1830
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1831
- var i = index++;
1832
- state = hasState
1833
- ?
1834
- accumulator(state, value, i)
1835
- :
1836
- ((hasState = true), value);
1837
- emitOnNext && subscriber.next(state);
1838
- }, emitBeforeComplete &&
1839
- (function () {
1840
- hasState && subscriber.next(state);
1841
- subscriber.complete();
1842
- })));
1843
- };
1844
- }
1845
-
1846
- function reduce(accumulator, seed) {
1847
- return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));
1848
- }
1849
-
1850
- var arrReducer = function (arr, value) { return (arr.push(value), arr); };
1851
- function toArray() {
1852
- return operate(function (source, subscriber) {
1853
- reduce(arrReducer, [])(source).subscribe(subscriber);
1854
- });
1855
- }
1856
-
1857
- function concat() {
1858
- var args = [];
1859
- for (var _i = 0; _i < arguments.length; _i++) {
1860
- args[_i] = arguments[_i];
1861
- }
1862
- var scheduler = popScheduler(args);
1863
- return operate(function (source, subscriber) {
1864
- concatAll()(from(__spreadArray([source], __read(args)), scheduler)).subscribe(subscriber);
1865
- });
1866
- }
1867
-
1868
- function concatWith() {
1869
- var otherSources = [];
1870
- for (var _i = 0; _i < arguments.length; _i++) {
1871
- otherSources[_i] = arguments[_i];
1872
- }
1873
- return concat.apply(void 0, __spreadArray([], __read(otherSources)));
1874
- }
1875
-
1876
- function defaultIfEmpty(defaultValue) {
1877
- return operate(function (source, subscriber) {
1878
- var hasValue = false;
1879
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1880
- hasValue = true;
1881
- subscriber.next(value);
1882
- }, function () {
1883
- if (!hasValue) {
1884
- subscriber.next(defaultValue);
1885
- }
1886
- subscriber.complete();
1887
- }));
1888
- });
1889
- }
1890
-
1891
- function take(count) {
1892
- return count <= 0
1893
- ?
1894
- function () { return EMPTY; }
1895
- : operate(function (source, subscriber) {
1896
- var seen = 0;
1897
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1898
- if (++seen <= count) {
1899
- subscriber.next(value);
1900
- if (count <= seen) {
1901
- subscriber.complete();
1902
- }
1903
- }
1904
- }));
1905
- });
1906
- }
1907
-
1908
- function throwIfEmpty(errorFactory) {
1909
- if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
1910
- return operate(function (source, subscriber) {
1911
- var hasValue = false;
1912
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1913
- hasValue = true;
1914
- subscriber.next(value);
1915
- }, function () { return (hasValue ? subscriber.complete() : subscriber.error(errorFactory())); }));
1916
- });
1917
- }
1918
- function defaultErrorFactory() {
1919
- return new EmptyError();
1920
- }
1921
-
1922
- function first(predicate, defaultValue) {
1923
- var hasDefaultValue = arguments.length >= 2;
1924
- return function (source) {
1925
- return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); }));
1926
- };
1927
- }
1928
-
1929
- function retry(configOrCount) {
1930
- if (configOrCount === void 0) { configOrCount = Infinity; }
1931
- var config;
1932
- if (configOrCount && typeof configOrCount === 'object') {
1933
- config = configOrCount;
1934
- }
1935
- else {
1936
- config = {
1937
- count: configOrCount,
1938
- };
1939
- }
1940
- var _a = config.count, count = _a === void 0 ? Infinity : _a, delay = config.delay, _b = config.resetOnSuccess, resetOnSuccess = _b === void 0 ? false : _b;
1941
- return count <= 0
1942
- ? identity
1943
- : operate(function (source, subscriber) {
1944
- var soFar = 0;
1945
- var innerSub;
1946
- var subscribeForRetry = function () {
1947
- var syncUnsub = false;
1948
- innerSub = source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1949
- if (resetOnSuccess) {
1950
- soFar = 0;
1951
- }
1952
- subscriber.next(value);
1953
- }, undefined, function (err) {
1954
- if (soFar++ < count) {
1955
- var resub_1 = function () {
1956
- if (innerSub) {
1957
- innerSub.unsubscribe();
1958
- innerSub = null;
1959
- subscribeForRetry();
1960
- }
1961
- else {
1962
- syncUnsub = true;
1963
- }
1964
- };
1965
- if (delay != null) {
1966
- var notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(err, soFar));
1967
- var notifierSubscriber_1 = createOperatorSubscriber(subscriber, function () {
1968
- notifierSubscriber_1.unsubscribe();
1969
- resub_1();
1970
- }, function () {
1971
- subscriber.complete();
1972
- });
1973
- notifier.subscribe(notifierSubscriber_1);
1974
- }
1975
- else {
1976
- resub_1();
1977
- }
1978
- }
1979
- else {
1980
- subscriber.error(err);
1981
- }
1982
- }));
1983
- if (syncUnsub) {
1984
- innerSub.unsubscribe();
1985
- innerSub = null;
1986
- subscribeForRetry();
1987
- }
1988
- };
1989
- subscribeForRetry();
1990
- });
1991
- }
1992
-
1993
- function startWith() {
1994
- var values = [];
1995
- for (var _i = 0; _i < arguments.length; _i++) {
1996
- values[_i] = arguments[_i];
1997
- }
1998
- var scheduler = popScheduler(values);
1999
- return operate(function (source, subscriber) {
2000
- (scheduler ? concat$1(values, source, scheduler) : concat$1(values, source)).subscribe(subscriber);
2001
- });
2002
- }
2003
-
2004
- function switchMap(project, resultSelector) {
2005
- return operate(function (source, subscriber) {
2006
- var innerSubscriber = null;
2007
- var index = 0;
2008
- var isComplete = false;
2009
- var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); };
2010
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2011
- innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
2012
- var innerIndex = 0;
2013
- var outerIndex = index++;
2014
- innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () {
2015
- innerSubscriber = null;
2016
- checkComplete();
2017
- })));
2018
- }, function () {
2019
- isComplete = true;
2020
- checkComplete();
2021
- }));
2022
- });
2023
- }
2024
-
2025
- function takeUntil(notifier) {
2026
- return operate(function (source, subscriber) {
2027
- innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, function () { return subscriber.complete(); }, noop));
2028
- !subscriber.closed && source.subscribe(subscriber);
2029
- });
2030
- }
2031
-
2032
166
  class RxMap extends Map {
2033
167
  static isChangeType = {
2034
168
  clear: (x) => x.type === "clear",
@@ -2088,10 +222,12 @@ function getFileName({ type, id }) {
2088
222
  case "asset":
2089
223
  return fileName;
2090
224
  default:
2091
- throw new Error(`Unexpected script type "${type}" for "${JSON.stringify({
2092
- type,
2093
- id
2094
- })}"`);
225
+ throw new Error(
226
+ `Unexpected script type "${type}" for "${JSON.stringify({
227
+ type,
228
+ id
229
+ })}"`
230
+ );
2095
231
  }
2096
232
  }
2097
233
  function getOutputPath(server, fileName) {
@@ -2147,7 +283,10 @@ const pluginBackground = () => {
2147
283
  load(id) {
2148
284
  if (id === workerClientId) {
2149
285
  const base = `http://localhost:${config.server.port}/`;
2150
- return defineClientValues(workerHmrClient.replace("__BASE__", JSON.stringify(base)), config);
286
+ return defineClientValues(
287
+ workerHmrClient.replace("__BASE__", JSON.stringify(base)),
288
+ config
289
+ );
2151
290
  }
2152
291
  }
2153
292
  },
@@ -2164,7 +303,7 @@ const pluginBackground = () => {
2164
303
  const port = config.server.port?.toString();
2165
304
  if (typeof port === "undefined")
2166
305
  throw new Error("server port is undefined in watch mode");
2167
- loader = `import 'http:/localhost:${port}/@vite/env';
306
+ loader = `import 'http://localhost:${port}/@vite/env';
2168
307
  `;
2169
308
  loader += `import 'http://localhost:${port}${workerClientId}';
2170
309
  `;
@@ -2232,15 +371,39 @@ function createProLoader({ fileName }) {
2232
371
  }
2233
372
 
2234
373
  const serverEvent$ = new ReplaySubject(1);
2235
- const close$ = serverEvent$.pipe(filter((e) => e.type === "close"), switchMap((e) => of(e)));
2236
- const start$ = serverEvent$.pipe(filter((e) => e.type === "start"), switchMap((e) => of(e)));
374
+ const close$ = serverEvent$.pipe(
375
+ filter((e) => e.type === "close"),
376
+ switchMap((e) => of(e))
377
+ );
378
+ const start$ = serverEvent$.pipe(
379
+ filter((e) => e.type === "start"),
380
+ switchMap((e) => of(e))
381
+ );
2237
382
  const fileWriterEvent$ = new ReplaySubject(1);
2238
- const buildEnd$ = fileWriterEvent$.pipe(filter((e) => e.type === "build_end"), switchMap((e) => of(e)));
2239
- fileWriterEvent$.pipe(filter((e) => e.type === "build_start"), switchMap((e) => of(e)));
2240
- const allFilesReady$ = buildEnd$.pipe(switchMap(() => outputFiles.change$.pipe(startWith({ type: "start" }))), map(() => [...outputFiles.values()]), switchMap((files) => Promise.allSettled(files.map(({ file }) => file))));
383
+ const buildEnd$ = fileWriterEvent$.pipe(
384
+ filter((e) => e.type === "build_end"),
385
+ switchMap((e) => of(e))
386
+ );
387
+ fileWriterEvent$.pipe(
388
+ filter((e) => e.type === "build_start"),
389
+ switchMap((e) => of(e))
390
+ );
391
+ const allFilesReady$ = buildEnd$.pipe(
392
+ switchMap(() => outputFiles.change$.pipe(startWith({ type: "start" }))),
393
+ map(() => [...outputFiles.values()]),
394
+ switchMap((files) => Promise.allSettled(files.map(({ file }) => file)))
395
+ );
2241
396
  const isRejected = (x) => x?.status === "rejected";
2242
- const fileWriterError$ = allFilesReady$.pipe(mergeMap((results) => results.filter(isRejected)), map((rejected) => ({ err: rejected.reason, type: "error" })));
2243
- firstValueFrom(fileWriterError$.pipe(takeUntil(serverEvent$.pipe(first(({ type }) => type === "close"))), toArray()));
397
+ const fileWriterError$ = allFilesReady$.pipe(
398
+ mergeMap((results) => results.filter(isRejected)),
399
+ map((rejected) => ({ err: rejected.reason, type: "error" }))
400
+ );
401
+ firstValueFrom(
402
+ fileWriterError$.pipe(
403
+ takeUntil(serverEvent$.pipe(first(({ type }) => type === "close"))),
404
+ toArray()
405
+ )
406
+ );
2244
407
  function prepFileData(fileId) {
2245
408
  const fileName = getFileName(fileId);
2246
409
  if (fileId.type === "asset") {
@@ -2250,46 +413,54 @@ function prepFileData(fileId) {
2250
413
  }
2251
414
  }
2252
415
  function prepAsset(fileName, { id, source }) {
2253
- return ($) => $.pipe(mergeMap(async ({ server }) => {
2254
- const target = getOutputPath(server, fileName);
2255
- return {
2256
- target,
2257
- source: source ?? await readFile$1(join(server.config.root, id)),
2258
- deps: []
2259
- };
2260
- }));
416
+ return ($) => $.pipe(
417
+ mergeMap(async ({ server }) => {
418
+ const target = getOutputPath(server, fileName);
419
+ return {
420
+ target,
421
+ source: source ?? await readFile$1(join(server.config.root, id)),
422
+ deps: []
423
+ };
424
+ })
425
+ );
2261
426
  }
2262
427
  function prepScript(fileName, script) {
2263
- return ($) => $.pipe(mergeMap(async ({ server }) => {
2264
- const target = getOutputPath(server, fileName);
2265
- const viteUrl = getViteUrl(script);
2266
- const transformResult = await server.transformRequest(viteUrl);
2267
- if (!transformResult)
2268
- throw new TypeError(`Unable to load "${script.id}" from server.`);
2269
- const { code, deps = [], dynamicDeps = [] } = transformResult;
2270
- return { target, code, deps: [...deps, ...dynamicDeps].flat(), server };
2271
- }), retry({ count: 10, delay: 100 }), mergeMap(async ({ target, server, ...rest }) => {
2272
- const plugins = server.config.plugins;
2273
- let { code, deps } = rest;
2274
- for (const plugin of plugins) {
2275
- const r = await plugin.renderCrxDevScript?.(code, script);
2276
- if (typeof r === "string")
2277
- code = r;
2278
- }
2279
- return { target, code, deps };
2280
- }), mergeMap(async ({ target, code, deps }) => {
2281
- await lexer.init;
2282
- const [imports] = lexer.parse(code, fileName);
2283
- const depSet = new Set(deps);
2284
- const magic = new MagicString(code);
2285
- for (const i of imports)
2286
- if (i.n) {
2287
- depSet.add(i.n);
2288
- const fileName2 = getFileName({ type: "module", id: i.n });
2289
- magic.overwrite(i.s, i.e, `/${fileName2}`);
428
+ return ($) => $.pipe(
429
+ mergeMap(async ({ server }) => {
430
+ const target = getOutputPath(server, fileName);
431
+ const viteUrl = getViteUrl(script);
432
+ const transformResult = await server.transformRequest(viteUrl);
433
+ if (!transformResult)
434
+ throw new TypeError(`Unable to load "${script.id}" from server.`);
435
+ const { code, deps = [], dynamicDeps = [] } = transformResult;
436
+ return { target, code, deps: [...deps, ...dynamicDeps].flat(), server };
437
+ }),
438
+ retry({ count: 10, delay: 100 }),
439
+ mergeMap(async ({ target, server, ...rest }) => {
440
+ const plugins = server.config.plugins;
441
+ let { code, deps } = rest;
442
+ for (const plugin of plugins) {
443
+ const r = await plugin.renderCrxDevScript?.(code, script);
444
+ if (typeof r === "string")
445
+ code = r;
2290
446
  }
2291
- return { target, source: magic.toString(), deps: [...depSet] };
2292
- }));
447
+ return { target, code, deps };
448
+ }),
449
+ mergeMap(async ({ target, code, deps }) => {
450
+ await lexer.init;
451
+ const [imports] = lexer.parse(code, fileName);
452
+ const depSet = new Set(deps);
453
+ const magic = new MagicString(code);
454
+ for (const i of imports)
455
+ if (i.n) {
456
+ depSet.add(i.n);
457
+ const fileName2 = getFileName({ type: "module", id: i.n });
458
+ const fullImport = code.substring(i.s, i.e);
459
+ magic.overwrite(i.s, i.e, fullImport.replace(i.n, `/${fileName2}`));
460
+ }
461
+ return { target, source: magic.toString(), deps: [...depSet] };
462
+ })
463
+ );
2293
464
  }
2294
465
  async function allFilesReady() {
2295
466
  await firstValueFrom(allFilesReady$);
@@ -2301,7 +472,9 @@ async function start({
2301
472
  server
2302
473
  }) {
2303
474
  serverEvent$.next({ type: "start", server });
2304
- const plugins = server.config.plugins.filter((p) => p.name?.startsWith("crx:"));
475
+ const plugins = server.config.plugins.filter(
476
+ (p) => p.name?.startsWith("crx:")
477
+ );
2305
478
  const { rollupOptions, outDir } = server.config.build;
2306
479
  const inputOptions = {
2307
480
  input: "index.html",
@@ -2353,21 +526,28 @@ function update(_id) {
2353
526
  }
2354
527
  async function write(fileId) {
2355
528
  const start2 = performance.now();
2356
- const deps = await firstValueFrom(start$.pipe(prepFileData(fileId), mergeMap(async ({ target, source, deps: deps2 }) => {
2357
- const files = deps2.map((id) => {
2358
- const r = [add({ id, type: "module" })];
2359
- if (id.includes("?import")) {
2360
- const [imported] = id.split("?import");
2361
- r.push(add({ id: imported, type: "asset" }));
2362
- }
2363
- return r;
2364
- }).flat();
2365
- if (source instanceof Uint8Array)
2366
- await outputFile(target, source);
2367
- else
2368
- await outputFile(target, source, { encoding: "utf8" });
2369
- return files;
2370
- }), takeUntil(close$), concatWith(of([]))));
529
+ const deps = await firstValueFrom(
530
+ start$.pipe(
531
+ prepFileData(fileId),
532
+ mergeMap(async ({ target, source, deps: deps2 }) => {
533
+ const files = deps2.map((id) => {
534
+ const r = [add({ id, type: "module" })];
535
+ if (id.includes("?import")) {
536
+ const [imported] = id.split("?import");
537
+ r.push(add({ id: imported, type: "asset" }));
538
+ }
539
+ return r;
540
+ }).flat();
541
+ if (source instanceof Uint8Array)
542
+ await outputFile(target, source);
543
+ else
544
+ await outputFile(target, source, { encoding: "utf8" });
545
+ return files;
546
+ }),
547
+ takeUntil(close$),
548
+ concatWith(of([]))
549
+ )
550
+ );
2371
551
  const close2 = performance.now();
2372
552
  return { start: start2, close: close2, deps };
2373
553
  }
@@ -2381,14 +561,16 @@ const pluginContentScripts = () => {
2381
561
  {
2382
562
  name: "crx:content-scripts",
2383
563
  apply: "serve",
2384
- config(config) {
2385
- const { contentScripts: contentScripts2 = {} } = getOptions(config);
564
+ async config(config) {
565
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config);
2386
566
  hmrTimeout = contentScripts2.hmrTimeout ?? 5e3;
2387
567
  preambleCode = preambleCode ?? contentScripts2.preambleCode;
2388
568
  },
2389
569
  async configureServer(_server) {
2390
570
  server = _server;
2391
- if (typeof preambleCode === "undefined" && server.config.plugins.some(({ name = "none" }) => name.toLowerCase().includes("react"))) {
571
+ if (typeof preambleCode === "undefined" && server.config.plugins.some(
572
+ ({ name = "none" }) => name.toLowerCase().includes("react") && !name.toLowerCase().includes("preact")
573
+ )) {
2392
574
  try {
2393
575
  const react = await import('@vitejs/plugin-react');
2394
576
  preambleCode = react.default.preambleCode;
@@ -2396,31 +578,33 @@ const pluginContentScripts = () => {
2396
578
  preambleCode = false;
2397
579
  }
2398
580
  }
2399
- sub.add(contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ value: script }) => {
2400
- const { type, id } = script;
2401
- if (type === "loader") {
2402
- let preamble = { fileName: "" };
2403
- if (preambleCode)
2404
- preamble = add({ type: "module", id: preambleId });
2405
- const client = add({ type: "module", id: viteClientId });
2406
- const file = add({ type: "module", id });
2407
- const loader = add({
2408
- type: "asset",
2409
- id: getFileName({ type: "loader", id }),
2410
- source: createDevLoader({
2411
- preamble: preamble.fileName,
2412
- client: client.fileName,
2413
- fileName: file.fileName
2414
- })
2415
- });
2416
- script.fileName = loader.fileName;
2417
- } else if (type === "iife") {
2418
- throw new Error("IIFE content scripts are not implemented");
2419
- } else {
2420
- const file = add({ type: "module", id });
2421
- script.fileName = file.fileName;
2422
- }
2423
- }));
581
+ sub.add(
582
+ contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ value: script }) => {
583
+ const { type, id } = script;
584
+ if (type === "loader") {
585
+ let preamble = { fileName: "" };
586
+ if (preambleCode)
587
+ preamble = add({ type: "module", id: preambleId });
588
+ const client = add({ type: "module", id: viteClientId });
589
+ const file = add({ type: "module", id });
590
+ const loader = add({
591
+ type: "asset",
592
+ id: getFileName({ type: "loader", id }),
593
+ source: createDevLoader({
594
+ preamble: preamble.fileName,
595
+ client: client.fileName,
596
+ fileName: file.fileName
597
+ })
598
+ });
599
+ script.fileName = loader.fileName;
600
+ } else if (type === "iife") {
601
+ throw new Error("IIFE content scripts are not implemented");
602
+ } else {
603
+ const file = add({ type: "module", id });
604
+ script.fileName = file.fileName;
605
+ }
606
+ })
607
+ );
2424
608
  },
2425
609
  resolveId(source) {
2426
610
  if (source === preambleId)
@@ -2434,7 +618,10 @@ const pluginContentScripts = () => {
2434
618
  return defined;
2435
619
  }
2436
620
  if (id === contentHmrPortId) {
2437
- const defined = contentHmrPort.replace("__CRX_HMR_TIMEOUT__", JSON.stringify(hmrTimeout));
621
+ const defined = contentHmrPort.replace(
622
+ "__CRX_HMR_TIMEOUT__",
623
+ JSON.stringify(hmrTimeout)
624
+ );
2438
625
  return defined;
2439
626
  }
2440
627
  },
@@ -2477,8 +664,8 @@ const pluginContentScriptsCss = () => {
2477
664
  return {
2478
665
  name: "crx:content-scripts-css",
2479
666
  enforce: "post",
2480
- config(config) {
2481
- const { contentScripts: contentScripts2 = {} } = getOptions(config);
667
+ async config(config) {
668
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config);
2482
669
  injectCss = contentScripts2.injectCss ?? true;
2483
670
  },
2484
671
  renderCrxManifest(manifest) {
@@ -2492,7 +679,9 @@ const pluginContentScriptsCss = () => {
2492
679
  if (css?.length)
2493
680
  script.css = [script.css ?? [], css].flat();
2494
681
  } else {
2495
- throw new Error(`Content script is undefined by fileName: ${fileName}`);
682
+ throw new Error(
683
+ `Content script is undefined by fileName: ${fileName}`
684
+ );
2496
685
  }
2497
686
  }
2498
687
  }
@@ -2505,7 +694,7 @@ const pluginDeclaredContentScripts = () => {
2505
694
  return [];
2506
695
  };
2507
696
 
2508
- const _dynamicScriptRegEx = /\b(import.meta).CRX_DYNAMIC_SCRIPT_(.+?);$/gm;
697
+ const _dynamicScriptRegEx = /\b(import.meta).CRX_DYNAMIC_SCRIPT_(.+?)[,;]/gm;
2509
698
  const dynamicScriptRegEx = () => {
2510
699
  _dynamicScriptRegEx.lastIndex = 0;
2511
700
  return _dynamicScriptRegEx;
@@ -2519,6 +708,34 @@ const pluginDynamicContentScripts = () => {
2519
708
  configResolved(_config) {
2520
709
  config = _config;
2521
710
  },
711
+ configureServer(server) {
712
+ return () => {
713
+ server.middlewares.use(async (req, res, next) => {
714
+ try {
715
+ await allFilesReady();
716
+ next();
717
+ } catch (error) {
718
+ let err;
719
+ if (error instanceof Error) {
720
+ err = error;
721
+ } else if (typeof error === "string") {
722
+ err = new Error(error);
723
+ } else {
724
+ err = new Error(
725
+ `Unexpected error "${error}" in middleware for "${req.url}"`
726
+ );
727
+ }
728
+ server.ws.send({
729
+ type: "error",
730
+ err: {
731
+ message: err.message,
732
+ stack: err.stack ?? "no stack available"
733
+ }
734
+ });
735
+ }
736
+ });
737
+ };
738
+ },
2522
739
  async resolveId(_source, importer) {
2523
740
  if (importer && _source.includes("?script")) {
2524
741
  const url = new URL(_source, "stub://stub");
@@ -2528,7 +745,9 @@ const pluginDynamicContentScripts = () => {
2528
745
  skipSelf: true
2529
746
  });
2530
747
  if (!resolved)
2531
- throw new Error(`Could not resolve dynamic script: "${_source}" from "${importer}"`);
748
+ throw new Error(
749
+ `Could not resolve dynamic script: "${_source}" from "${importer}"`
750
+ );
2532
751
  const { id } = resolved;
2533
752
  let type = "loader";
2534
753
  if (url.searchParams.has("module")) {
@@ -2585,10 +804,11 @@ const pluginDynamicContentScripts = () => {
2585
804
  if (config.command === "build") {
2586
805
  return `export default import.meta.CRX_DYNAMIC_SCRIPT_${script.refId};`;
2587
806
  } else if (typeof script.fileName === "string") {
2588
- await fileReady(script);
2589
807
  return `export default ${JSON.stringify(script.fileName)};`;
2590
808
  } else {
2591
- throw new Error(`Content script fileName is undefined: "${script.id}"`);
809
+ throw new Error(
810
+ `Content script fileName is undefined: "${script.id}"`
811
+ );
2592
812
  }
2593
813
  }
2594
814
  }
@@ -2600,14 +820,23 @@ const pluginDynamicContentScripts = () => {
2600
820
  for (const chunk of Object.values(bundle))
2601
821
  if (chunk.type === "chunk") {
2602
822
  if (dynamicScriptRegEx().test(chunk.code)) {
2603
- const replaced = chunk.code.replace(dynamicScriptRegEx(), (match, p1, scriptKey) => {
2604
- const script = contentScripts.get(scriptKey);
2605
- if (typeof script === "undefined")
2606
- throw new Error(`Content script refId is undefined: "${match}"`);
2607
- if (typeof script.fileName === "undefined")
2608
- throw new Error(`Content script fileName is undefined: "${script.id}"`);
2609
- return `${JSON.stringify(`/${script.loaderName ?? script.fileName}`)};`;
2610
- });
823
+ const replaced = chunk.code.replace(
824
+ dynamicScriptRegEx(),
825
+ (match, p1, scriptKey) => {
826
+ const script = contentScripts.get(scriptKey);
827
+ if (typeof script === "undefined")
828
+ throw new Error(
829
+ `Content script refId is undefined: "${match}"`
830
+ );
831
+ if (typeof script.fileName === "undefined")
832
+ throw new Error(
833
+ `Content script fileName is undefined: "${script.id}"`
834
+ );
835
+ return `${JSON.stringify(
836
+ `/${script.loaderName ?? script.fileName}`
837
+ )}${match.split(scriptKey)[1]}`;
838
+ }
839
+ );
2611
840
  chunk.code = replaced;
2612
841
  }
2613
842
  }
@@ -2678,25 +907,33 @@ async function manifestFiles(manifest, options = {}) {
2678
907
  let locales = [];
2679
908
  if (manifest.default_locale)
2680
909
  locales = await fg("_locales/**/messages.json", options);
2681
- const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(({ path }) => path) ?? [];
910
+ const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(
911
+ ({ path }) => path
912
+ ) ?? [];
2682
913
  const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
2683
914
  const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
2684
915
  const serviceWorker = manifest.background?.service_worker;
2685
916
  const htmlPages = htmlFiles(manifest);
2686
917
  const icons = [
2687
- Object.values(isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}),
2688
- Object.values(isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {})
918
+ Object.values(
919
+ isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}
920
+ ),
921
+ Object.values(
922
+ isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {}
923
+ )
2689
924
  ].flat();
2690
925
  let webAccessibleResources = [];
2691
926
  if (manifest.web_accessible_resources) {
2692
- const resources = await Promise.all(manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
2693
- if (["*", "**/*"].includes(r))
2694
- return void 0;
2695
- if (fg.isDynamicPattern(r))
2696
- return fg(r, options);
2697
- return r;
2698
- }));
2699
- webAccessibleResources = resources.flat().filter(isString);
927
+ const resources = await Promise.all(
928
+ manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
929
+ if (["*", "**/*"].includes(r))
930
+ return void 0;
931
+ if (fg.isDynamicPattern(r))
932
+ return fg(r, options);
933
+ return r;
934
+ })
935
+ );
936
+ webAccessibleResources = [...new Set(resources.flat())].filter(isString);
2700
937
  }
2701
938
  return {
2702
939
  contentScripts: [...new Set(contentScripts)].filter(isString),
@@ -2748,66 +985,73 @@ const pluginFileWriterPublic = () => {
2748
985
  _debug("file-writer").extend("hmr");
2749
986
  const isCrxHMRPayload = (p) => p.type === "custom" && p.event.startsWith("crx:");
2750
987
  const hmrPayload$ = new Subject();
2751
- const crxHMRPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buffer(allFilesReady$), mergeMap((pps) => {
2752
- let fullReload;
2753
- const payloads = [];
2754
- for (const p of pps)
2755
- if (p.type === "full-reload") {
2756
- fullReload = p;
2757
- } else {
2758
- payloads.push(p);
2759
- }
2760
- if (fullReload)
2761
- payloads.push(fullReload);
2762
- return payloads;
2763
- }), map((p) => {
2764
- switch (p.type) {
2765
- case "full-reload": {
2766
- const fullReload = {
2767
- type: "full-reload",
2768
- path: p.path && getViteUrl({ id: p.path, type: "module" })
2769
- };
2770
- return fullReload;
2771
- }
2772
- case "prune": {
2773
- const prune = {
2774
- type: "prune",
2775
- paths: p.paths.map((id) => getViteUrl({ id, type: "module" }))
2776
- };
2777
- return prune;
2778
- }
2779
- case "update": {
2780
- const update = {
2781
- type: "update",
2782
- updates: p.updates.map(({ acceptedPath: ap, path: p2, ...rest }) => ({
2783
- ...rest,
2784
- acceptedPath: prefix$1("/", getFileName({ id: ap, type: "module" })),
2785
- path: prefix$1("/", getFileName({ id: p2, type: "module" }))
2786
- }))
2787
- };
2788
- return update;
988
+ const crxHMRPayload$ = hmrPayload$.pipe(
989
+ filter((p) => !isCrxHMRPayload(p)),
990
+ buffer(allFilesReady$),
991
+ mergeMap((pps) => {
992
+ let fullReload;
993
+ const payloads = [];
994
+ for (const p of pps)
995
+ if (p.type === "full-reload") {
996
+ fullReload = p;
997
+ } else {
998
+ payloads.push(p);
999
+ }
1000
+ if (fullReload)
1001
+ payloads.push(fullReload);
1002
+ return payloads;
1003
+ }),
1004
+ map((p) => {
1005
+ switch (p.type) {
1006
+ case "full-reload": {
1007
+ const fullReload = {
1008
+ type: "full-reload",
1009
+ path: p.path && getViteUrl({ id: p.path, type: "module" })
1010
+ };
1011
+ return fullReload;
1012
+ }
1013
+ case "prune": {
1014
+ const prune = {
1015
+ type: "prune",
1016
+ paths: p.paths.map((id) => getViteUrl({ id, type: "module" }))
1017
+ };
1018
+ return prune;
1019
+ }
1020
+ case "update": {
1021
+ const update = {
1022
+ type: "update",
1023
+ updates: p.updates.map(({ acceptedPath: ap, path: p2, ...rest }) => ({
1024
+ ...rest,
1025
+ acceptedPath: prefix$1("/", getFileName({ id: ap, type: "module" })),
1026
+ path: prefix$1("/", getFileName({ id: p2, type: "module" }))
1027
+ }))
1028
+ };
1029
+ return update;
1030
+ }
1031
+ default:
1032
+ return p;
1033
+ }
1034
+ }),
1035
+ filter((p) => {
1036
+ switch (p.type) {
1037
+ case "full-reload":
1038
+ return typeof p.path === "undefined";
1039
+ case "prune":
1040
+ return p.paths.length > 0;
1041
+ case "update":
1042
+ return p.updates.length > 0;
1043
+ default:
1044
+ return true;
2789
1045
  }
2790
- default:
2791
- return p;
2792
- }
2793
- }), filter((p) => {
2794
- switch (p.type) {
2795
- case "full-reload":
2796
- return typeof p.path === "undefined";
2797
- case "prune":
2798
- return p.paths.length > 0;
2799
- case "update":
2800
- return p.updates.length > 0;
2801
- default:
2802
- return true;
2803
- }
2804
- }), map((data) => {
2805
- return {
2806
- type: "custom",
2807
- event: "crx:content-script-payload",
2808
- data
2809
- };
2810
- }));
1046
+ }),
1047
+ map((data) => {
1048
+ return {
1049
+ type: "custom",
1050
+ event: "crx:content-script-payload",
1051
+ data
1052
+ };
1053
+ })
1054
+ );
2811
1055
 
2812
1056
  function isImporter(file) {
2813
1057
  const seen = /* @__PURE__ */ new Set();
@@ -2847,7 +1091,6 @@ const pluginHMR = () => {
2847
1091
  server.hmr = {};
2848
1092
  server.hmr = server.hmr ?? {};
2849
1093
  server.hmr.host = "localhost";
2850
- server.hmr.port = server.hmr.port ?? await getPort({ port: portNumbers(5200, 5300) });
2851
1094
  return { server, ...config2 };
2852
1095
  },
2853
1096
  configResolved(_config) {
@@ -2877,9 +1120,11 @@ const pluginHMR = () => {
2877
1120
  server.ws.send = decoratedSend;
2878
1121
  subs = new Subscription(() => subs = new Subscription());
2879
1122
  subs.add(fileWriterError$.subscribe(send));
2880
- subs.add(crxHMRPayload$.subscribe((payload) => {
2881
- send(payload);
2882
- }));
1123
+ subs.add(
1124
+ crxHMRPayload$.subscribe((payload) => {
1125
+ send(payload);
1126
+ })
1127
+ );
2883
1128
  }
2884
1129
  },
2885
1130
  closeBundle() {
@@ -2920,7 +1165,9 @@ const pluginHMR = () => {
2920
1165
  if (type === "module" && _id !== "/@vite/client" && code.includes("createHotContext")) {
2921
1166
  const id = _id.replace(/t=\d+&/, "");
2922
1167
  const escaped = id.replace(/([?&.])/g, "\\$1");
2923
- const regexp = new RegExp(`(?<=createHotContext\\(")${escaped}(?="\\))`);
1168
+ const regexp = new RegExp(
1169
+ `(?<=createHotContext\\(")${escaped}(?="\\))`
1170
+ );
2924
1171
  const fileUrl = prefix$1("/", getFileName({ id, type }));
2925
1172
  const replaced = code.replace(regexp, fileUrl);
2926
1173
  return replaced;
@@ -3005,10 +1252,12 @@ const pluginHtmlInlineScripts = () => {
3005
1252
  const p = pages.get(key);
3006
1253
  if (p?.scripts.some(isInlineTag)) {
3007
1254
  const $ = load(html);
3008
- p.scripts.push(...$("script").toArray().map((el) => ({
3009
- tag: "script",
3010
- attrs: { src: $(el).attr("src"), type: "module" }
3011
- })));
1255
+ p.scripts.push(
1256
+ ...$("script").toArray().map((el) => ({
1257
+ tag: "script",
1258
+ attrs: { src: $(el).attr("src"), type: "module" }
1259
+ }))
1260
+ );
3012
1261
  $("script").remove();
3013
1262
  const loader2 = {
3014
1263
  tag: "script",
@@ -3081,7 +1330,9 @@ const pluginManifest = () => {
3081
1330
  const { manifest: _manifest } = await getOptions(config2);
3082
1331
  manifest = await (typeof _manifest === "function" ? _manifest(env) : _manifest);
3083
1332
  if (manifest.manifest_version !== 3)
3084
- throw new Error(`CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`);
1333
+ throw new Error(
1334
+ `CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`
1335
+ );
3085
1336
  if (env.command === "serve") {
3086
1337
  const {
3087
1338
  contentScripts: js,
@@ -3122,7 +1373,7 @@ const pluginManifest = () => {
3122
1373
  name: "crx:manifest-loader",
3123
1374
  enforce: "pre",
3124
1375
  buildStart(options) {
3125
- if (typeof options.input !== "undefined") {
1376
+ if (typeof options.input !== "undefined" && !("ssr" in this)) {
3126
1377
  refId = this.emitFile({
3127
1378
  type: "chunk",
3128
1379
  id: manifestId,
@@ -3186,7 +1437,9 @@ const pluginManifest = () => {
3186
1437
  configResolved(_config) {
3187
1438
  config = _config;
3188
1439
  const plugins2 = config.plugins;
3189
- const crx = plugins2.findIndex(({ name }) => name === "crx:manifest-post");
1440
+ const crx = plugins2.findIndex(
1441
+ ({ name }) => name === "crx:manifest-post"
1442
+ );
3190
1443
  const [plugin] = plugins2.splice(crx, 1);
3191
1444
  plugins2.push(plugin);
3192
1445
  },
@@ -3209,13 +1462,16 @@ const pluginManifest = () => {
3209
1462
  if (manifest2.content_scripts)
3210
1463
  for (const { js = [], matches = [] } of manifest2.content_scripts)
3211
1464
  for (const id2 of js) {
3212
- contentScripts.set(prefix$1("/", id2), formatFileData({
3213
- type: "loader",
3214
- id: id2,
3215
- matches,
3216
- refId: hashScriptId({ type: "loader", id: id2 }),
3217
- fileName: getFileName({ type: "loader", id: id2 })
3218
- }));
1465
+ contentScripts.set(
1466
+ prefix$1("/", id2),
1467
+ formatFileData({
1468
+ type: "loader",
1469
+ id: id2,
1470
+ matches,
1471
+ refId: hashScriptId({ type: "loader", id: id2 }),
1472
+ fileName: getFileName({ type: "loader", id: id2 })
1473
+ })
1474
+ );
3219
1475
  }
3220
1476
  } else {
3221
1477
  if (manifest2.content_scripts)
@@ -3227,12 +1483,15 @@ const pluginManifest = () => {
3227
1483
  id: id2,
3228
1484
  name: basename(file)
3229
1485
  });
3230
- contentScripts.set(file, formatFileData({
3231
- type: "loader",
3232
- id: file,
3233
- refId: refId2,
3234
- matches
3235
- }));
1486
+ contentScripts.set(
1487
+ file,
1488
+ formatFileData({
1489
+ type: "loader",
1490
+ id: file,
1491
+ refId: refId2,
1492
+ matches
1493
+ })
1494
+ );
3236
1495
  }
3237
1496
  if (manifest2.background?.service_worker) {
3238
1497
  const file = manifest2.background.service_worker;
@@ -3263,7 +1522,9 @@ const pluginManifest = () => {
3263
1522
  if (config.command === "serve") {
3264
1523
  if (manifest2.content_scripts)
3265
1524
  for (const script of manifest2.content_scripts) {
3266
- script.js = script.js?.map((id) => getFileName({ id, type: "loader" }));
1525
+ script.js = script.js?.map(
1526
+ (id) => getFileName({ id, type: "loader" })
1527
+ );
3267
1528
  }
3268
1529
  } else {
3269
1530
  if (manifest2.background?.service_worker) {
@@ -3271,18 +1532,22 @@ const pluginManifest = () => {
3271
1532
  const name = this.getFileName(ref);
3272
1533
  manifest2.background.service_worker = name;
3273
1534
  }
3274
- manifest2.content_scripts = manifest2.content_scripts?.map(({ js = [], ...rest }) => {
3275
- return {
3276
- js: js.map((id) => {
3277
- const script = contentScripts.get(id);
3278
- const fileName = script?.loaderName ?? script?.fileName;
3279
- if (typeof fileName === "undefined")
3280
- throw new Error(`Content script fileName is undefined: "${id}"`);
3281
- return fileName;
3282
- }),
3283
- ...rest
3284
- };
3285
- });
1535
+ manifest2.content_scripts = manifest2.content_scripts?.map(
1536
+ ({ js = [], ...rest }) => {
1537
+ return {
1538
+ js: js.map((id) => {
1539
+ const script = contentScripts.get(id);
1540
+ const fileName = script?.loaderName ?? script?.fileName;
1541
+ if (typeof fileName === "undefined")
1542
+ throw new Error(
1543
+ `Content script fileName is undefined: "${id}"`
1544
+ );
1545
+ return fileName;
1546
+ }),
1547
+ ...rest
1548
+ };
1549
+ }
1550
+ );
3286
1551
  }
3287
1552
  for (const plugin of plugins) {
3288
1553
  try {
@@ -3293,7 +1558,9 @@ const pluginManifest = () => {
3293
1558
  const name = `[${plugin.name}]`;
3294
1559
  let message = error;
3295
1560
  if (error instanceof Error) {
3296
- message = colors.red(`${name} ${error.stack ? error.stack : error.message}`);
1561
+ message = colors.red(
1562
+ `${name} ${error.stack ? error.stack : error.message}`
1563
+ );
3297
1564
  } else if (typeof error === "string") {
3298
1565
  message = colors.red(`${name} ${error}`);
3299
1566
  }
@@ -3308,23 +1575,27 @@ const pluginManifest = () => {
3308
1575
  "webAccessibleResources"
3309
1576
  ];
3310
1577
  const files = await manifestFiles(manifest2, { cwd: config.root });
3311
- await Promise.all(assetTypes.map((k) => files[k]).flat().map(async (f) => {
3312
- if (typeof bundle[f] === "undefined") {
3313
- let filename = join(config.root, f);
3314
- if (!existsSync(filename))
3315
- filename = join(config.publicDir, f);
3316
- if (!existsSync(filename))
3317
- throw new Error(`ENOENT: Could not load manifest asset "${f}".
1578
+ await Promise.all(
1579
+ assetTypes.map((k) => files[k]).flat().map(async (f) => {
1580
+ if (typeof bundle[f] === "undefined") {
1581
+ let filename = join(config.root, f);
1582
+ if (!existsSync(filename))
1583
+ filename = join(config.publicDir, f);
1584
+ if (!existsSync(filename))
1585
+ throw new Error(
1586
+ `ENOENT: Could not load manifest asset "${f}".
3318
1587
  Manifest assets must exist in one of these directories:
3319
1588
  Project root: "${config.root}"
3320
- Public dir: "${config.publicDir}"`);
3321
- this.emitFile({
3322
- type: "asset",
3323
- fileName: f,
3324
- source: await readFile(filename)
3325
- });
3326
- }
3327
- }));
1589
+ Public dir: "${config.publicDir}"`
1590
+ );
1591
+ this.emitFile({
1592
+ type: "asset",
1593
+ fileName: f,
1594
+ source: await readFile(filename)
1595
+ });
1596
+ }
1597
+ })
1598
+ );
3328
1599
  if (config.command === "serve" && files.html.length) {
3329
1600
  const refId2 = this.emitFile({
3330
1601
  type: "asset",
@@ -3332,11 +1603,16 @@ Public dir: "${config.publicDir}"`);
3332
1603
  source: precontrollerJs
3333
1604
  });
3334
1605
  const precontrollerJsName = this.getFileName(refId2);
3335
- files.html.map((f) => this.emitFile({
3336
- type: "asset",
3337
- fileName: f,
3338
- source: precontrollerHtml.replace("%SCRIPT%", `/${precontrollerJsName}`)
3339
- }));
1606
+ files.html.map(
1607
+ (f) => this.emitFile({
1608
+ type: "asset",
1609
+ fileName: f,
1610
+ source: precontrollerHtml.replace(
1611
+ "%SCRIPT%",
1612
+ `/${precontrollerJsName}`
1613
+ )
1614
+ })
1615
+ );
3340
1616
  }
3341
1617
  const manifestJson = bundle["manifest.json"];
3342
1618
  if (typeof manifestJson === "undefined") {
@@ -3381,7 +1657,11 @@ function compileFileResources(fileName, {
3381
1657
  throw new Error(`Content script fileName for ${m} is undefined`);
3382
1658
  } else {
3383
1659
  resources.imports.add(script.fileName);
3384
- compileFileResources(script.fileName, { chunks, files, config }, resources);
1660
+ compileFileResources(
1661
+ script.fileName,
1662
+ { chunks, files, config },
1663
+ resources
1664
+ );
3385
1665
  }
3386
1666
  }
3387
1667
  }
@@ -3464,7 +1744,10 @@ const pluginWebAccessibleResources = () => {
3464
1744
  dynamicScriptMatches.add("https://*/*");
3465
1745
  }
3466
1746
  if (contentScripts.size > 0) {
3467
- const viteManifest = parseJsonAsset(bundle, "manifest.json");
1747
+ const viteManifest = parseJsonAsset(
1748
+ bundle,
1749
+ "manifest.json"
1750
+ );
3468
1751
  const viteFiles = /* @__PURE__ */ new Map();
3469
1752
  for (const [, file] of Object.entries(viteManifest))
3470
1753
  viteFiles.set(file.file, file);
@@ -3482,9 +1765,14 @@ const pluginWebAccessibleResources = () => {
3482
1765
  if (key === id) {
3483
1766
  if (isDynamicScript || matches.length)
3484
1767
  if (typeof fileName === "undefined") {
3485
- throw new Error(`Content script filename is undefined for "${id}"`);
1768
+ throw new Error(
1769
+ `Content script filename is undefined for "${id}"`
1770
+ );
3486
1771
  } else {
3487
- const { assets, css, imports } = compileFileResources(fileName, { chunks: bundleChunks, files: viteFiles, config });
1772
+ const { assets, css, imports } = compileFileResources(
1773
+ fileName,
1774
+ { chunks: bundleChunks, files: viteFiles, config }
1775
+ );
3488
1776
  contentScripts.get(key).css = [...css];
3489
1777
  if (type === "loader")
3490
1778
  imports.add(fileName);
@@ -3500,7 +1788,9 @@ const pluginWebAccessibleResources = () => {
3500
1788
  if (type === "module") {
3501
1789
  moduleScriptResources.set(fileName, resource);
3502
1790
  } else {
3503
- resource.matches = resource.matches.map(getMatchPatternOrigin);
1791
+ resource.matches = resource.matches.map(
1792
+ getMatchPatternOrigin
1793
+ );
3504
1794
  web_accessible_resources.push(resource);
3505
1795
  }
3506
1796
  }