@rpgjs/server 5.0.0-alpha.43 → 5.0.0-alpha.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3965 @@
1
+ var __defProp$5 = Object.defineProperty;
2
+ var __name$2 = (target, value) => __defProp$5(target, "name", { value, configurable: true });
3
+
4
+ /******************************************************************************
5
+ Copyright (c) Microsoft Corporation.
6
+
7
+ Permission to use, copy, modify, and/or distribute this software for any
8
+ purpose with or without fee is hereby granted.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
+ PERFORMANCE OF THIS SOFTWARE.
17
+ ***************************************************************************** */
18
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
19
+
20
+ var extendStatics = function(d, b) {
21
+ extendStatics = Object.setPrototypeOf ||
22
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
23
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
24
+ return extendStatics(d, b);
25
+ };
26
+
27
+ function __extends(d, b) {
28
+ if (typeof b !== "function" && b !== null)
29
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
30
+ extendStatics(d, b);
31
+ function __() { this.constructor = d; }
32
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
33
+ }
34
+
35
+ function __awaiter(thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ }
44
+
45
+ function __generator(thisArg, body) {
46
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
47
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
48
+ function verb(n) { return function (v) { return step([n, v]); }; }
49
+ function step(op) {
50
+ if (f) throw new TypeError("Generator is already executing.");
51
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
52
+ 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;
53
+ if (y = 0, t) op = [op[0] & 2, t.value];
54
+ switch (op[0]) {
55
+ case 0: case 1: t = op; break;
56
+ case 4: _.label++; return { value: op[1], done: false };
57
+ case 5: _.label++; y = op[1]; op = [0]; continue;
58
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
59
+ default:
60
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
61
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
62
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
63
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
64
+ if (t[2]) _.ops.pop();
65
+ _.trys.pop(); continue;
66
+ }
67
+ op = body.call(thisArg, _);
68
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
69
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
70
+ }
71
+ }
72
+
73
+ function __values(o) {
74
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
75
+ if (m) return m.call(o);
76
+ if (o && typeof o.length === "number") return {
77
+ next: function () {
78
+ if (o && i >= o.length) o = void 0;
79
+ return { value: o && o[i++], done: !o };
80
+ }
81
+ };
82
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
83
+ }
84
+
85
+ function __read(o, n) {
86
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
87
+ if (!m) return o;
88
+ var i = m.call(o), r, ar = [], e;
89
+ try {
90
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
91
+ }
92
+ catch (error) { e = { error: error }; }
93
+ finally {
94
+ try {
95
+ if (r && !r.done && (m = i["return"])) m.call(i);
96
+ }
97
+ finally { if (e) throw e.error; }
98
+ }
99
+ return ar;
100
+ }
101
+
102
+ function __spreadArray(to, from, pack) {
103
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
104
+ if (ar || !(i in from)) {
105
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
106
+ ar[i] = from[i];
107
+ }
108
+ }
109
+ return to.concat(ar || Array.prototype.slice.call(from));
110
+ }
111
+
112
+ function __await(v) {
113
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
114
+ }
115
+
116
+ function __asyncGenerator(thisArg, _arguments, generator) {
117
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
118
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
119
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
120
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
121
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
122
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
123
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
124
+ function fulfill(value) { resume("next", value); }
125
+ function reject(value) { resume("throw", value); }
126
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
127
+ }
128
+
129
+ function __asyncValues(o) {
130
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
131
+ var m = o[Symbol.asyncIterator], i;
132
+ 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);
133
+ 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); }); }; }
134
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
135
+ }
136
+
137
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
138
+ var e = new Error(message);
139
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
140
+ };
141
+
142
+ function isFunction$1(value) {
143
+ return typeof value === 'function';
144
+ }
145
+
146
+ function createErrorClass(createImpl) {
147
+ var _super = function (instance) {
148
+ Error.call(instance);
149
+ instance.stack = new Error().stack;
150
+ };
151
+ var ctorFunc = createImpl(_super);
152
+ ctorFunc.prototype = Object.create(Error.prototype);
153
+ ctorFunc.prototype.constructor = ctorFunc;
154
+ return ctorFunc;
155
+ }
156
+
157
+ var UnsubscriptionError = createErrorClass(function (_super) {
158
+ return function UnsubscriptionErrorImpl(errors) {
159
+ _super(this);
160
+ this.message = errors
161
+ ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
162
+ : '';
163
+ this.name = 'UnsubscriptionError';
164
+ this.errors = errors;
165
+ };
166
+ });
167
+
168
+ function arrRemove(arr, item) {
169
+ if (arr) {
170
+ var index = arr.indexOf(item);
171
+ 0 <= index && arr.splice(index, 1);
172
+ }
173
+ }
174
+
175
+ var Subscription = (function () {
176
+ function Subscription(initialTeardown) {
177
+ this.initialTeardown = initialTeardown;
178
+ this.closed = false;
179
+ this._parentage = null;
180
+ this._finalizers = null;
181
+ }
182
+ Subscription.prototype.unsubscribe = function () {
183
+ var e_1, _a, e_2, _b;
184
+ var errors;
185
+ if (!this.closed) {
186
+ this.closed = true;
187
+ var _parentage = this._parentage;
188
+ if (_parentage) {
189
+ this._parentage = null;
190
+ if (Array.isArray(_parentage)) {
191
+ try {
192
+ for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
193
+ var parent_1 = _parentage_1_1.value;
194
+ parent_1.remove(this);
195
+ }
196
+ }
197
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
198
+ finally {
199
+ try {
200
+ if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
201
+ }
202
+ finally { if (e_1) throw e_1.error; }
203
+ }
204
+ }
205
+ else {
206
+ _parentage.remove(this);
207
+ }
208
+ }
209
+ var initialFinalizer = this.initialTeardown;
210
+ if (isFunction$1(initialFinalizer)) {
211
+ try {
212
+ initialFinalizer();
213
+ }
214
+ catch (e) {
215
+ errors = e instanceof UnsubscriptionError ? e.errors : [e];
216
+ }
217
+ }
218
+ var _finalizers = this._finalizers;
219
+ if (_finalizers) {
220
+ this._finalizers = null;
221
+ try {
222
+ for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
223
+ var finalizer = _finalizers_1_1.value;
224
+ try {
225
+ execFinalizer(finalizer);
226
+ }
227
+ catch (err) {
228
+ errors = errors !== null && errors !== void 0 ? errors : [];
229
+ if (err instanceof UnsubscriptionError) {
230
+ errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
231
+ }
232
+ else {
233
+ errors.push(err);
234
+ }
235
+ }
236
+ }
237
+ }
238
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
239
+ finally {
240
+ try {
241
+ if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
242
+ }
243
+ finally { if (e_2) throw e_2.error; }
244
+ }
245
+ }
246
+ if (errors) {
247
+ throw new UnsubscriptionError(errors);
248
+ }
249
+ }
250
+ };
251
+ Subscription.prototype.add = function (teardown) {
252
+ var _a;
253
+ if (teardown && teardown !== this) {
254
+ if (this.closed) {
255
+ execFinalizer(teardown);
256
+ }
257
+ else {
258
+ if (teardown instanceof Subscription) {
259
+ if (teardown.closed || teardown._hasParent(this)) {
260
+ return;
261
+ }
262
+ teardown._addParent(this);
263
+ }
264
+ (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
265
+ }
266
+ }
267
+ };
268
+ Subscription.prototype._hasParent = function (parent) {
269
+ var _parentage = this._parentage;
270
+ return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
271
+ };
272
+ Subscription.prototype._addParent = function (parent) {
273
+ var _parentage = this._parentage;
274
+ this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
275
+ };
276
+ Subscription.prototype._removeParent = function (parent) {
277
+ var _parentage = this._parentage;
278
+ if (_parentage === parent) {
279
+ this._parentage = null;
280
+ }
281
+ else if (Array.isArray(_parentage)) {
282
+ arrRemove(_parentage, parent);
283
+ }
284
+ };
285
+ Subscription.prototype.remove = function (teardown) {
286
+ var _finalizers = this._finalizers;
287
+ _finalizers && arrRemove(_finalizers, teardown);
288
+ if (teardown instanceof Subscription) {
289
+ teardown._removeParent(this);
290
+ }
291
+ };
292
+ Subscription.EMPTY = (function () {
293
+ var empty = new Subscription();
294
+ empty.closed = true;
295
+ return empty;
296
+ })();
297
+ return Subscription;
298
+ }());
299
+ var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
300
+ function isSubscription(value) {
301
+ return (value instanceof Subscription ||
302
+ (value && 'closed' in value && isFunction$1(value.remove) && isFunction$1(value.add) && isFunction$1(value.unsubscribe)));
303
+ }
304
+ function execFinalizer(finalizer) {
305
+ if (isFunction$1(finalizer)) {
306
+ finalizer();
307
+ }
308
+ else {
309
+ finalizer.unsubscribe();
310
+ }
311
+ }
312
+
313
+ var config = {
314
+ Promise: undefined};
315
+
316
+ var timeoutProvider = {
317
+ setTimeout: function (handler, timeout) {
318
+ var args = [];
319
+ for (var _i = 2; _i < arguments.length; _i++) {
320
+ args[_i - 2] = arguments[_i];
321
+ }
322
+ return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
323
+ },
324
+ clearTimeout: function (handle) {
325
+ return (clearTimeout)(handle);
326
+ },
327
+ delegate: undefined,
328
+ };
329
+
330
+ function reportUnhandledError(err) {
331
+ timeoutProvider.setTimeout(function () {
332
+ {
333
+ throw err;
334
+ }
335
+ });
336
+ }
337
+
338
+ function noop() { }
339
+
340
+ function errorContext(cb) {
341
+ {
342
+ cb();
343
+ }
344
+ }
345
+
346
+ var Subscriber = (function (_super) {
347
+ __extends(Subscriber, _super);
348
+ function Subscriber(destination) {
349
+ var _this = _super.call(this) || this;
350
+ _this.isStopped = false;
351
+ if (destination) {
352
+ _this.destination = destination;
353
+ if (isSubscription(destination)) {
354
+ destination.add(_this);
355
+ }
356
+ }
357
+ else {
358
+ _this.destination = EMPTY_OBSERVER;
359
+ }
360
+ return _this;
361
+ }
362
+ Subscriber.create = function (next, error, complete) {
363
+ return new SafeSubscriber(next, error, complete);
364
+ };
365
+ Subscriber.prototype.next = function (value) {
366
+ if (this.isStopped) ;
367
+ else {
368
+ this._next(value);
369
+ }
370
+ };
371
+ Subscriber.prototype.error = function (err) {
372
+ if (this.isStopped) ;
373
+ else {
374
+ this.isStopped = true;
375
+ this._error(err);
376
+ }
377
+ };
378
+ Subscriber.prototype.complete = function () {
379
+ if (this.isStopped) ;
380
+ else {
381
+ this.isStopped = true;
382
+ this._complete();
383
+ }
384
+ };
385
+ Subscriber.prototype.unsubscribe = function () {
386
+ if (!this.closed) {
387
+ this.isStopped = true;
388
+ _super.prototype.unsubscribe.call(this);
389
+ this.destination = null;
390
+ }
391
+ };
392
+ Subscriber.prototype._next = function (value) {
393
+ this.destination.next(value);
394
+ };
395
+ Subscriber.prototype._error = function (err) {
396
+ try {
397
+ this.destination.error(err);
398
+ }
399
+ finally {
400
+ this.unsubscribe();
401
+ }
402
+ };
403
+ Subscriber.prototype._complete = function () {
404
+ try {
405
+ this.destination.complete();
406
+ }
407
+ finally {
408
+ this.unsubscribe();
409
+ }
410
+ };
411
+ return Subscriber;
412
+ }(Subscription));
413
+ var ConsumerObserver = (function () {
414
+ function ConsumerObserver(partialObserver) {
415
+ this.partialObserver = partialObserver;
416
+ }
417
+ ConsumerObserver.prototype.next = function (value) {
418
+ var partialObserver = this.partialObserver;
419
+ if (partialObserver.next) {
420
+ try {
421
+ partialObserver.next(value);
422
+ }
423
+ catch (error) {
424
+ handleUnhandledError(error);
425
+ }
426
+ }
427
+ };
428
+ ConsumerObserver.prototype.error = function (err) {
429
+ var partialObserver = this.partialObserver;
430
+ if (partialObserver.error) {
431
+ try {
432
+ partialObserver.error(err);
433
+ }
434
+ catch (error) {
435
+ handleUnhandledError(error);
436
+ }
437
+ }
438
+ else {
439
+ handleUnhandledError(err);
440
+ }
441
+ };
442
+ ConsumerObserver.prototype.complete = function () {
443
+ var partialObserver = this.partialObserver;
444
+ if (partialObserver.complete) {
445
+ try {
446
+ partialObserver.complete();
447
+ }
448
+ catch (error) {
449
+ handleUnhandledError(error);
450
+ }
451
+ }
452
+ };
453
+ return ConsumerObserver;
454
+ }());
455
+ var SafeSubscriber = (function (_super) {
456
+ __extends(SafeSubscriber, _super);
457
+ function SafeSubscriber(observerOrNext, error, complete) {
458
+ var _this = _super.call(this) || this;
459
+ var partialObserver;
460
+ if (isFunction$1(observerOrNext) || !observerOrNext) {
461
+ partialObserver = {
462
+ next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),
463
+ error: error !== null && error !== void 0 ? error : undefined,
464
+ complete: complete !== null && complete !== void 0 ? complete : undefined,
465
+ };
466
+ }
467
+ else {
468
+ {
469
+ partialObserver = observerOrNext;
470
+ }
471
+ }
472
+ _this.destination = new ConsumerObserver(partialObserver);
473
+ return _this;
474
+ }
475
+ return SafeSubscriber;
476
+ }(Subscriber));
477
+ function handleUnhandledError(error) {
478
+ {
479
+ reportUnhandledError(error);
480
+ }
481
+ }
482
+ function defaultErrorHandler(err) {
483
+ throw err;
484
+ }
485
+ var EMPTY_OBSERVER = {
486
+ closed: true,
487
+ next: noop,
488
+ error: defaultErrorHandler,
489
+ complete: noop,
490
+ };
491
+
492
+ var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
493
+
494
+ function identity(x) {
495
+ return x;
496
+ }
497
+
498
+ function pipeFromArray(fns) {
499
+ if (fns.length === 0) {
500
+ return identity;
501
+ }
502
+ if (fns.length === 1) {
503
+ return fns[0];
504
+ }
505
+ return function piped(input) {
506
+ return fns.reduce(function (prev, fn) { return fn(prev); }, input);
507
+ };
508
+ }
509
+
510
+ var Observable = (function () {
511
+ function Observable(subscribe) {
512
+ if (subscribe) {
513
+ this._subscribe = subscribe;
514
+ }
515
+ }
516
+ Observable.prototype.lift = function (operator) {
517
+ var observable = new Observable();
518
+ observable.source = this;
519
+ observable.operator = operator;
520
+ return observable;
521
+ };
522
+ Observable.prototype.subscribe = function (observerOrNext, error, complete) {
523
+ var _this = this;
524
+ var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
525
+ errorContext(function () {
526
+ var _a = _this, operator = _a.operator, source = _a.source;
527
+ subscriber.add(operator
528
+ ?
529
+ operator.call(subscriber, source)
530
+ : source
531
+ ?
532
+ _this._subscribe(subscriber)
533
+ :
534
+ _this._trySubscribe(subscriber));
535
+ });
536
+ return subscriber;
537
+ };
538
+ Observable.prototype._trySubscribe = function (sink) {
539
+ try {
540
+ return this._subscribe(sink);
541
+ }
542
+ catch (err) {
543
+ sink.error(err);
544
+ }
545
+ };
546
+ Observable.prototype.forEach = function (next, promiseCtor) {
547
+ var _this = this;
548
+ promiseCtor = getPromiseCtor(promiseCtor);
549
+ return new promiseCtor(function (resolve, reject) {
550
+ var subscriber = new SafeSubscriber({
551
+ next: function (value) {
552
+ try {
553
+ next(value);
554
+ }
555
+ catch (err) {
556
+ reject(err);
557
+ subscriber.unsubscribe();
558
+ }
559
+ },
560
+ error: reject,
561
+ complete: resolve,
562
+ });
563
+ _this.subscribe(subscriber);
564
+ });
565
+ };
566
+ Observable.prototype._subscribe = function (subscriber) {
567
+ var _a;
568
+ return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
569
+ };
570
+ Observable.prototype[observable] = function () {
571
+ return this;
572
+ };
573
+ Observable.prototype.pipe = function () {
574
+ var operations = [];
575
+ for (var _i = 0; _i < arguments.length; _i++) {
576
+ operations[_i] = arguments[_i];
577
+ }
578
+ return pipeFromArray(operations)(this);
579
+ };
580
+ Observable.prototype.toPromise = function (promiseCtor) {
581
+ var _this = this;
582
+ promiseCtor = getPromiseCtor(promiseCtor);
583
+ return new promiseCtor(function (resolve, reject) {
584
+ var value;
585
+ _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
586
+ });
587
+ };
588
+ Observable.create = function (subscribe) {
589
+ return new Observable(subscribe);
590
+ };
591
+ return Observable;
592
+ }());
593
+ function getPromiseCtor(promiseCtor) {
594
+ var _a;
595
+ return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
596
+ }
597
+ function isObserver(value) {
598
+ return value && isFunction$1(value.next) && isFunction$1(value.error) && isFunction$1(value.complete);
599
+ }
600
+ function isSubscriber(value) {
601
+ return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
602
+ }
603
+
604
+ function hasLift(source) {
605
+ return isFunction$1(source === null || source === void 0 ? void 0 : source.lift);
606
+ }
607
+ function operate(init) {
608
+ return function (source) {
609
+ if (hasLift(source)) {
610
+ return source.lift(function (liftedSource) {
611
+ try {
612
+ return init(liftedSource, this);
613
+ }
614
+ catch (err) {
615
+ this.error(err);
616
+ }
617
+ });
618
+ }
619
+ throw new TypeError('Unable to lift unknown Observable type');
620
+ };
621
+ }
622
+
623
+ function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
624
+ return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
625
+ }
626
+ var OperatorSubscriber = (function (_super) {
627
+ __extends(OperatorSubscriber, _super);
628
+ function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
629
+ var _this = _super.call(this, destination) || this;
630
+ _this.onFinalize = onFinalize;
631
+ _this.shouldUnsubscribe = shouldUnsubscribe;
632
+ _this._next = onNext
633
+ ? function (value) {
634
+ try {
635
+ onNext(value);
636
+ }
637
+ catch (err) {
638
+ destination.error(err);
639
+ }
640
+ }
641
+ : _super.prototype._next;
642
+ _this._error = onError
643
+ ? function (err) {
644
+ try {
645
+ onError(err);
646
+ }
647
+ catch (err) {
648
+ destination.error(err);
649
+ }
650
+ finally {
651
+ this.unsubscribe();
652
+ }
653
+ }
654
+ : _super.prototype._error;
655
+ _this._complete = onComplete
656
+ ? function () {
657
+ try {
658
+ onComplete();
659
+ }
660
+ catch (err) {
661
+ destination.error(err);
662
+ }
663
+ finally {
664
+ this.unsubscribe();
665
+ }
666
+ }
667
+ : _super.prototype._complete;
668
+ return _this;
669
+ }
670
+ OperatorSubscriber.prototype.unsubscribe = function () {
671
+ var _a;
672
+ if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
673
+ var closed_1 = this.closed;
674
+ _super.prototype.unsubscribe.call(this);
675
+ !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
676
+ }
677
+ };
678
+ return OperatorSubscriber;
679
+ }(Subscriber));
680
+
681
+ var ObjectUnsubscribedError = createErrorClass(function (_super) {
682
+ return function ObjectUnsubscribedErrorImpl() {
683
+ _super(this);
684
+ this.name = 'ObjectUnsubscribedError';
685
+ this.message = 'object unsubscribed';
686
+ };
687
+ });
688
+
689
+ var Subject = (function (_super) {
690
+ __extends(Subject, _super);
691
+ function Subject() {
692
+ var _this = _super.call(this) || this;
693
+ _this.closed = false;
694
+ _this.currentObservers = null;
695
+ _this.observers = [];
696
+ _this.isStopped = false;
697
+ _this.hasError = false;
698
+ _this.thrownError = null;
699
+ return _this;
700
+ }
701
+ Subject.prototype.lift = function (operator) {
702
+ var subject = new AnonymousSubject(this, this);
703
+ subject.operator = operator;
704
+ return subject;
705
+ };
706
+ Subject.prototype._throwIfClosed = function () {
707
+ if (this.closed) {
708
+ throw new ObjectUnsubscribedError();
709
+ }
710
+ };
711
+ Subject.prototype.next = function (value) {
712
+ var _this = this;
713
+ errorContext(function () {
714
+ var e_1, _a;
715
+ _this._throwIfClosed();
716
+ if (!_this.isStopped) {
717
+ if (!_this.currentObservers) {
718
+ _this.currentObservers = Array.from(_this.observers);
719
+ }
720
+ try {
721
+ for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
722
+ var observer = _c.value;
723
+ observer.next(value);
724
+ }
725
+ }
726
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
727
+ finally {
728
+ try {
729
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
730
+ }
731
+ finally { if (e_1) throw e_1.error; }
732
+ }
733
+ }
734
+ });
735
+ };
736
+ Subject.prototype.error = function (err) {
737
+ var _this = this;
738
+ errorContext(function () {
739
+ _this._throwIfClosed();
740
+ if (!_this.isStopped) {
741
+ _this.hasError = _this.isStopped = true;
742
+ _this.thrownError = err;
743
+ var observers = _this.observers;
744
+ while (observers.length) {
745
+ observers.shift().error(err);
746
+ }
747
+ }
748
+ });
749
+ };
750
+ Subject.prototype.complete = function () {
751
+ var _this = this;
752
+ errorContext(function () {
753
+ _this._throwIfClosed();
754
+ if (!_this.isStopped) {
755
+ _this.isStopped = true;
756
+ var observers = _this.observers;
757
+ while (observers.length) {
758
+ observers.shift().complete();
759
+ }
760
+ }
761
+ });
762
+ };
763
+ Subject.prototype.unsubscribe = function () {
764
+ this.isStopped = this.closed = true;
765
+ this.observers = this.currentObservers = null;
766
+ };
767
+ Object.defineProperty(Subject.prototype, "observed", {
768
+ get: function () {
769
+ var _a;
770
+ return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
771
+ },
772
+ enumerable: false,
773
+ configurable: true
774
+ });
775
+ Subject.prototype._trySubscribe = function (subscriber) {
776
+ this._throwIfClosed();
777
+ return _super.prototype._trySubscribe.call(this, subscriber);
778
+ };
779
+ Subject.prototype._subscribe = function (subscriber) {
780
+ this._throwIfClosed();
781
+ this._checkFinalizedStatuses(subscriber);
782
+ return this._innerSubscribe(subscriber);
783
+ };
784
+ Subject.prototype._innerSubscribe = function (subscriber) {
785
+ var _this = this;
786
+ var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
787
+ if (hasError || isStopped) {
788
+ return EMPTY_SUBSCRIPTION;
789
+ }
790
+ this.currentObservers = null;
791
+ observers.push(subscriber);
792
+ return new Subscription(function () {
793
+ _this.currentObservers = null;
794
+ arrRemove(observers, subscriber);
795
+ });
796
+ };
797
+ Subject.prototype._checkFinalizedStatuses = function (subscriber) {
798
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
799
+ if (hasError) {
800
+ subscriber.error(thrownError);
801
+ }
802
+ else if (isStopped) {
803
+ subscriber.complete();
804
+ }
805
+ };
806
+ Subject.prototype.asObservable = function () {
807
+ var observable = new Observable();
808
+ observable.source = this;
809
+ return observable;
810
+ };
811
+ Subject.create = function (destination, source) {
812
+ return new AnonymousSubject(destination, source);
813
+ };
814
+ return Subject;
815
+ }(Observable));
816
+ var AnonymousSubject = (function (_super) {
817
+ __extends(AnonymousSubject, _super);
818
+ function AnonymousSubject(destination, source) {
819
+ var _this = _super.call(this) || this;
820
+ _this.destination = destination;
821
+ _this.source = source;
822
+ return _this;
823
+ }
824
+ AnonymousSubject.prototype.next = function (value) {
825
+ var _a, _b;
826
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
827
+ };
828
+ AnonymousSubject.prototype.error = function (err) {
829
+ var _a, _b;
830
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
831
+ };
832
+ AnonymousSubject.prototype.complete = function () {
833
+ var _a, _b;
834
+ (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
835
+ };
836
+ AnonymousSubject.prototype._subscribe = function (subscriber) {
837
+ var _a, _b;
838
+ return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
839
+ };
840
+ return AnonymousSubject;
841
+ }(Subject));
842
+
843
+ var BehaviorSubject = (function (_super) {
844
+ __extends(BehaviorSubject, _super);
845
+ function BehaviorSubject(_value) {
846
+ var _this = _super.call(this) || this;
847
+ _this._value = _value;
848
+ return _this;
849
+ }
850
+ Object.defineProperty(BehaviorSubject.prototype, "value", {
851
+ get: function () {
852
+ return this.getValue();
853
+ },
854
+ enumerable: false,
855
+ configurable: true
856
+ });
857
+ BehaviorSubject.prototype._subscribe = function (subscriber) {
858
+ var subscription = _super.prototype._subscribe.call(this, subscriber);
859
+ !subscription.closed && subscriber.next(this._value);
860
+ return subscription;
861
+ };
862
+ BehaviorSubject.prototype.getValue = function () {
863
+ var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
864
+ if (hasError) {
865
+ throw thrownError;
866
+ }
867
+ this._throwIfClosed();
868
+ return _value;
869
+ };
870
+ BehaviorSubject.prototype.next = function (value) {
871
+ _super.prototype.next.call(this, (this._value = value));
872
+ };
873
+ return BehaviorSubject;
874
+ }(Subject));
875
+
876
+ function isScheduler(value) {
877
+ return value && isFunction$1(value.schedule);
878
+ }
879
+
880
+ function last(arr) {
881
+ return arr[arr.length - 1];
882
+ }
883
+ function popResultSelector(args) {
884
+ return isFunction$1(last(args)) ? args.pop() : undefined;
885
+ }
886
+ function popScheduler(args) {
887
+ return isScheduler(last(args)) ? args.pop() : undefined;
888
+ }
889
+
890
+ var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
891
+
892
+ function isPromise(value) {
893
+ return isFunction$1(value === null || value === void 0 ? void 0 : value.then);
894
+ }
895
+
896
+ function isInteropObservable(input) {
897
+ return isFunction$1(input[observable]);
898
+ }
899
+
900
+ function isAsyncIterable(obj) {
901
+ return Symbol.asyncIterator && isFunction$1(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
902
+ }
903
+
904
+ function createInvalidObservableTypeError(input) {
905
+ 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.");
906
+ }
907
+
908
+ function getSymbolIterator() {
909
+ if (typeof Symbol !== 'function' || !Symbol.iterator) {
910
+ return '@@iterator';
911
+ }
912
+ return Symbol.iterator;
913
+ }
914
+ var iterator = getSymbolIterator();
915
+
916
+ function isIterable(input) {
917
+ return isFunction$1(input === null || input === void 0 ? void 0 : input[iterator]);
918
+ }
919
+
920
+ function readableStreamLikeToAsyncGenerator(readableStream) {
921
+ return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
922
+ var reader, _a, value, done;
923
+ return __generator(this, function (_b) {
924
+ switch (_b.label) {
925
+ case 0:
926
+ reader = readableStream.getReader();
927
+ _b.label = 1;
928
+ case 1:
929
+ _b.trys.push([1, , 9, 10]);
930
+ _b.label = 2;
931
+ case 2:
932
+ return [4, __await(reader.read())];
933
+ case 3:
934
+ _a = _b.sent(), value = _a.value, done = _a.done;
935
+ if (!done) return [3, 5];
936
+ return [4, __await(void 0)];
937
+ case 4: return [2, _b.sent()];
938
+ case 5: return [4, __await(value)];
939
+ case 6: return [4, _b.sent()];
940
+ case 7:
941
+ _b.sent();
942
+ return [3, 2];
943
+ case 8: return [3, 10];
944
+ case 9:
945
+ reader.releaseLock();
946
+ return [7];
947
+ case 10: return [2];
948
+ }
949
+ });
950
+ });
951
+ }
952
+ function isReadableStreamLike(obj) {
953
+ return isFunction$1(obj === null || obj === void 0 ? void 0 : obj.getReader);
954
+ }
955
+
956
+ function innerFrom(input) {
957
+ if (input instanceof Observable) {
958
+ return input;
959
+ }
960
+ if (input != null) {
961
+ if (isInteropObservable(input)) {
962
+ return fromInteropObservable(input);
963
+ }
964
+ if (isArrayLike(input)) {
965
+ return fromArrayLike(input);
966
+ }
967
+ if (isPromise(input)) {
968
+ return fromPromise(input);
969
+ }
970
+ if (isAsyncIterable(input)) {
971
+ return fromAsyncIterable(input);
972
+ }
973
+ if (isIterable(input)) {
974
+ return fromIterable(input);
975
+ }
976
+ if (isReadableStreamLike(input)) {
977
+ return fromReadableStreamLike(input);
978
+ }
979
+ }
980
+ throw createInvalidObservableTypeError(input);
981
+ }
982
+ function fromInteropObservable(obj) {
983
+ return new Observable(function (subscriber) {
984
+ var obs = obj[observable]();
985
+ if (isFunction$1(obs.subscribe)) {
986
+ return obs.subscribe(subscriber);
987
+ }
988
+ throw new TypeError('Provided object does not correctly implement Symbol.observable');
989
+ });
990
+ }
991
+ function fromArrayLike(array) {
992
+ return new Observable(function (subscriber) {
993
+ for (var i = 0; i < array.length && !subscriber.closed; i++) {
994
+ subscriber.next(array[i]);
995
+ }
996
+ subscriber.complete();
997
+ });
998
+ }
999
+ function fromPromise(promise) {
1000
+ return new Observable(function (subscriber) {
1001
+ promise
1002
+ .then(function (value) {
1003
+ if (!subscriber.closed) {
1004
+ subscriber.next(value);
1005
+ subscriber.complete();
1006
+ }
1007
+ }, function (err) { return subscriber.error(err); })
1008
+ .then(null, reportUnhandledError);
1009
+ });
1010
+ }
1011
+ function fromIterable(iterable) {
1012
+ return new Observable(function (subscriber) {
1013
+ var e_1, _a;
1014
+ try {
1015
+ for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
1016
+ var value = iterable_1_1.value;
1017
+ subscriber.next(value);
1018
+ if (subscriber.closed) {
1019
+ return;
1020
+ }
1021
+ }
1022
+ }
1023
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1024
+ finally {
1025
+ try {
1026
+ if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
1027
+ }
1028
+ finally { if (e_1) throw e_1.error; }
1029
+ }
1030
+ subscriber.complete();
1031
+ });
1032
+ }
1033
+ function fromAsyncIterable(asyncIterable) {
1034
+ return new Observable(function (subscriber) {
1035
+ process$1(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
1036
+ });
1037
+ }
1038
+ function fromReadableStreamLike(readableStream) {
1039
+ return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1040
+ }
1041
+ function process$1(asyncIterable, subscriber) {
1042
+ var asyncIterable_1, asyncIterable_1_1;
1043
+ var e_2, _a;
1044
+ return __awaiter(this, void 0, void 0, function () {
1045
+ var value, e_2_1;
1046
+ return __generator(this, function (_b) {
1047
+ switch (_b.label) {
1048
+ case 0:
1049
+ _b.trys.push([0, 5, 6, 11]);
1050
+ asyncIterable_1 = __asyncValues(asyncIterable);
1051
+ _b.label = 1;
1052
+ case 1: return [4, asyncIterable_1.next()];
1053
+ case 2:
1054
+ if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
1055
+ value = asyncIterable_1_1.value;
1056
+ subscriber.next(value);
1057
+ if (subscriber.closed) {
1058
+ return [2];
1059
+ }
1060
+ _b.label = 3;
1061
+ case 3: return [3, 1];
1062
+ case 4: return [3, 11];
1063
+ case 5:
1064
+ e_2_1 = _b.sent();
1065
+ e_2 = { error: e_2_1 };
1066
+ return [3, 11];
1067
+ case 6:
1068
+ _b.trys.push([6, , 9, 10]);
1069
+ if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
1070
+ return [4, _a.call(asyncIterable_1)];
1071
+ case 7:
1072
+ _b.sent();
1073
+ _b.label = 8;
1074
+ case 8: return [3, 10];
1075
+ case 9:
1076
+ if (e_2) throw e_2.error;
1077
+ return [7];
1078
+ case 10: return [7];
1079
+ case 11:
1080
+ subscriber.complete();
1081
+ return [2];
1082
+ }
1083
+ });
1084
+ });
1085
+ }
1086
+
1087
+ function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
1088
+ if (delay === void 0) { delay = 0; }
1089
+ if (repeat === void 0) { repeat = false; }
1090
+ var scheduleSubscription = scheduler.schedule(function () {
1091
+ work();
1092
+ if (repeat) {
1093
+ parentSubscription.add(this.schedule(null, delay));
1094
+ }
1095
+ else {
1096
+ this.unsubscribe();
1097
+ }
1098
+ }, delay);
1099
+ parentSubscription.add(scheduleSubscription);
1100
+ if (!repeat) {
1101
+ return scheduleSubscription;
1102
+ }
1103
+ }
1104
+
1105
+ function observeOn(scheduler, delay) {
1106
+ if (delay === void 0) { delay = 0; }
1107
+ return operate(function (source, subscriber) {
1108
+ 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); }));
1109
+ });
1110
+ }
1111
+
1112
+ function subscribeOn(scheduler, delay) {
1113
+ if (delay === void 0) { delay = 0; }
1114
+ return operate(function (source, subscriber) {
1115
+ subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
1116
+ });
1117
+ }
1118
+
1119
+ function scheduleObservable(input, scheduler) {
1120
+ return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1121
+ }
1122
+
1123
+ function schedulePromise(input, scheduler) {
1124
+ return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1125
+ }
1126
+
1127
+ function scheduleArray(input, scheduler) {
1128
+ return new Observable(function (subscriber) {
1129
+ var i = 0;
1130
+ return scheduler.schedule(function () {
1131
+ if (i === input.length) {
1132
+ subscriber.complete();
1133
+ }
1134
+ else {
1135
+ subscriber.next(input[i++]);
1136
+ if (!subscriber.closed) {
1137
+ this.schedule();
1138
+ }
1139
+ }
1140
+ });
1141
+ });
1142
+ }
1143
+
1144
+ function scheduleIterable(input, scheduler) {
1145
+ return new Observable(function (subscriber) {
1146
+ var iterator$1;
1147
+ executeSchedule(subscriber, scheduler, function () {
1148
+ iterator$1 = input[iterator]();
1149
+ executeSchedule(subscriber, scheduler, function () {
1150
+ var _a;
1151
+ var value;
1152
+ var done;
1153
+ try {
1154
+ (_a = iterator$1.next(), value = _a.value, done = _a.done);
1155
+ }
1156
+ catch (err) {
1157
+ subscriber.error(err);
1158
+ return;
1159
+ }
1160
+ if (done) {
1161
+ subscriber.complete();
1162
+ }
1163
+ else {
1164
+ subscriber.next(value);
1165
+ }
1166
+ }, 0, true);
1167
+ });
1168
+ return function () { return isFunction$1(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return(); };
1169
+ });
1170
+ }
1171
+
1172
+ function scheduleAsyncIterable(input, scheduler) {
1173
+ if (!input) {
1174
+ throw new Error('Iterable cannot be null');
1175
+ }
1176
+ return new Observable(function (subscriber) {
1177
+ executeSchedule(subscriber, scheduler, function () {
1178
+ var iterator = input[Symbol.asyncIterator]();
1179
+ executeSchedule(subscriber, scheduler, function () {
1180
+ iterator.next().then(function (result) {
1181
+ if (result.done) {
1182
+ subscriber.complete();
1183
+ }
1184
+ else {
1185
+ subscriber.next(result.value);
1186
+ }
1187
+ });
1188
+ }, 0, true);
1189
+ });
1190
+ });
1191
+ }
1192
+
1193
+ function scheduleReadableStreamLike(input, scheduler) {
1194
+ return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
1195
+ }
1196
+
1197
+ function scheduled(input, scheduler) {
1198
+ if (input != null) {
1199
+ if (isInteropObservable(input)) {
1200
+ return scheduleObservable(input, scheduler);
1201
+ }
1202
+ if (isArrayLike(input)) {
1203
+ return scheduleArray(input, scheduler);
1204
+ }
1205
+ if (isPromise(input)) {
1206
+ return schedulePromise(input, scheduler);
1207
+ }
1208
+ if (isAsyncIterable(input)) {
1209
+ return scheduleAsyncIterable(input, scheduler);
1210
+ }
1211
+ if (isIterable(input)) {
1212
+ return scheduleIterable(input, scheduler);
1213
+ }
1214
+ if (isReadableStreamLike(input)) {
1215
+ return scheduleReadableStreamLike(input, scheduler);
1216
+ }
1217
+ }
1218
+ throw createInvalidObservableTypeError(input);
1219
+ }
1220
+
1221
+ function from(input, scheduler) {
1222
+ return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1223
+ }
1224
+
1225
+ function map(project, thisArg) {
1226
+ return operate(function (source, subscriber) {
1227
+ var index = 0;
1228
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1229
+ subscriber.next(project.call(thisArg, value, index++));
1230
+ }));
1231
+ });
1232
+ }
1233
+
1234
+ var isArray$1 = Array.isArray;
1235
+ function callOrApply(fn, args) {
1236
+ return isArray$1(args) ? fn.apply(void 0, __spreadArray([], __read(args))) : fn(args);
1237
+ }
1238
+ function mapOneOrManyArgs(fn) {
1239
+ return map(function (args) { return callOrApply(fn, args); });
1240
+ }
1241
+
1242
+ var isArray = Array.isArray;
1243
+ var getPrototypeOf = Object.getPrototypeOf, objectProto = Object.prototype, getKeys = Object.keys;
1244
+ function argsArgArrayOrObject(args) {
1245
+ if (args.length === 1) {
1246
+ var first_1 = args[0];
1247
+ if (isArray(first_1)) {
1248
+ return { args: first_1, keys: null };
1249
+ }
1250
+ if (isPOJO(first_1)) {
1251
+ var keys = getKeys(first_1);
1252
+ return {
1253
+ args: keys.map(function (key) { return first_1[key]; }),
1254
+ keys: keys,
1255
+ };
1256
+ }
1257
+ }
1258
+ return { args: args, keys: null };
1259
+ }
1260
+ function isPOJO(obj) {
1261
+ return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;
1262
+ }
1263
+
1264
+ function createObject(keys, values) {
1265
+ return keys.reduce(function (result, key, i) { return ((result[key] = values[i]), result); }, {});
1266
+ }
1267
+
1268
+ function combineLatest() {
1269
+ var args = [];
1270
+ for (var _i = 0; _i < arguments.length; _i++) {
1271
+ args[_i] = arguments[_i];
1272
+ }
1273
+ var scheduler = popScheduler(args);
1274
+ var resultSelector = popResultSelector(args);
1275
+ var _a = argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys;
1276
+ if (observables.length === 0) {
1277
+ return from([], scheduler);
1278
+ }
1279
+ var result = new Observable(combineLatestInit(observables, scheduler, keys
1280
+ ?
1281
+ function (values) { return createObject(keys, values); }
1282
+ :
1283
+ identity));
1284
+ return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;
1285
+ }
1286
+ function combineLatestInit(observables, scheduler, valueTransform) {
1287
+ if (valueTransform === void 0) { valueTransform = identity; }
1288
+ return function (subscriber) {
1289
+ maybeSchedule(scheduler, function () {
1290
+ var length = observables.length;
1291
+ var values = new Array(length);
1292
+ var active = length;
1293
+ var remainingFirstValues = length;
1294
+ var _loop_1 = function (i) {
1295
+ maybeSchedule(scheduler, function () {
1296
+ var source = from(observables[i], scheduler);
1297
+ var hasFirstValue = false;
1298
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1299
+ values[i] = value;
1300
+ if (!hasFirstValue) {
1301
+ hasFirstValue = true;
1302
+ remainingFirstValues--;
1303
+ }
1304
+ if (!remainingFirstValues) {
1305
+ subscriber.next(valueTransform(values.slice()));
1306
+ }
1307
+ }, function () {
1308
+ if (!--active) {
1309
+ subscriber.complete();
1310
+ }
1311
+ }));
1312
+ }, subscriber);
1313
+ };
1314
+ for (var i = 0; i < length; i++) {
1315
+ _loop_1(i);
1316
+ }
1317
+ }, subscriber);
1318
+ };
1319
+ }
1320
+ function maybeSchedule(scheduler, execute, subscription) {
1321
+ if (scheduler) {
1322
+ executeSchedule(subscription, scheduler, execute);
1323
+ }
1324
+ else {
1325
+ execute();
1326
+ }
1327
+ }
1328
+
1329
+ function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
1330
+ var buffer = [];
1331
+ var active = 0;
1332
+ var index = 0;
1333
+ var isComplete = false;
1334
+ var checkComplete = function () {
1335
+ if (isComplete && !buffer.length && !active) {
1336
+ subscriber.complete();
1337
+ }
1338
+ };
1339
+ var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
1340
+ var doInnerSub = function (value) {
1341
+ active++;
1342
+ var innerComplete = false;
1343
+ innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {
1344
+ {
1345
+ subscriber.next(innerValue);
1346
+ }
1347
+ }, function () {
1348
+ innerComplete = true;
1349
+ }, undefined, function () {
1350
+ if (innerComplete) {
1351
+ try {
1352
+ active--;
1353
+ var _loop_1 = function () {
1354
+ var bufferedValue = buffer.shift();
1355
+ if (innerSubScheduler) ;
1356
+ else {
1357
+ doInnerSub(bufferedValue);
1358
+ }
1359
+ };
1360
+ while (buffer.length && active < concurrent) {
1361
+ _loop_1();
1362
+ }
1363
+ checkComplete();
1364
+ }
1365
+ catch (err) {
1366
+ subscriber.error(err);
1367
+ }
1368
+ }
1369
+ }));
1370
+ };
1371
+ source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {
1372
+ isComplete = true;
1373
+ checkComplete();
1374
+ }));
1375
+ return function () {
1376
+ };
1377
+ }
1378
+
1379
+ function mergeMap(project, resultSelector, concurrent) {
1380
+ if (concurrent === void 0) { concurrent = Infinity; }
1381
+ if (isFunction$1(resultSelector)) {
1382
+ return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);
1383
+ }
1384
+ else if (typeof resultSelector === 'number') {
1385
+ concurrent = resultSelector;
1386
+ }
1387
+ return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });
1388
+ }
1389
+
1390
+ function filter(predicate, thisArg) {
1391
+ return operate(function (source, subscriber) {
1392
+ var index = 0;
1393
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
1394
+ });
1395
+ }
1396
+
1397
+ function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
1398
+ return function (source, subscriber) {
1399
+ var hasState = hasSeed;
1400
+ var state = seed;
1401
+ var index = 0;
1402
+ source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1403
+ var i = index++;
1404
+ state = hasState
1405
+ ?
1406
+ accumulator(state, value, i)
1407
+ :
1408
+ ((hasState = true), value);
1409
+ }, (function () {
1410
+ hasState && subscriber.next(state);
1411
+ subscriber.complete();
1412
+ })));
1413
+ };
1414
+ }
1415
+
1416
+ function reduce(accumulator, seed) {
1417
+ return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));
1418
+ }
1419
+
1420
+ var arrReducer = function (arr, value) { return (arr.push(value), arr); };
1421
+ function toArray() {
1422
+ return operate(function (source, subscriber) {
1423
+ reduce(arrReducer, [])(source).subscribe(subscriber);
1424
+ });
1425
+ }
1426
+
1427
+ function finalize(callback) {
1428
+ return operate(function (source, subscriber) {
1429
+ try {
1430
+ source.subscribe(subscriber);
1431
+ }
1432
+ finally {
1433
+ subscriber.add(callback);
1434
+ }
1435
+ });
1436
+ }
1437
+
1438
+ var __defProp$4 = Object.defineProperty;
1439
+ var __name$1 = (target, value) => __defProp$4(target, "name", { value, configurable: true });
1440
+ var ArraySubject = class extends BehaviorSubject {
1441
+ static {
1442
+ __name$1(this, "ArraySubject");
1443
+ }
1444
+ _items = [];
1445
+ constructor(items = []) {
1446
+ super({
1447
+ type: "init",
1448
+ items
1449
+ });
1450
+ this.createProxy(items);
1451
+ }
1452
+ createProxy(items) {
1453
+ this._items = new Proxy(items, {
1454
+ get: /* @__PURE__ */ __name$1((target, prop, receiver) => {
1455
+ const origMethod = target[prop];
1456
+ if (typeof origMethod === "function") {
1457
+ return (...args) => {
1458
+ let changeType = "update";
1459
+ let index = void 0;
1460
+ let isMutateFn = false;
1461
+ let itemsToEmit = [];
1462
+ let changeSplice = true;
1463
+ switch (prop) {
1464
+ case "push":
1465
+ index = target.length;
1466
+ changeType = "add";
1467
+ isMutateFn = true;
1468
+ break;
1469
+ case "pop":
1470
+ index = target.length - 1;
1471
+ changeType = "remove";
1472
+ isMutateFn = true;
1473
+ break;
1474
+ case "unshift":
1475
+ index = 0;
1476
+ changeType = "add";
1477
+ isMutateFn = true;
1478
+ break;
1479
+ case "shift":
1480
+ index = 0;
1481
+ changeType = "remove";
1482
+ isMutateFn = true;
1483
+ break;
1484
+ case "splice":
1485
+ index = args[0];
1486
+ const deleteCount = args[1];
1487
+ const newItems = args.slice(2);
1488
+ itemsToEmit = newItems;
1489
+ if (deleteCount > 0 && newItems.length === 0) {
1490
+ changeType = "remove";
1491
+ } else if (deleteCount === 0 && newItems.length > 0) {
1492
+ changeType = "add";
1493
+ } else if (deleteCount === 0 && newItems.length === 0) {
1494
+ changeSplice = false;
1495
+ } else {
1496
+ changeType = "update";
1497
+ }
1498
+ isMutateFn = true;
1499
+ break;
1500
+ }
1501
+ const result = origMethod.apply(target, args);
1502
+ if (isMutateFn && changeSplice) {
1503
+ if (prop === "splice") {
1504
+ this.next({
1505
+ type: changeType,
1506
+ index,
1507
+ items: itemsToEmit
1508
+ });
1509
+ } else {
1510
+ this.next({
1511
+ type: changeType,
1512
+ index,
1513
+ items: args
1514
+ });
1515
+ }
1516
+ }
1517
+ return result;
1518
+ };
1519
+ }
1520
+ return Reflect.get(target, prop, receiver);
1521
+ }, "get"),
1522
+ set: /* @__PURE__ */ __name$1((target, prop, value) => {
1523
+ const index = !isNaN(Number(prop)) ? Number(prop) : void 0;
1524
+ target[prop] = value;
1525
+ this.next({
1526
+ type: "update",
1527
+ index,
1528
+ items: [
1529
+ value
1530
+ ]
1531
+ });
1532
+ return true;
1533
+ }, "set")
1534
+ });
1535
+ }
1536
+ get items() {
1537
+ return this._items;
1538
+ }
1539
+ set items(newItems) {
1540
+ this.createProxy(newItems);
1541
+ this.next({
1542
+ type: "reset",
1543
+ items: newItems
1544
+ });
1545
+ }
1546
+ };
1547
+ var isArraySubject = /* @__PURE__ */ __name$1((value) => {
1548
+ return "_items" in value;
1549
+ }, "isArraySubject");
1550
+ var ObjectSubject = class extends BehaviorSubject {
1551
+ static {
1552
+ __name$1(this, "ObjectSubject");
1553
+ }
1554
+ _obj;
1555
+ constructor(obj = {}) {
1556
+ super({
1557
+ type: "init",
1558
+ value: obj
1559
+ });
1560
+ this.createProxy(obj);
1561
+ }
1562
+ createProxy(obj) {
1563
+ this._obj = new Proxy(obj, {
1564
+ get: /* @__PURE__ */ __name$1((target, prop, receiver) => {
1565
+ return Reflect.get(target, prop, receiver);
1566
+ }, "get"),
1567
+ set: /* @__PURE__ */ __name$1((target, prop, value, receiver) => {
1568
+ const key = prop;
1569
+ const changeType = key in target ? "update" : "add";
1570
+ target[key] = value;
1571
+ this.next({
1572
+ type: changeType,
1573
+ key,
1574
+ value
1575
+ });
1576
+ return true;
1577
+ }, "set"),
1578
+ deleteProperty: /* @__PURE__ */ __name$1((target, prop) => {
1579
+ const key = prop;
1580
+ if (key in target) {
1581
+ const value = target[key];
1582
+ delete target[key];
1583
+ this.next({
1584
+ type: "remove",
1585
+ key,
1586
+ value
1587
+ });
1588
+ return true;
1589
+ }
1590
+ return false;
1591
+ }, "deleteProperty")
1592
+ });
1593
+ }
1594
+ get obj() {
1595
+ return this._obj;
1596
+ }
1597
+ set obj(newObj) {
1598
+ this.createProxy(newObj);
1599
+ this.next({
1600
+ type: "reset",
1601
+ value: newObj
1602
+ });
1603
+ }
1604
+ };
1605
+ var isObjectSubject = /* @__PURE__ */ __name$1((value) => {
1606
+ return "_obj" in value;
1607
+ }, "isObjectSubject");
1608
+ var getGlobalReactiveStore = /* @__PURE__ */ __name$1(() => {
1609
+ const globalKey = "__REACTIVE_STORE__";
1610
+ if (typeof globalThis !== "undefined") {
1611
+ if (!globalThis[globalKey]) {
1612
+ globalThis[globalKey] = {
1613
+ currentDependencyTracker: null,
1614
+ currentSubscriptionsTracker: null
1615
+ };
1616
+ }
1617
+ return globalThis[globalKey];
1618
+ }
1619
+ let globalObj;
1620
+ if (typeof window !== "undefined") {
1621
+ globalObj = window;
1622
+ } else if (typeof process !== "undefined" && process.versions && process.versions.node) {
1623
+ globalObj = Function("return this")();
1624
+ } else if (typeof self !== "undefined") {
1625
+ globalObj = self;
1626
+ } else {
1627
+ console.warn("Unable to find global object, using local instance");
1628
+ return {
1629
+ currentDependencyTracker: null,
1630
+ currentSubscriptionsTracker: null
1631
+ };
1632
+ }
1633
+ if (!globalObj[globalKey]) {
1634
+ globalObj[globalKey] = {
1635
+ currentDependencyTracker: null,
1636
+ currentSubscriptionsTracker: null
1637
+ };
1638
+ }
1639
+ return globalObj[globalKey];
1640
+ }, "getGlobalReactiveStore");
1641
+ var reactiveStore = getGlobalReactiveStore();
1642
+ var trackDependency = /* @__PURE__ */ __name$1((signal2) => {
1643
+ if (reactiveStore.currentDependencyTracker) {
1644
+ reactiveStore.currentDependencyTracker(signal2);
1645
+ }
1646
+ }, "trackDependency");
1647
+ function signal(defaultValue, options) {
1648
+ let subject;
1649
+ if (Array.isArray(defaultValue)) {
1650
+ subject = new ArraySubject(defaultValue);
1651
+ } else if (typeof defaultValue === "object" && defaultValue !== null) {
1652
+ subject = new ObjectSubject(defaultValue);
1653
+ } else {
1654
+ subject = new BehaviorSubject(defaultValue);
1655
+ }
1656
+ const getValue = /* @__PURE__ */ __name$1(() => {
1657
+ if (subject instanceof ArraySubject) {
1658
+ return subject.items;
1659
+ } else if (subject instanceof ObjectSubject) {
1660
+ return subject.obj;
1661
+ }
1662
+ return subject.value;
1663
+ }, "getValue");
1664
+ const fn = /* @__PURE__ */ __name$1(function() {
1665
+ trackDependency(fn);
1666
+ return getValue();
1667
+ }, "fn");
1668
+ fn.set = (value) => {
1669
+ const currentValue = getValue();
1670
+ let shouldEmit = true;
1671
+ if (options?.equal) {
1672
+ shouldEmit = !options.equal(currentValue, value);
1673
+ } else {
1674
+ shouldEmit = currentValue !== value;
1675
+ }
1676
+ if (shouldEmit) {
1677
+ if (subject instanceof ArraySubject) {
1678
+ subject.items = value;
1679
+ } else if (subject instanceof ObjectSubject) {
1680
+ subject.obj = value;
1681
+ } else {
1682
+ subject.next(value);
1683
+ }
1684
+ }
1685
+ };
1686
+ fn._isFrozen = false;
1687
+ fn.freeze = () => {
1688
+ fn._isFrozen = true;
1689
+ };
1690
+ fn.unfreeze = () => {
1691
+ fn._isFrozen = false;
1692
+ if (subject instanceof ArraySubject) {
1693
+ subject.next({
1694
+ type: "init",
1695
+ items: subject.items
1696
+ });
1697
+ } else if (subject instanceof ObjectSubject) {
1698
+ subject.next({
1699
+ type: "init",
1700
+ value: subject.obj
1701
+ });
1702
+ } else {
1703
+ subject.next(subject.value);
1704
+ }
1705
+ };
1706
+ fn.mutate = (mutateFn) => {
1707
+ const value = getValue();
1708
+ mutateFn(value);
1709
+ };
1710
+ fn.update = (updateFn) => {
1711
+ const updatedValue = updateFn(getValue());
1712
+ fn.set(updatedValue);
1713
+ };
1714
+ fn.observable = subject.asObservable().pipe(filter(() => !fn._isFrozen));
1715
+ fn._subject = subject;
1716
+ return fn;
1717
+ }
1718
+ __name$1(signal, "signal");
1719
+ function isSignal(value) {
1720
+ return !!(value && value.observable);
1721
+ }
1722
+ __name$1(isSignal, "isSignal");
1723
+ function isComputed(value) {
1724
+ return isSignal(value) && !!value.dependencies;
1725
+ }
1726
+ __name$1(isComputed, "isComputed");
1727
+ function computed(computeFunction, disposableFn) {
1728
+ const dependencies = /* @__PURE__ */ new Set();
1729
+ let init = true;
1730
+ let lastComputedValue;
1731
+ const previousTracker = reactiveStore.currentDependencyTracker;
1732
+ reactiveStore.currentDependencyTracker = (signal2) => {
1733
+ dependencies.add(signal2);
1734
+ };
1735
+ lastComputedValue = computeFunction();
1736
+ if (computeFunction["isEffect"]) {
1737
+ disposableFn = lastComputedValue;
1738
+ }
1739
+ reactiveStore.currentDependencyTracker = previousTracker;
1740
+ const observables = [
1741
+ ...dependencies
1742
+ ].map((dep) => {
1743
+ if (isComputed(dep) && "dependencies" in dep) {
1744
+ const computedDep = dep;
1745
+ if (computedDep.dependencies.size === 0) {
1746
+ return new BehaviorSubject(computedDep()).asObservable();
1747
+ }
1748
+ }
1749
+ return dep.observable;
1750
+ });
1751
+ const computedObservable = combineLatest(observables).pipe(filter(() => !init), map(() => computeFunction()), finalize(() => disposableFn?.()));
1752
+ const fn = /* @__PURE__ */ __name$1(function() {
1753
+ trackDependency(fn);
1754
+ return lastComputedValue;
1755
+ }, "fn");
1756
+ fn.observable = computedObservable;
1757
+ fn.subscription = computedObservable.subscribe((value) => {
1758
+ lastComputedValue = value;
1759
+ });
1760
+ fn.dependencies = dependencies;
1761
+ reactiveStore.currentSubscriptionsTracker?.(fn.subscription);
1762
+ init = false;
1763
+ return fn;
1764
+ }
1765
+ __name$1(computed, "computed");
1766
+ function linkedSignal(computationOrOptions, simpleOptions) {
1767
+ const dependencies = /* @__PURE__ */ new Set();
1768
+ let init = true;
1769
+ let lastComputedValue;
1770
+ let computeFunction;
1771
+ let sourceSignal;
1772
+ let computationFn;
1773
+ let equalFn;
1774
+ let previousValue;
1775
+ let isOverridden = false;
1776
+ let overriddenValue;
1777
+ let depVersion = 0;
1778
+ let overrideDepVersion = null;
1779
+ if (typeof computationOrOptions === "function") {
1780
+ computeFunction = computationOrOptions;
1781
+ equalFn = simpleOptions?.equal;
1782
+ } else {
1783
+ const options = computationOrOptions;
1784
+ sourceSignal = options.source;
1785
+ computationFn = options.computation;
1786
+ equalFn = options.equal;
1787
+ if (typeof sourceSignal === "function" && !isSignal(sourceSignal)) {
1788
+ const sourceFn = sourceSignal;
1789
+ computeFunction = /* @__PURE__ */ __name$1(() => {
1790
+ const sourceValue = sourceFn();
1791
+ if (computationFn.length > 1) {
1792
+ const result = computationFn(sourceValue, previousValue);
1793
+ previousValue = {
1794
+ source: sourceValue,
1795
+ value: result
1796
+ };
1797
+ return result;
1798
+ } else {
1799
+ const result = computationFn(sourceValue);
1800
+ previousValue = {
1801
+ source: sourceValue,
1802
+ value: result
1803
+ };
1804
+ return result;
1805
+ }
1806
+ }, "computeFunction");
1807
+ } else {
1808
+ const source = typeof sourceSignal === "function" ? sourceSignal : sourceSignal;
1809
+ computeFunction = /* @__PURE__ */ __name$1(() => {
1810
+ const sourceValue = source();
1811
+ if (computationFn.length > 1) {
1812
+ const result = computationFn(sourceValue, previousValue);
1813
+ previousValue = {
1814
+ source: sourceValue,
1815
+ value: result
1816
+ };
1817
+ return result;
1818
+ } else {
1819
+ const result = computationFn(sourceValue);
1820
+ previousValue = {
1821
+ source: sourceValue,
1822
+ value: result
1823
+ };
1824
+ return result;
1825
+ }
1826
+ }, "computeFunction");
1827
+ }
1828
+ }
1829
+ const previousTracker = reactiveStore.currentDependencyTracker;
1830
+ reactiveStore.currentDependencyTracker = (signal2) => {
1831
+ dependencies.add(signal2);
1832
+ };
1833
+ if (sourceSignal && typeof sourceSignal === "function" && !isSignal(sourceSignal)) {
1834
+ lastComputedValue = computeFunction();
1835
+ } else if (sourceSignal && isSignal(sourceSignal)) {
1836
+ dependencies.add(sourceSignal);
1837
+ lastComputedValue = computeFunction();
1838
+ } else {
1839
+ lastComputedValue = computeFunction();
1840
+ }
1841
+ reactiveStore.currentDependencyTracker = previousTracker;
1842
+ const subject = new BehaviorSubject(lastComputedValue);
1843
+ const observables = [
1844
+ ...dependencies
1845
+ ].map((dep) => {
1846
+ if (isComputed(dep) && "dependencies" in dep) {
1847
+ const computedDep = dep;
1848
+ if (computedDep.dependencies.size === 0) {
1849
+ return new BehaviorSubject(computedDep()).asObservable();
1850
+ }
1851
+ }
1852
+ return dep.observable;
1853
+ });
1854
+ let linkedObservable;
1855
+ if (observables.length > 0) {
1856
+ linkedObservable = combineLatest(observables).pipe(filter(() => !init), map(() => {
1857
+ const computed2 = computeFunction();
1858
+ if (equalFn) {
1859
+ if (!equalFn(lastComputedValue, computed2)) {
1860
+ lastComputedValue = computed2;
1861
+ isOverridden = false;
1862
+ }
1863
+ } else {
1864
+ if (lastComputedValue !== computed2) {
1865
+ lastComputedValue = computed2;
1866
+ isOverridden = false;
1867
+ }
1868
+ }
1869
+ return lastComputedValue;
1870
+ }));
1871
+ } else {
1872
+ linkedObservable = subject.asObservable().pipe(filter(() => !init));
1873
+ }
1874
+ const fn = /* @__PURE__ */ __name$1(function() {
1875
+ trackDependency(fn);
1876
+ if (isOverridden && dependencies.size > 0) {
1877
+ if (overrideDepVersion !== depVersion) {
1878
+ const computed2 = computeFunction();
1879
+ isOverridden = false;
1880
+ overriddenValue = void 0;
1881
+ lastComputedValue = computed2;
1882
+ overrideDepVersion = null;
1883
+ return computed2;
1884
+ }
1885
+ return overriddenValue;
1886
+ }
1887
+ if (isOverridden) {
1888
+ return overriddenValue;
1889
+ }
1890
+ if (dependencies.size === 0) {
1891
+ const computed2 = computeFunction();
1892
+ lastComputedValue = computed2;
1893
+ }
1894
+ return lastComputedValue;
1895
+ }, "fn");
1896
+ fn.observable = new Observable((observer) => {
1897
+ const depSubscription = linkedObservable.subscribe((value) => {
1898
+ if (dependencies.size > 0) {
1899
+ depVersion++;
1900
+ isOverridden = false;
1901
+ overrideDepVersion = null;
1902
+ lastComputedValue = value;
1903
+ } else {
1904
+ lastComputedValue = value;
1905
+ }
1906
+ observer.next(value);
1907
+ });
1908
+ let subjectSubscription;
1909
+ if (dependencies.size === 0) {
1910
+ subjectSubscription = subject.pipe(filter(() => !init)).subscribe((value) => {
1911
+ observer.next(value);
1912
+ });
1913
+ }
1914
+ observer.next(lastComputedValue);
1915
+ return () => {
1916
+ depSubscription.unsubscribe();
1917
+ if (subjectSubscription) {
1918
+ subjectSubscription.unsubscribe();
1919
+ }
1920
+ };
1921
+ });
1922
+ fn.subscription = fn.observable.subscribe(() => {
1923
+ });
1924
+ fn.dependencies = dependencies;
1925
+ fn._subject = subject;
1926
+ fn.set = (value) => {
1927
+ if (!isOverridden) {
1928
+ overrideDepVersion = depVersion;
1929
+ if (computationFn && sourceSignal) {
1930
+ const sourceValue = untracked(() => {
1931
+ if (typeof sourceSignal === "function") {
1932
+ const source = sourceSignal;
1933
+ return isSignal(source) ? source() : sourceSignal();
1934
+ }
1935
+ return sourceSignal();
1936
+ });
1937
+ previousValue = {
1938
+ source: sourceValue,
1939
+ value
1940
+ };
1941
+ }
1942
+ }
1943
+ isOverridden = true;
1944
+ overriddenValue = value;
1945
+ lastComputedValue = value;
1946
+ subject.next(value);
1947
+ };
1948
+ reactiveStore.currentSubscriptionsTracker?.(fn.subscription);
1949
+ init = false;
1950
+ return fn;
1951
+ }
1952
+ __name$1(linkedSignal, "linkedSignal");
1953
+ function untracked(fn) {
1954
+ const prevDepTracker = reactiveStore.currentDependencyTracker;
1955
+ const prevSubTracker = reactiveStore.currentSubscriptionsTracker;
1956
+ reactiveStore.currentDependencyTracker = null;
1957
+ reactiveStore.currentSubscriptionsTracker = null;
1958
+ try {
1959
+ return fn();
1960
+ } finally {
1961
+ reactiveStore.currentDependencyTracker = prevDepTracker;
1962
+ reactiveStore.currentSubscriptionsTracker = prevSubTracker;
1963
+ }
1964
+ }
1965
+ __name$1(untracked, "untracked");
1966
+
1967
+ // src/effect.ts
1968
+ function effect(fn) {
1969
+ fn["isEffect"] = true;
1970
+ return computed(fn);
1971
+ }
1972
+ __name$1(effect, "effect");
1973
+
1974
+ // src/utils.ts
1975
+ function isFunction(val) {
1976
+ return {}.toString.call(val) === "[object Function]";
1977
+ }
1978
+ __name$2(isFunction, "isFunction");
1979
+ function isClass(obj) {
1980
+ return typeof obj === "function" && obj.prototype && obj.prototype.constructor === obj;
1981
+ }
1982
+ __name$2(isClass, "isClass");
1983
+ var isObject = /* @__PURE__ */ __name$2((item) => item && typeof item === "object" && !Array.isArray(item) && item !== null, "isObject");
1984
+ function isInstanceOfClass(value) {
1985
+ if (value === null || typeof value !== "object" || value === void 0 || Array.isArray(value)) {
1986
+ return false;
1987
+ }
1988
+ return Object.getPrototypeOf(value) !== Object.prototype;
1989
+ }
1990
+ __name$2(isInstanceOfClass, "isInstanceOfClass");
1991
+ function generateShortUUID() {
1992
+ const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
1993
+ let uuid = "";
1994
+ for (let i = 0; i < 8; i++) {
1995
+ const randomIndex = Math.floor(Math.random() * chars.length);
1996
+ uuid += chars[randomIndex];
1997
+ }
1998
+ return uuid;
1999
+ }
2000
+ __name$2(generateShortUUID, "generateShortUUID");
2001
+
2002
+ // src/core.ts
2003
+ var DELETE_TOKEN = "$delete";
2004
+ var syncClass = /* @__PURE__ */ __name$2((instance, options = {}) => {
2005
+ const cacheSync = /* @__PURE__ */ new Map();
2006
+ const cachePersist = /* @__PURE__ */ new Map();
2007
+ instance.$valuesChanges = {
2008
+ set: /* @__PURE__ */ __name$2((path, value) => {
2009
+ cacheSync.set(path, value);
2010
+ options.onSync?.(cacheSync);
2011
+ }, "set"),
2012
+ setPersist: /* @__PURE__ */ __name$2((path, value) => {
2013
+ if (path == "") path = ".";
2014
+ cachePersist.set(path, value);
2015
+ options.onPersist?.(cachePersist);
2016
+ }, "setPersist"),
2017
+ has: /* @__PURE__ */ __name$2((path) => {
2018
+ return cacheSync.has(path);
2019
+ }, "has"),
2020
+ get: /* @__PURE__ */ __name$2((path) => {
2021
+ return cacheSync.get(path);
2022
+ }, "get")
2023
+ };
2024
+ createSyncClass(instance);
2025
+ }, "syncClass");
2026
+ function createStatesSnapshot(instance) {
2027
+ let persistObject = {};
2028
+ if (instance?.$snapshot) {
2029
+ for (const key of instance.$snapshot.keys()) {
2030
+ const signal = instance.$snapshot.get(key);
2031
+ const persist2 = signal.options.persist ?? true;
2032
+ let value = signal();
2033
+ if (isObject(value) || Array.isArray(value)) {
2034
+ continue;
2035
+ }
2036
+ if (persist2) {
2037
+ persistObject[key] = value;
2038
+ }
2039
+ }
2040
+ }
2041
+ return persistObject;
2042
+ }
2043
+ __name$2(createStatesSnapshot, "createStatesSnapshot");
2044
+ var SNAPSHOT_SKIP = Symbol("snapshot-skip");
2045
+ var serializeSnapshotDeep = /* @__PURE__ */ __name$2((value, path, options, seen) => {
2046
+ if (isSignal(value)) {
2047
+ return serializeSnapshotDeep(value(), path, options, seen);
2048
+ }
2049
+ if (value instanceof Map) {
2050
+ return SNAPSHOT_SKIP;
2051
+ }
2052
+ if (options.filter && !options.filter(value, path)) {
2053
+ return SNAPSHOT_SKIP;
2054
+ }
2055
+ if (value instanceof Date) {
2056
+ return options.dateToString ? options.dateToString(value) : value.toISOString();
2057
+ }
2058
+ if (value && typeof value === "object") {
2059
+ if (seen.has(value)) {
2060
+ return SNAPSHOT_SKIP;
2061
+ }
2062
+ seen.add(value);
2063
+ if (Array.isArray(value)) {
2064
+ const result2 = [];
2065
+ value.forEach((item, index) => {
2066
+ const itemPath = path ? `${path}.${index}` : String(index);
2067
+ const serialized = serializeSnapshotDeep(item, itemPath, options, seen);
2068
+ if (serialized !== SNAPSHOT_SKIP) {
2069
+ result2.push(serialized);
2070
+ }
2071
+ });
2072
+ return result2;
2073
+ }
2074
+ const result = {};
2075
+ const idKey = isInstanceOfClass(value) ? value.constructor?._propertyMetadata?.get("id") : void 0;
2076
+ const entries = Object.entries(value).filter(([key]) => isInstanceOfClass(value) ? key.startsWith("__") || (idKey ? key === idKey : false) : true);
2077
+ for (const [key, childValue] of entries) {
2078
+ const normalizedKey = key.startsWith("__") ? key.slice(2) : key;
2079
+ const childPath = path ? `${path}.${normalizedKey}` : normalizedKey;
2080
+ const serialized = serializeSnapshotDeep(childValue, childPath, options, seen);
2081
+ if (serialized !== SNAPSHOT_SKIP) {
2082
+ result[normalizedKey] = serialized;
2083
+ }
2084
+ }
2085
+ return result;
2086
+ }
2087
+ return value;
2088
+ }, "serializeSnapshotDeep");
2089
+ function createStatesSnapshotDeep(instance, options = {}) {
2090
+ const persistObject = {};
2091
+ if (instance?.$snapshot) {
2092
+ for (const key of instance.$snapshot.keys()) {
2093
+ const signal = instance.$snapshot.get(key);
2094
+ const persist2 = signal.options.persist ?? true;
2095
+ if (!persist2) {
2096
+ continue;
2097
+ }
2098
+ const value = signal();
2099
+ const serialized = serializeSnapshotDeep(value, key, options, /* @__PURE__ */ new WeakSet());
2100
+ if (serialized !== SNAPSHOT_SKIP) {
2101
+ persistObject[key] = serialized;
2102
+ }
2103
+ }
2104
+ }
2105
+ return persistObject;
2106
+ }
2107
+ __name$2(createStatesSnapshotDeep, "createStatesSnapshotDeep");
2108
+ function setMetadata(target, key, value) {
2109
+ const meta = target.constructor._propertyMetadata;
2110
+ const propId = meta?.get(key);
2111
+ if (propId) {
2112
+ if (isSignal(target[propId])) {
2113
+ target[propId].set(value);
2114
+ } else {
2115
+ target[propId] = value;
2116
+ }
2117
+ }
2118
+ }
2119
+ __name$2(setMetadata, "setMetadata");
2120
+ var createSyncClass = /* @__PURE__ */ __name$2((currentClass, parentKey = null, parentClass = null, path = "") => {
2121
+ currentClass.$path = path;
2122
+ if (parentClass) {
2123
+ currentClass.$valuesChanges = parentClass.$valuesChanges;
2124
+ }
2125
+ if (parentKey) {
2126
+ setMetadata(currentClass, "id", parentKey);
2127
+ }
2128
+ if (currentClass.$snapshot) {
2129
+ for (const key of currentClass.$snapshot.keys()) {
2130
+ const signal = currentClass.$snapshot.get(key);
2131
+ const syncToClient = signal.options?.syncToClient ?? true;
2132
+ const persist2 = signal.options?.persist ?? true;
2133
+ const transform = signal.options?.transform;
2134
+ let signalValue = signal();
2135
+ if (transform) {
2136
+ signalValue = transform(signalValue);
2137
+ }
2138
+ if (isObject(signalValue) || Array.isArray(signalValue)) {
2139
+ signalValue = {
2140
+ ...signalValue
2141
+ };
2142
+ }
2143
+ const transformedValue = signalValue;
2144
+ const newPath = (path ? path + "." : "") + key;
2145
+ if (syncToClient) {
2146
+ currentClass.$valuesChanges.set(newPath, transformedValue);
2147
+ }
2148
+ if (persist2) {
2149
+ if (parentClass) currentClass.$valuesChanges.setPersist(path, transformedValue);
2150
+ }
2151
+ if (isComputed(signal)) {
2152
+ signal.observable.subscribe((newValue) => {
2153
+ if (syncToClient) {
2154
+ const transformedNewValue = transform ? transform(newValue) : newValue;
2155
+ currentClass.$valuesChanges.set(newPath, transformedNewValue);
2156
+ }
2157
+ });
2158
+ }
2159
+ }
2160
+ }
2161
+ }, "createSyncClass");
2162
+ var type = /* @__PURE__ */ __name$2((_signal, path, options = {}, currentInstance) => {
2163
+ const { syncToClient = true, persist: persist2 = true, transform } = options;
2164
+ let init = true;
2165
+ const handleObjectSubject = /* @__PURE__ */ __name$2((value, propPath) => {
2166
+ const newPath = `${propPath}${value.key ? `.${value.key}` : ""}`;
2167
+ if ([
2168
+ "add",
2169
+ "reset",
2170
+ "update"
2171
+ ].includes(value.type)) {
2172
+ if (isInstanceOfClass(value.value)) {
2173
+ createSyncClass(value.value, value.key, currentInstance, newPath);
2174
+ } else if (value.type === "update" && (isObject(value.value) || Array.isArray(value.value))) {
2175
+ createSyncClass(value.value, value.key, currentInstance, newPath);
2176
+ } else {
2177
+ savePath(newPath, value.value);
2178
+ }
2179
+ } else if (value.type === "remove") {
2180
+ savePath(newPath, DELETE_TOKEN);
2181
+ }
2182
+ }, "handleObjectSubject");
2183
+ const handleArraySubject = /* @__PURE__ */ __name$2((value, propPath) => {
2184
+ if (value.type === "reset" && Array.isArray(value.items)) {
2185
+ value.items.forEach((item, index) => {
2186
+ const newPath2 = `${propPath}.${index}`;
2187
+ if (isInstanceOfClass(item)) {
2188
+ createSyncClass(item, value.key, currentInstance, newPath2);
2189
+ } else {
2190
+ savePath(newPath2, item);
2191
+ }
2192
+ });
2193
+ return;
2194
+ }
2195
+ const newPath = `${propPath}.${value.index}`;
2196
+ const firstItem = value.items?.[0];
2197
+ if ([
2198
+ "add",
2199
+ "update"
2200
+ ].includes(value.type) && firstItem !== void 0) {
2201
+ if (isInstanceOfClass(firstItem)) {
2202
+ createSyncClass(firstItem, value.key, currentInstance, newPath);
2203
+ } else if (value.type === "update" && (isObject(firstItem) || Array.isArray(firstItem))) {
2204
+ createSyncClass(firstItem, value.key, currentInstance, newPath);
2205
+ } else {
2206
+ savePath(newPath, firstItem);
2207
+ }
2208
+ } else if (value.type === "remove") {
2209
+ savePath(newPath, DELETE_TOKEN);
2210
+ }
2211
+ }, "handleArraySubject");
2212
+ const savePath = /* @__PURE__ */ __name$2((propPath, value) => {
2213
+ const transformedValue = transform && value !== DELETE_TOKEN ? transform(value) : value;
2214
+ if (syncToClient) {
2215
+ currentInstance.$valuesChanges.set(propPath, transformedValue);
2216
+ }
2217
+ if (persist2 && currentInstance.$path !== void 0) {
2218
+ currentInstance.$valuesChanges.setPersist(transformedValue == DELETE_TOKEN ? propPath : currentInstance.$path, transformedValue);
2219
+ }
2220
+ }, "savePath");
2221
+ const setupSubscription = /* @__PURE__ */ __name$2((signal, signalPath) => {
2222
+ if (!isSignal(signal)) return;
2223
+ if (syncToClient && currentInstance.$valuesChanges) {
2224
+ const initialValue = signal();
2225
+ const transformedInitialValue = transform ? transform(initialValue) : initialValue;
2226
+ currentInstance.$valuesChanges.set(signalPath, transformedInitialValue);
2227
+ }
2228
+ signal.options = options;
2229
+ signal.observable.subscribe((value) => {
2230
+ if (init) return;
2231
+ if (currentInstance.$path !== void 0) {
2232
+ const fullPath = `${currentInstance.$path ? currentInstance.$path + "." : ""}${signalPath}`;
2233
+ if (isComputed(signal)) {
2234
+ savePath(fullPath, value);
2235
+ } else if (isObjectSubject(signal._subject)) {
2236
+ handleObjectSubject(value, fullPath);
2237
+ } else if (isArraySubject(signal._subject)) {
2238
+ handleArraySubject(value, fullPath);
2239
+ } else {
2240
+ savePath(fullPath, value);
2241
+ }
2242
+ }
2243
+ });
2244
+ if (!currentInstance.$snapshot) {
2245
+ currentInstance.$snapshot = /* @__PURE__ */ new Map();
2246
+ }
2247
+ currentInstance.$snapshot.set(path, signal);
2248
+ }, "setupSubscription");
2249
+ if (!isSignal(_signal)) {
2250
+ if (_signal && typeof _signal === "object" && !Array.isArray(_signal)) {
2251
+ for (const key in _signal) {
2252
+ if (Object.prototype.hasOwnProperty.call(_signal, key)) {
2253
+ const value = _signal[key];
2254
+ const propertyPath = `${path}.${key}`;
2255
+ if (isSignal(value)) {
2256
+ setupSubscription(value, propertyPath);
2257
+ } else if (value && typeof value === "object" && !Array.isArray(value)) {
2258
+ type(value, propertyPath, options, currentInstance);
2259
+ }
2260
+ }
2261
+ }
2262
+ init = false;
2263
+ }
2264
+ return _signal;
2265
+ }
2266
+ setupSubscription(_signal, path);
2267
+ init = false;
2268
+ return _signal;
2269
+ }, "type");
2270
+
2271
+ // src/decorators.ts
2272
+ function sync(options) {
2273
+ let classType;
2274
+ let persist2 = true;
2275
+ let syncToClient = true;
2276
+ let transform;
2277
+ if (typeof options === "function") {
2278
+ classType = options;
2279
+ } else if (typeof options === "object") {
2280
+ classType = options.classType;
2281
+ if (options.hasOwnProperty("persist")) {
2282
+ persist2 = options.persist;
2283
+ }
2284
+ if (options.hasOwnProperty("syncToClient")) {
2285
+ syncToClient = options.syncToClient;
2286
+ }
2287
+ if (options.hasOwnProperty("transform")) {
2288
+ transform = options.transform;
2289
+ }
2290
+ }
2291
+ return function(target, propertyKey) {
2292
+ const privatePropertyKey = `__${propertyKey}`;
2293
+ const getter = /* @__PURE__ */ __name$2(function() {
2294
+ return this[privatePropertyKey];
2295
+ }, "getter");
2296
+ const setter = /* @__PURE__ */ __name$2(function(newVal) {
2297
+ this[privatePropertyKey] = type(newVal, propertyKey, {
2298
+ classType,
2299
+ persist: persist2,
2300
+ syncToClient,
2301
+ transform
2302
+ }, this);
2303
+ }, "setter");
2304
+ Object.defineProperty(target, propertyKey, {
2305
+ get: getter,
2306
+ set: setter,
2307
+ enumerable: true,
2308
+ configurable: true
2309
+ });
2310
+ };
2311
+ }
2312
+ __name$2(sync, "sync");
2313
+ function id() {
2314
+ return function(target, propertyKey) {
2315
+ if (!target.constructor._propertyMetadata) {
2316
+ target.constructor._propertyMetadata = /* @__PURE__ */ new Map();
2317
+ }
2318
+ target.constructor._propertyMetadata.set("id", propertyKey);
2319
+ };
2320
+ }
2321
+ __name$2(id, "id");
2322
+ function users(options) {
2323
+ return function(target, propertyKey) {
2324
+ if (!target.constructor._propertyMetadata) {
2325
+ target.constructor._propertyMetadata = /* @__PURE__ */ new Map();
2326
+ }
2327
+ target.constructor._propertyMetadata.set("users", propertyKey);
2328
+ sync(options)(target, propertyKey);
2329
+ };
2330
+ }
2331
+ __name$2(users, "users");
2332
+ function persist() {
2333
+ return sync({
2334
+ persist: true,
2335
+ syncToClient: false
2336
+ });
2337
+ }
2338
+ __name$2(persist, "persist");
2339
+ function connected() {
2340
+ return function(target, propertyKey) {
2341
+ if (!target.constructor._propertyMetadata) {
2342
+ target.constructor._propertyMetadata = /* @__PURE__ */ new Map();
2343
+ }
2344
+ target.constructor._propertyMetadata.set("connected", propertyKey);
2345
+ sync({
2346
+ persist: false
2347
+ })(target, propertyKey);
2348
+ };
2349
+ }
2350
+ __name$2(connected, "connected");
2351
+ function load(rootInstance, values, valueIsObject) {
2352
+ if (valueIsObject) {
2353
+ loadFromObject(rootInstance, values);
2354
+ } else {
2355
+ loadFromPaths(rootInstance, values);
2356
+ }
2357
+ }
2358
+ __name$2(load, "load");
2359
+ function loadFromPaths(rootInstance, values) {
2360
+ for (const [path, value] of Object.entries(values)) {
2361
+ const parts = path.split(".");
2362
+ loadValue(rootInstance, parts, value);
2363
+ }
2364
+ }
2365
+ __name$2(loadFromPaths, "loadFromPaths");
2366
+ function loadFromObject(rootInstance, values, currentPath = "") {
2367
+ for (let key in values) {
2368
+ const value = values[key];
2369
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
2370
+ if (typeof value === "object" && !Array.isArray(value) && value !== null) {
2371
+ loadFromObject(rootInstance, value, newPath);
2372
+ } else {
2373
+ const parts = newPath.split(".");
2374
+ loadValue(rootInstance, parts, value);
2375
+ }
2376
+ }
2377
+ }
2378
+ __name$2(loadFromObject, "loadFromObject");
2379
+ function loadValue(rootInstance, parts, value) {
2380
+ let current = rootInstance;
2381
+ for (let i = 0; i < parts.length; i++) {
2382
+ const part = parts[i];
2383
+ if (i === parts.length - 1) {
2384
+ if (value == DELETE_TOKEN) {
2385
+ if (isSignal(current)) {
2386
+ current = current();
2387
+ }
2388
+ Reflect.deleteProperty(current, part);
2389
+ } else if (current[part]?._subject) {
2390
+ current[part].set(value);
2391
+ } else if (isSignal(current) && Array.isArray(current()) && !isNaN(Number(part))) {
2392
+ current()[Number(part)] = value;
2393
+ } else {
2394
+ current[part] = value;
2395
+ }
2396
+ } else {
2397
+ if (isSignal(current)) {
2398
+ current = current();
2399
+ }
2400
+ const currentValue = current[part];
2401
+ if (currentValue === void 0) {
2402
+ const parentInstance = getByPath(rootInstance, parts.slice(0, i).join("."));
2403
+ const classType = parentInstance?.options?.classType;
2404
+ if (classType) {
2405
+ current[part] = !isClass(classType) ? classType(part) : new classType();
2406
+ setMetadata(current[part], "id", part);
2407
+ } else {
2408
+ current[part] = {};
2409
+ }
2410
+ }
2411
+ current = current[part];
2412
+ }
2413
+ }
2414
+ }
2415
+ __name$2(loadValue, "loadValue");
2416
+ function getByPath(root, path) {
2417
+ const parts = path.split(".");
2418
+ let current = root;
2419
+ for (const part of parts) {
2420
+ if (isSignal(current)) {
2421
+ current = current();
2422
+ }
2423
+ if (current[part]) {
2424
+ current = current[part];
2425
+ } else {
2426
+ return void 0;
2427
+ }
2428
+ }
2429
+ return current;
2430
+ }
2431
+ __name$2(getByPath, "getByPath");
2432
+
2433
+ var __defProp$3 = Object.defineProperty;
2434
+ var __decorateClass$2 = (decorators, target, key, kind) => {
2435
+ var result = void 0 ;
2436
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
2437
+ if (decorator = decorators[i])
2438
+ result = (decorator(target, key, result) ) || result;
2439
+ if (result) __defProp$3(target, key, result);
2440
+ return result;
2441
+ };
2442
+ class Item {
2443
+ constructor(data) {
2444
+ this.id = signal("");
2445
+ this.name = signal("");
2446
+ this.description = signal("");
2447
+ this.price = signal(0);
2448
+ this.atk = signal(0);
2449
+ this.pdef = signal(0);
2450
+ this.sdef = signal(0);
2451
+ this.icon = signal("");
2452
+ this.quantity = signal(1);
2453
+ this.onAdd = () => {
2454
+ };
2455
+ this.description.set(data?.description ?? "");
2456
+ this.price.set(data?.price ?? 0);
2457
+ this.name.set(data?.name ?? "");
2458
+ this.atk.set(data?.atk ?? 0);
2459
+ this.pdef.set(data?.pdef ?? 0);
2460
+ this.sdef.set(data?.sdef ?? 0);
2461
+ this.icon.set(data?.icon ?? "");
2462
+ this.onAdd = data?.onAdd?.bind(this) ?? (() => {
2463
+ });
2464
+ }
2465
+ }
2466
+ __decorateClass$2([
2467
+ id()
2468
+ ], Item.prototype, "id");
2469
+ __decorateClass$2([
2470
+ sync()
2471
+ ], Item.prototype, "name");
2472
+ __decorateClass$2([
2473
+ sync()
2474
+ ], Item.prototype, "icon");
2475
+ __decorateClass$2([
2476
+ sync()
2477
+ ], Item.prototype, "quantity");
2478
+
2479
+ var __defProp$2 = Object.defineProperty;
2480
+ var __decorateClass$1 = (decorators, target, key, kind) => {
2481
+ var result = void 0 ;
2482
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
2483
+ if (decorator = decorators[i])
2484
+ result = (decorator(target, key, result) ) || result;
2485
+ if (result) __defProp$2(target, key, result);
2486
+ return result;
2487
+ };
2488
+ class Skill {
2489
+ constructor(data) {
2490
+ this.id = signal("");
2491
+ this.name = signal("");
2492
+ this.description = signal("");
2493
+ this.spCost = signal(0);
2494
+ this.icon = signal("");
2495
+ this.hitRate = signal(0);
2496
+ this.power = signal(0);
2497
+ this.coefficient = signal({});
2498
+ this.id.set(data?.id ?? "");
2499
+ this.name.set(data?.name ?? "");
2500
+ this.description.set(data?.description ?? "");
2501
+ this.spCost.set(data?.spCost ?? 0);
2502
+ this.hitRate.set(data?.hitRate ?? 0);
2503
+ this.power.set(data?.power ?? 0);
2504
+ this.coefficient.set(data?.coefficient ?? {});
2505
+ this.icon.set(data?.icon ?? "");
2506
+ }
2507
+ }
2508
+ __decorateClass$1([
2509
+ id()
2510
+ ], Skill.prototype, "id");
2511
+ __decorateClass$1([
2512
+ sync()
2513
+ ], Skill.prototype, "name");
2514
+ __decorateClass$1([
2515
+ sync()
2516
+ ], Skill.prototype, "spCost");
2517
+ __decorateClass$1([
2518
+ sync()
2519
+ ], Skill.prototype, "icon");
2520
+
2521
+ var __defProp$1 = Object.defineProperty;
2522
+ var __decorateClass = (decorators, target, key, kind) => {
2523
+ var result = void 0 ;
2524
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
2525
+ if (decorator = decorators[i])
2526
+ result = (decorator(target, key, result) ) || result;
2527
+ if (result) __defProp$1(target, key, result);
2528
+ return result;
2529
+ };
2530
+ var Direction = /* @__PURE__ */ ((Direction2) => {
2531
+ Direction2["Up"] = "up";
2532
+ Direction2["Down"] = "down";
2533
+ Direction2["Left"] = "left";
2534
+ Direction2["Right"] = "right";
2535
+ return Direction2;
2536
+ })(Direction || {});
2537
+ class RpgCommonPlayer {
2538
+ constructor() {
2539
+ this.name = signal("");
2540
+ this.type = signal("");
2541
+ this.x = signal(0);
2542
+ this.y = signal(0);
2543
+ this.z = signal(0);
2544
+ this.tint = signal("white");
2545
+ this.direction = signal("down" /* Down */);
2546
+ this.speed = signal(4);
2547
+ this.graphics = signal([]);
2548
+ this.canMove = signal(true);
2549
+ this.hitbox = signal({
2550
+ w: 32,
2551
+ h: 32
2552
+ });
2553
+ this._gold = signal(0);
2554
+ this.animationName = signal("stand");
2555
+ this.hpSignal = signal(0);
2556
+ this.spSignal = signal(0);
2557
+ this._exp = signal(0);
2558
+ this._level = signal(1);
2559
+ this._class = signal({});
2560
+ this.items = signal([]);
2561
+ this.equipments = signal([]);
2562
+ this.states = signal([]);
2563
+ this.skills = signal([]);
2564
+ this._effects = signal([]);
2565
+ this._through = signal(false);
2566
+ this._throughOtherPlayer = signal(true);
2567
+ this._throughEvent = signal(false);
2568
+ this._frequency = signal(0);
2569
+ this._frames = signal([]);
2570
+ this.componentsTop = signal(null);
2571
+ this.componentsBottom = signal(null);
2572
+ this.componentsCenter = signal(null);
2573
+ this.componentsLeft = signal(null);
2574
+ this.componentsRight = signal(null);
2575
+ this.isConnected = signal(false);
2576
+ // Store intended movement direction (not synced, only used locally)
2577
+ this._intendedDirection = null;
2578
+ // Direction and animation locking (server-side only, not synced)
2579
+ this._directionFixed = signal(false);
2580
+ this._animationFixed = signal(false);
2581
+ this.pendingInputs = [];
2582
+ }
2583
+ /**
2584
+ * Get whether direction changes are locked
2585
+ *
2586
+ * @returns True if direction is locked and cannot be changed automatically
2587
+ *
2588
+ * @example
2589
+ * ```ts
2590
+ * if (player.directionFixed) {
2591
+ * // Direction is locked, won't change automatically
2592
+ * }
2593
+ * ```
2594
+ */
2595
+ get directionFixed() {
2596
+ return this._directionFixed();
2597
+ }
2598
+ /**
2599
+ * Set whether direction changes are locked
2600
+ *
2601
+ * When set to true, the player's direction will not change automatically
2602
+ * during movement or from physics engine callbacks.
2603
+ *
2604
+ * @param value - True to lock direction, false to allow automatic changes
2605
+ *
2606
+ * @example
2607
+ * ```ts
2608
+ * // Lock direction during a special animation
2609
+ * player.directionFixed = true;
2610
+ * player.setAnimation('attack');
2611
+ * // ... later
2612
+ * player.directionFixed = false;
2613
+ * ```
2614
+ */
2615
+ set directionFixed(value) {
2616
+ this._directionFixed.set(value);
2617
+ }
2618
+ /**
2619
+ * Get whether animation changes are locked
2620
+ *
2621
+ * @returns True if animation is locked and cannot be changed automatically
2622
+ *
2623
+ * @example
2624
+ * ```ts
2625
+ * if (player.animationFixed) {
2626
+ * // Animation is locked, won't change automatically
2627
+ * }
2628
+ * ```
2629
+ */
2630
+ get animationFixed() {
2631
+ return this._animationFixed();
2632
+ }
2633
+ /**
2634
+ * Set whether animation changes are locked
2635
+ *
2636
+ * When set to true, the player's animation will not change automatically
2637
+ * during movement or from physics engine callbacks.
2638
+ *
2639
+ * @param value - True to lock animation, false to allow automatic changes
2640
+ *
2641
+ * @example
2642
+ * ```ts
2643
+ * // Lock animation during a special skill
2644
+ * player.animationFixed = true;
2645
+ * player.setAnimation('skill');
2646
+ * // ... later
2647
+ * player.animationFixed = false;
2648
+ * ```
2649
+ */
2650
+ set animationFixed(value) {
2651
+ this._animationFixed.set(value);
2652
+ }
2653
+ /**
2654
+ * Change the player's facing direction
2655
+ *
2656
+ * Updates the direction the player is facing, which affects animations
2657
+ * and directional abilities. This should be called when the player
2658
+ * intends to move in a specific direction, not when they are pushed
2659
+ * by physics or sliding.
2660
+ *
2661
+ * If `directionFixed` is true, this method will not change the direction.
2662
+ *
2663
+ * @param direction - The new direction to face
2664
+ *
2665
+ * @example
2666
+ * ```ts
2667
+ * // Player presses right arrow key
2668
+ * player.changeDirection(Direction.Right);
2669
+ *
2670
+ * // Lock direction to prevent automatic changes
2671
+ * player.directionFixed = true;
2672
+ * player.changeDirection(Direction.Up); // This will be ignored
2673
+ * ```
2674
+ */
2675
+ changeDirection(direction) {
2676
+ if (this._directionFixed()) {
2677
+ return;
2678
+ }
2679
+ this.direction.set(direction);
2680
+ }
2681
+ /**
2682
+ * Get the current facing direction
2683
+ *
2684
+ * @returns Current direction the player is facing
2685
+ *
2686
+ * @example
2687
+ * ```ts
2688
+ * const currentDirection = player.getDirection();
2689
+ * if (currentDirection === Direction.Up) {
2690
+ * // Player is facing up
2691
+ * }
2692
+ * ```
2693
+ */
2694
+ getDirection() {
2695
+ return this.direction();
2696
+ }
2697
+ }
2698
+ __decorateClass([
2699
+ id()
2700
+ ], RpgCommonPlayer.prototype, "id");
2701
+ __decorateClass([
2702
+ sync()
2703
+ ], RpgCommonPlayer.prototype, "name");
2704
+ __decorateClass([
2705
+ sync()
2706
+ ], RpgCommonPlayer.prototype, "type");
2707
+ __decorateClass([
2708
+ sync()
2709
+ ], RpgCommonPlayer.prototype, "x");
2710
+ __decorateClass([
2711
+ sync()
2712
+ ], RpgCommonPlayer.prototype, "y");
2713
+ __decorateClass([
2714
+ sync()
2715
+ ], RpgCommonPlayer.prototype, "z");
2716
+ __decorateClass([
2717
+ sync()
2718
+ ], RpgCommonPlayer.prototype, "tint");
2719
+ __decorateClass([
2720
+ sync()
2721
+ ], RpgCommonPlayer.prototype, "direction");
2722
+ __decorateClass([
2723
+ sync()
2724
+ ], RpgCommonPlayer.prototype, "speed");
2725
+ __decorateClass([
2726
+ sync()
2727
+ ], RpgCommonPlayer.prototype, "graphics");
2728
+ __decorateClass([
2729
+ sync({
2730
+ persist: false
2731
+ })
2732
+ ], RpgCommonPlayer.prototype, "canMove");
2733
+ __decorateClass([
2734
+ sync()
2735
+ ], RpgCommonPlayer.prototype, "hitbox");
2736
+ __decorateClass([
2737
+ sync()
2738
+ ], RpgCommonPlayer.prototype, "_gold");
2739
+ __decorateClass([
2740
+ sync()
2741
+ ], RpgCommonPlayer.prototype, "animationName");
2742
+ __decorateClass([
2743
+ sync()
2744
+ ], RpgCommonPlayer.prototype, "hpSignal");
2745
+ __decorateClass([
2746
+ sync()
2747
+ ], RpgCommonPlayer.prototype, "spSignal");
2748
+ __decorateClass([
2749
+ sync()
2750
+ ], RpgCommonPlayer.prototype, "_exp");
2751
+ __decorateClass([
2752
+ sync()
2753
+ ], RpgCommonPlayer.prototype, "_level");
2754
+ __decorateClass([
2755
+ sync()
2756
+ ], RpgCommonPlayer.prototype, "_class");
2757
+ __decorateClass([
2758
+ sync(Item)
2759
+ ], RpgCommonPlayer.prototype, "items");
2760
+ __decorateClass([
2761
+ sync()
2762
+ ], RpgCommonPlayer.prototype, "equipments");
2763
+ __decorateClass([
2764
+ sync()
2765
+ ], RpgCommonPlayer.prototype, "states");
2766
+ __decorateClass([
2767
+ sync(Skill)
2768
+ ], RpgCommonPlayer.prototype, "skills");
2769
+ __decorateClass([
2770
+ sync()
2771
+ ], RpgCommonPlayer.prototype, "_effects");
2772
+ __decorateClass([
2773
+ sync()
2774
+ ], RpgCommonPlayer.prototype, "_through");
2775
+ __decorateClass([
2776
+ sync()
2777
+ ], RpgCommonPlayer.prototype, "_throughOtherPlayer");
2778
+ __decorateClass([
2779
+ sync()
2780
+ ], RpgCommonPlayer.prototype, "_throughEvent");
2781
+ __decorateClass([
2782
+ sync()
2783
+ ], RpgCommonPlayer.prototype, "_frequency");
2784
+ __decorateClass([
2785
+ sync()
2786
+ ], RpgCommonPlayer.prototype, "_frames");
2787
+ __decorateClass([
2788
+ sync()
2789
+ ], RpgCommonPlayer.prototype, "componentsTop");
2790
+ __decorateClass([
2791
+ sync()
2792
+ ], RpgCommonPlayer.prototype, "componentsBottom");
2793
+ __decorateClass([
2794
+ sync()
2795
+ ], RpgCommonPlayer.prototype, "componentsCenter");
2796
+ __decorateClass([
2797
+ sync()
2798
+ ], RpgCommonPlayer.prototype, "componentsLeft");
2799
+ __decorateClass([
2800
+ sync()
2801
+ ], RpgCommonPlayer.prototype, "componentsRight");
2802
+ __decorateClass([
2803
+ connected()
2804
+ ], RpgCommonPlayer.prototype, "isConnected");
2805
+
2806
+ class Vector2 {
2807
+ /**
2808
+ * Creates a new Vector2
2809
+ *
2810
+ * @param x - X component (default: 0)
2811
+ * @param y - Y component (default: 0)
2812
+ */
2813
+ constructor(x = 0, y = 0) {
2814
+ this.x = x;
2815
+ this.y = y;
2816
+ }
2817
+ /**
2818
+ * Creates a copy of this vector
2819
+ *
2820
+ * @returns A new Vector2 with the same values
2821
+ */
2822
+ clone() {
2823
+ return new Vector2(this.x, this.y);
2824
+ }
2825
+ /**
2826
+ * Sets the components of this vector
2827
+ *
2828
+ * @param x - X component
2829
+ * @param y - Y component
2830
+ * @returns This vector for chaining
2831
+ */
2832
+ set(x, y) {
2833
+ this.x = x;
2834
+ this.y = y;
2835
+ return this;
2836
+ }
2837
+ /**
2838
+ * Copies values from another vector
2839
+ *
2840
+ * @param other - Vector to copy from
2841
+ * @returns This vector for chaining
2842
+ */
2843
+ copyFrom(other) {
2844
+ this.x = other.x;
2845
+ this.y = other.y;
2846
+ return this;
2847
+ }
2848
+ /**
2849
+ * Adds another vector to this vector (immutable)
2850
+ *
2851
+ * @param other - Vector to add
2852
+ * @returns New vector with the result
2853
+ */
2854
+ add(other) {
2855
+ return new Vector2(this.x + other.x, this.y + other.y);
2856
+ }
2857
+ /**
2858
+ * Adds another vector to this vector (in-place)
2859
+ *
2860
+ * @param other - Vector to add
2861
+ * @returns This vector for chaining
2862
+ */
2863
+ addInPlace(other) {
2864
+ this.x += other.x;
2865
+ this.y += other.y;
2866
+ return this;
2867
+ }
2868
+ /**
2869
+ * Subtracts another vector from this vector (immutable)
2870
+ *
2871
+ * @param other - Vector to subtract
2872
+ * @returns New vector with the result
2873
+ */
2874
+ sub(other) {
2875
+ return new Vector2(this.x - other.x, this.y - other.y);
2876
+ }
2877
+ /**
2878
+ * Subtracts another vector from this vector (in-place)
2879
+ *
2880
+ * @param other - Vector to subtract
2881
+ * @returns This vector for chaining
2882
+ */
2883
+ subInPlace(other) {
2884
+ this.x -= other.x;
2885
+ this.y -= other.y;
2886
+ return this;
2887
+ }
2888
+ /**
2889
+ * Multiplies this vector by a scalar (immutable)
2890
+ *
2891
+ * @param scalar - Scalar value
2892
+ * @returns New vector with the result
2893
+ */
2894
+ mul(scalar) {
2895
+ return new Vector2(this.x * scalar, this.y * scalar);
2896
+ }
2897
+ /**
2898
+ * Multiplies this vector by a scalar (in-place)
2899
+ *
2900
+ * @param scalar - Scalar value
2901
+ * @returns This vector for chaining
2902
+ */
2903
+ mulInPlace(scalar) {
2904
+ this.x *= scalar;
2905
+ this.y *= scalar;
2906
+ return this;
2907
+ }
2908
+ /**
2909
+ * Divides this vector by a scalar (immutable)
2910
+ *
2911
+ * @param scalar - Scalar value (must not be zero)
2912
+ * @returns New vector with the result
2913
+ */
2914
+ div(scalar) {
2915
+ return new Vector2(this.x / scalar, this.y / scalar);
2916
+ }
2917
+ /**
2918
+ * Divides this vector by a scalar (in-place)
2919
+ *
2920
+ * @param scalar - Scalar value (must not be zero)
2921
+ * @returns This vector for chaining
2922
+ */
2923
+ divInPlace(scalar) {
2924
+ this.x /= scalar;
2925
+ this.y /= scalar;
2926
+ return this;
2927
+ }
2928
+ /**
2929
+ * Calculates the dot product with another vector
2930
+ *
2931
+ * @param other - Vector to dot with
2932
+ * @returns Dot product value
2933
+ */
2934
+ dot(other) {
2935
+ return this.x * other.x + this.y * other.y;
2936
+ }
2937
+ /**
2938
+ * Calculates the 2D cross product (scalar result)
2939
+ *
2940
+ * @param other - Vector to cross with
2941
+ * @returns Cross product value (z-component of 3D cross product)
2942
+ */
2943
+ cross(other) {
2944
+ return this.x * other.y - this.y * other.x;
2945
+ }
2946
+ /**
2947
+ * Calculates the squared length (faster than length, avoids sqrt)
2948
+ *
2949
+ * @returns Squared length
2950
+ */
2951
+ lengthSquared() {
2952
+ return this.x * this.x + this.y * this.y;
2953
+ }
2954
+ /**
2955
+ * Calculates the length (magnitude) of the vector
2956
+ *
2957
+ * @returns Length
2958
+ */
2959
+ length() {
2960
+ return Math.sqrt(this.lengthSquared());
2961
+ }
2962
+ /**
2963
+ * Normalizes this vector to unit length (immutable)
2964
+ *
2965
+ * @returns New normalized vector
2966
+ */
2967
+ normalize() {
2968
+ const len = this.length();
2969
+ if (len === 0) {
2970
+ return new Vector2(0, 0);
2971
+ }
2972
+ return this.div(len);
2973
+ }
2974
+ /**
2975
+ * Normalizes this vector to unit length (in-place)
2976
+ *
2977
+ * @returns This vector for chaining
2978
+ */
2979
+ normalizeInPlace() {
2980
+ const len = this.length();
2981
+ if (len === 0) {
2982
+ this.x = 0;
2983
+ this.y = 0;
2984
+ } else {
2985
+ this.divInPlace(len);
2986
+ }
2987
+ return this;
2988
+ }
2989
+ /**
2990
+ * Calculates the distance to another vector
2991
+ *
2992
+ * @param other - Target vector
2993
+ * @returns Distance
2994
+ */
2995
+ distanceTo(other) {
2996
+ return this.sub(other).length();
2997
+ }
2998
+ /**
2999
+ * Calculates the squared distance to another vector (faster)
3000
+ *
3001
+ * @param other - Target vector
3002
+ * @returns Squared distance
3003
+ */
3004
+ distanceToSquared(other) {
3005
+ return this.sub(other).lengthSquared();
3006
+ }
3007
+ /**
3008
+ * Rotates this vector by an angle in radians (immutable)
3009
+ *
3010
+ * @param angle - Angle in radians
3011
+ * @returns New rotated vector
3012
+ */
3013
+ rotate(angle) {
3014
+ const cos = Math.cos(angle);
3015
+ const sin = Math.sin(angle);
3016
+ return new Vector2(
3017
+ this.x * cos - this.y * sin,
3018
+ this.x * sin + this.y * cos
3019
+ );
3020
+ }
3021
+ /**
3022
+ * Rotates this vector by an angle in radians (in-place)
3023
+ *
3024
+ * @param angle - Angle in radians
3025
+ * @returns This vector for chaining
3026
+ */
3027
+ rotateInPlace(angle) {
3028
+ const cos = Math.cos(angle);
3029
+ const sin = Math.sin(angle);
3030
+ const x = this.x * cos - this.y * sin;
3031
+ const y = this.x * sin + this.y * cos;
3032
+ this.x = x;
3033
+ this.y = y;
3034
+ return this;
3035
+ }
3036
+ /**
3037
+ * Calculates the angle of this vector in radians
3038
+ *
3039
+ * @returns Angle in radians (range: -π to π)
3040
+ */
3041
+ angle() {
3042
+ return Math.atan2(this.y, this.x);
3043
+ }
3044
+ /**
3045
+ * Linearly interpolates between this vector and another
3046
+ *
3047
+ * @param other - Target vector
3048
+ * @param t - Interpolation factor (0 to 1)
3049
+ * @returns New interpolated vector
3050
+ */
3051
+ lerp(other, t) {
3052
+ return new Vector2(
3053
+ this.x + (other.x - this.x) * t,
3054
+ this.y + (other.y - this.y) * t
3055
+ );
3056
+ }
3057
+ /**
3058
+ * Checks if this vector equals another (with epsilon tolerance)
3059
+ *
3060
+ * @param other - Vector to compare
3061
+ * @param epsilon - Tolerance for comparison (default: 1e-5)
3062
+ * @returns True if vectors are approximately equal
3063
+ */
3064
+ equals(other, epsilon = 1e-5) {
3065
+ return Math.abs(this.x - other.x) < epsilon && Math.abs(this.y - other.y) < epsilon;
3066
+ }
3067
+ /**
3068
+ * Returns a string representation of this vector
3069
+ *
3070
+ * @returns String representation
3071
+ */
3072
+ toString() {
3073
+ return `Vector2(${this.x}, ${this.y})`;
3074
+ }
3075
+ static {
3076
+ /**
3077
+ * Static zero vector
3078
+ */
3079
+ this.ZERO = new Vector2(0, 0);
3080
+ }
3081
+ static {
3082
+ /**
3083
+ * Static unit X vector
3084
+ */
3085
+ this.UNIT_X = new Vector2(1, 0);
3086
+ }
3087
+ static {
3088
+ /**
3089
+ * Static unit Y vector
3090
+ */
3091
+ this.UNIT_Y = new Vector2(0, 1);
3092
+ }
3093
+ }
3094
+
3095
+ const ModulesToken = "ModulesToken";
3096
+ function RpgModule(options) {
3097
+ return (target) => {
3098
+ if (options.hooks) {
3099
+ target.hooks = options.hooks;
3100
+ }
3101
+ for (let key in options) {
3102
+ target.prototype[key] = options[key];
3103
+ }
3104
+ };
3105
+ }
3106
+ class Hooks {
3107
+ constructor(modules, namespace) {
3108
+ this.modules = modules;
3109
+ this.namespace = namespace;
3110
+ /**
3111
+ * Store of all module hooks by ID
3112
+ */
3113
+ this.moduleHooks = {};
3114
+ /**
3115
+ * Store of all hook functions by ID
3116
+ */
3117
+ this.hookFunctions = {};
3118
+ this.init();
3119
+ }
3120
+ init() {
3121
+ for (const module of this.modules) {
3122
+ for (const type in module) {
3123
+ const hookObject = module[type];
3124
+ for (const hook in hookObject) {
3125
+ const hookFunction = hookObject[hook];
3126
+ if (hookFunction) {
3127
+ const hookId = `${this.namespace}-${type}-${hook}`;
3128
+ if (!this.moduleHooks[hookId]) {
3129
+ this.moduleHooks[hookId] = new Subject();
3130
+ }
3131
+ if (!this.hookFunctions[hookId]) {
3132
+ this.hookFunctions[hookId] = [];
3133
+ }
3134
+ if (!this.hookFunctions[hookId].includes(hookFunction)) {
3135
+ this.hookFunctions[hookId].push(hookFunction);
3136
+ }
3137
+ }
3138
+ }
3139
+ }
3140
+ }
3141
+ return this.moduleHooks;
3142
+ }
3143
+ /**
3144
+ * Call hooks for a specific ID, passing arguments to all subscribed hooks
3145
+ *
3146
+ * @param hookId - The unique identifier of the module hook
3147
+ * @param args - Arguments to pass to the hook functions
3148
+ * @returns An Observable that emits an array with all hook results when subscribed
3149
+ * @example
3150
+ * ```ts
3151
+ * // Call all hook functions for the ID 'my-namespace-type-hook'
3152
+ * callHooks('my-namespace-type-hook', { x: 10, y: 20 }).subscribe(results => {
3153
+ * console.log('Hook results:', results); // Array of all hook function results
3154
+ * });
3155
+ *
3156
+ * // Hook functions are only executed when you subscribe to the returned Observable
3157
+ * const observable = callHooks('my-namespace-type-hook', player);
3158
+ * // ... later ...
3159
+ * observable.subscribe(results => {
3160
+ * // Process results array
3161
+ * });
3162
+ * ```
3163
+ */
3164
+ callHooks(hookId, ...args) {
3165
+ if (!this.moduleHooks[hookId]) {
3166
+ this.moduleHooks[hookId] = new Subject();
3167
+ }
3168
+ return new Observable((subscriber) => {
3169
+ if (this.hookFunctions[hookId] && this.hookFunctions[hookId].length > 0) {
3170
+ const hookResults$ = from(this.hookFunctions[hookId]).pipe(
3171
+ mergeMap((hookFunction) => {
3172
+ let result;
3173
+ try {
3174
+ result = hookFunction(...args);
3175
+ return from(Promise.resolve(result));
3176
+ } catch (error) {
3177
+ subscriber.error(error);
3178
+ return [];
3179
+ }
3180
+ }),
3181
+ toArray()
3182
+ // Collect all results into an array
3183
+ );
3184
+ const subscription = hookResults$.subscribe({
3185
+ next: (results) => {
3186
+ this.moduleHooks[hookId].next(results);
3187
+ subscriber.next(results);
3188
+ subscriber.complete();
3189
+ },
3190
+ error: (err) => {
3191
+ subscriber.error(err);
3192
+ }
3193
+ });
3194
+ return () => {
3195
+ subscription.unsubscribe();
3196
+ };
3197
+ } else {
3198
+ subscriber.next([]);
3199
+ subscriber.complete();
3200
+ return () => {
3201
+ };
3202
+ }
3203
+ });
3204
+ }
3205
+ }
3206
+ function provideModules(modules, namespace, transform) {
3207
+ return {
3208
+ provide: ModulesToken,
3209
+ useFactory: (context) => {
3210
+ modules = transform ? transform(modules, context) : modules;
3211
+ return new Hooks(modules, namespace);
3212
+ }
3213
+ };
3214
+ }
3215
+ function findModules(context, namespace) {
3216
+ let modules = [];
3217
+ for (let key in context["values"]) {
3218
+ if (key.endsWith("Module" + namespace)) {
3219
+ modules.push(context["values"][key].values.get("__default__"));
3220
+ }
3221
+ }
3222
+ return modules;
3223
+ }
3224
+
3225
+ var __defProp = Object.defineProperty;
3226
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3227
+
3228
+ // src/inject.ts
3229
+ var DEFAULT_INSTANCE_KEY = "__default__";
3230
+ function toTokenName(token) {
3231
+ return typeof token === "function" ? token.name : token;
3232
+ }
3233
+ __name(toTokenName, "toTokenName");
3234
+ function toInstanceKey(name) {
3235
+ return name ?? DEFAULT_INSTANCE_KEY;
3236
+ }
3237
+ __name(toInstanceKey, "toInstanceKey");
3238
+ function getRecord(context, token) {
3239
+ return context.get("inject:" + toTokenName(token));
3240
+ }
3241
+ __name(getRecord, "getRecord");
3242
+ function ensureRecord(context, token) {
3243
+ const key = "inject:" + toTokenName(token);
3244
+ let record = context.get(key);
3245
+ if (!record) {
3246
+ record = {
3247
+ multi: false,
3248
+ values: /* @__PURE__ */ new Map(),
3249
+ injected: /* @__PURE__ */ new Set()
3250
+ };
3251
+ }
3252
+ context.set(key, record);
3253
+ return record;
3254
+ }
3255
+ __name(ensureRecord, "ensureRecord");
3256
+ function provide(context, token, value, options = {}) {
3257
+ const record = ensureRecord(context, token);
3258
+ const instanceKey = toInstanceKey(options.name);
3259
+ if (options.multi) {
3260
+ record.multi = true;
3261
+ }
3262
+ if (!record.multi && instanceKey !== DEFAULT_INSTANCE_KEY) {
3263
+ record.multi = true;
3264
+ }
3265
+ record.values.set(instanceKey, value);
3266
+ return value;
3267
+ }
3268
+ __name(provide, "provide");
3269
+ function isInjected(context, token, options = {}) {
3270
+ const record = getRecord(context, token);
3271
+ if (!record) {
3272
+ return false;
3273
+ }
3274
+ if (options.name) {
3275
+ return record.injected.has(toInstanceKey(options.name));
3276
+ }
3277
+ if (record.multi) {
3278
+ return record.injected.size > 0;
3279
+ }
3280
+ return record.injected.has(DEFAULT_INSTANCE_KEY);
3281
+ }
3282
+ __name(isInjected, "isInjected");
3283
+ function isProvided(context, token, options = {}) {
3284
+ const record = getRecord(context, token);
3285
+ if (!record) {
3286
+ return false;
3287
+ }
3288
+ if (options.name) {
3289
+ return record.values.has(toInstanceKey(options.name));
3290
+ }
3291
+ if (record.multi) {
3292
+ return record.values.size > 0;
3293
+ }
3294
+ return record.values.has(DEFAULT_INSTANCE_KEY);
3295
+ }
3296
+ __name(isProvided, "isProvided");
3297
+ function hasInstance(context, token, options = {}) {
3298
+ return isProvided(context, token, options);
3299
+ }
3300
+ __name(hasInstance, "hasInstance");
3301
+ function handleMissingInjection(token, options) {
3302
+ const name = toTokenName(token);
3303
+ if (options.name) {
3304
+ throw new Error(`Injection provider ${name} with name ${options.name} not found`);
3305
+ }
3306
+ throw new Error(`Injection provider ${name} not found`);
3307
+ }
3308
+ __name(handleMissingInjection, "handleMissingInjection");
3309
+ function markInjected(record, key) {
3310
+ record.injected.add(key);
3311
+ }
3312
+ __name(markInjected, "markInjected");
3313
+ function markAllInjected(record) {
3314
+ for (const key of record.values.keys()) {
3315
+ record.injected.add(key);
3316
+ }
3317
+ }
3318
+ __name(markAllInjected, "markAllInjected");
3319
+ function inject$1(context, token, options = {}) {
3320
+ const record = getRecord(context, token);
3321
+ if (!record) {
3322
+ if (options.optional) {
3323
+ return options.multi ? [] : void 0;
3324
+ }
3325
+ return handleMissingInjection(token, options);
3326
+ }
3327
+ if (options.name) {
3328
+ const instanceKey = toInstanceKey(options.name);
3329
+ if (!record.values.has(instanceKey)) {
3330
+ if (options.optional) {
3331
+ return void 0;
3332
+ }
3333
+ return handleMissingInjection(token, options);
3334
+ }
3335
+ const value2 = record.values.get(instanceKey);
3336
+ markInjected(record, instanceKey);
3337
+ return value2;
3338
+ }
3339
+ if (options.multi || record.multi) {
3340
+ if (record.values.size === 0) {
3341
+ if (options.optional) {
3342
+ return [];
3343
+ }
3344
+ return handleMissingInjection(token, options);
3345
+ }
3346
+ markAllInjected(record);
3347
+ return Array.from(record.values.values());
3348
+ }
3349
+ const value = record.values.get(DEFAULT_INSTANCE_KEY);
3350
+ if (value === void 0) {
3351
+ if (options.optional) {
3352
+ return void 0;
3353
+ }
3354
+ return handleMissingInjection(token, options);
3355
+ }
3356
+ markInjected(record, DEFAULT_INSTANCE_KEY);
3357
+ return value;
3358
+ }
3359
+ __name(inject$1, "inject");
3360
+ function override(providers, newProvider, options) {
3361
+ let { upsert = false, key } = options ?? {};
3362
+ if (!key) {
3363
+ key = typeof newProvider === "function" ? newProvider.name : newProvider.provide;
3364
+ }
3365
+ const flatProviders = providers.flat();
3366
+ const exists = flatProviders.some((provider) => {
3367
+ if (typeof provider === "function") {
3368
+ return provider.name === key;
3369
+ } else if (typeof provider === "object") {
3370
+ return provider.provide === key;
3371
+ }
3372
+ return false;
3373
+ });
3374
+ const mappedProviders = flatProviders.map((provider) => {
3375
+ if (typeof provider === "function" && provider.name === key) {
3376
+ return newProvider;
3377
+ } else if (typeof provider === "object" && provider.provide === key) {
3378
+ return newProvider;
3379
+ }
3380
+ return provider;
3381
+ });
3382
+ if (upsert && !exists) {
3383
+ mappedProviders.push(newProvider);
3384
+ }
3385
+ return mappedProviders;
3386
+ }
3387
+ __name(override, "override");
3388
+ function findProviders(providers, name) {
3389
+ const results = [];
3390
+ for (const provider of providers) {
3391
+ if (Array.isArray(provider)) {
3392
+ results.push(...findProviders(provider, name));
3393
+ } else if (findProvider(provider, name)) {
3394
+ results.push(provider);
3395
+ }
3396
+ }
3397
+ return results;
3398
+ }
3399
+ __name(findProviders, "findProviders");
3400
+ function findProvider(providers, name) {
3401
+ if (!Array.isArray(providers)) {
3402
+ if (typeof providers === "object" && "provide" in providers) {
3403
+ const provider = providers;
3404
+ const providerName = typeof provider.provide === "function" ? provider.provide.name : provider.provide;
3405
+ if (name instanceof RegExp) {
3406
+ if (name.test(providerName)) return providers;
3407
+ } else {
3408
+ if (providerName === name) return providers;
3409
+ }
3410
+ }
3411
+ return null;
3412
+ }
3413
+ for (const provider of providers) {
3414
+ if (Array.isArray(provider)) {
3415
+ const found = findProvider(provider, name);
3416
+ if (found) return found;
3417
+ continue;
3418
+ }
3419
+ if (typeof provider === "object" && "provide" in provider) {
3420
+ const providerName = typeof provider.provide === "function" ? provider.provide.name : provider.provide;
3421
+ if (name instanceof RegExp) {
3422
+ if (name.test(providerName)) return provider;
3423
+ } else {
3424
+ if (providerName === name) return provider;
3425
+ }
3426
+ }
3427
+ }
3428
+ return null;
3429
+ }
3430
+ __name(findProvider, "findProvider");
3431
+
3432
+ // src/merge-config.ts
3433
+ function processProvider(mergedConfig, baseConfig, provider) {
3434
+ if (Array.isArray(provider)) {
3435
+ for (const nestedProvider of provider) {
3436
+ processProvider(mergedConfig, baseConfig, nestedProvider);
3437
+ }
3438
+ return;
3439
+ }
3440
+ const existingProvider = findProvider(baseConfig.providers, provider.provide);
3441
+ if (existingProvider) {
3442
+ mergedConfig.providers = override(mergedConfig.providers, provider);
3443
+ } else {
3444
+ mergedConfig.providers.push(provider);
3445
+ }
3446
+ }
3447
+ __name(processProvider, "processProvider");
3448
+ function mergeConfig(baseConfig, config) {
3449
+ const mergedConfig = {
3450
+ ...baseConfig,
3451
+ ...config,
3452
+ providers: [
3453
+ ...baseConfig.providers
3454
+ ]
3455
+ // Start with a copy of base providers
3456
+ };
3457
+ for (const provider of config.providers) {
3458
+ processProvider(mergedConfig, baseConfig, provider);
3459
+ }
3460
+ return mergedConfig;
3461
+ }
3462
+ __name(mergeConfig, "mergeConfig");
3463
+
3464
+ // src/provider.ts
3465
+ function extractProvideOptions(source) {
3466
+ if (!source) {
3467
+ return void 0;
3468
+ }
3469
+ const { multi, name } = source;
3470
+ if (multi === void 0 && name === void 0) {
3471
+ return void 0;
3472
+ }
3473
+ return {
3474
+ multi,
3475
+ name
3476
+ };
3477
+ }
3478
+ __name(extractProvideOptions, "extractProvideOptions");
3479
+ function getDeps(provider) {
3480
+ if (typeof provider === "function") {
3481
+ return provider.deps ?? [];
3482
+ }
3483
+ return provider.deps ?? [];
3484
+ }
3485
+ __name(getDeps, "getDeps");
3486
+ function sortProviders(providers) {
3487
+ const tokenName = /* @__PURE__ */ __name((t) => typeof t === "function" ? t.name : t, "tokenName");
3488
+ const map = /* @__PURE__ */ new Map();
3489
+ for (const p of providers) {
3490
+ const token = tokenName(typeof p === "function" ? p : p.provide);
3491
+ const list = map.get(token);
3492
+ if (list) {
3493
+ list.push(p);
3494
+ } else {
3495
+ map.set(token, [
3496
+ p
3497
+ ]);
3498
+ }
3499
+ }
3500
+ const result = [];
3501
+ const visited = /* @__PURE__ */ new Set();
3502
+ const stack = /* @__PURE__ */ new Set();
3503
+ const visit = /* @__PURE__ */ __name((token) => {
3504
+ const name = tokenName(token);
3505
+ if (visited.has(name)) return;
3506
+ if (stack.has(name)) {
3507
+ throw new Error(`Circular dependency detected for provider ${name}`);
3508
+ }
3509
+ stack.add(name);
3510
+ const providersForToken = map.get(name);
3511
+ if (providersForToken) {
3512
+ for (const provider of providersForToken) {
3513
+ for (const dep of getDeps(provider)) {
3514
+ visit(dep);
3515
+ }
3516
+ result.push(provider);
3517
+ }
3518
+ visited.add(name);
3519
+ }
3520
+ stack.delete(name);
3521
+ }, "visit");
3522
+ for (const p of providers) {
3523
+ const token = typeof p === "function" ? p : p.provide;
3524
+ visit(token);
3525
+ }
3526
+ return result;
3527
+ }
3528
+ __name(sortProviders, "sortProviders");
3529
+ async function injector(context, providers) {
3530
+ providers = providers.flat();
3531
+ providers = sortProviders(providers);
3532
+ for (const provider of providers) {
3533
+ let token;
3534
+ let instance;
3535
+ let options;
3536
+ if (typeof provider === "function") {
3537
+ token = provider;
3538
+ instance = new provider(context);
3539
+ const diOptions = extractProvideOptions(provider.diOptions ?? provider.di);
3540
+ options = diOptions;
3541
+ } else {
3542
+ token = provider.provide;
3543
+ options = extractProvideOptions(provider);
3544
+ const provideUserClass = provider.useClass;
3545
+ const isClass = typeof provideUserClass === "function";
3546
+ if (isClass) {
3547
+ instance = new provideUserClass(context);
3548
+ } else if ("useValue" in provider) {
3549
+ instance = provider.useValue;
3550
+ } else if ("useFactory" in provider) {
3551
+ instance = provider.useFactory?.(context);
3552
+ if (instance instanceof Promise) {
3553
+ instance = await instance;
3554
+ }
3555
+ } else if ("useExisting" in provider) {
3556
+ instance = inject$1(context, provider.useExisting);
3557
+ }
3558
+ }
3559
+ provide(context, token, instance, options);
3560
+ }
3561
+ }
3562
+ __name(injector, "injector");
3563
+
3564
+ // src/context.ts
3565
+ var Context = class {
3566
+ static {
3567
+ __name(this, "Context");
3568
+ }
3569
+ /** Internal storage for injected values */
3570
+ values = {};
3571
+ /**
3572
+ * Sets a value in the context
3573
+ * @param key - Unique identifier for the value
3574
+ * @param value - Value to store
3575
+ */
3576
+ set(key, value) {
3577
+ this.values[key] = value;
3578
+ }
3579
+ /**
3580
+ * Retrieves a value from the context
3581
+ * @param key - Unique identifier for the value
3582
+ * @returns The stored value or undefined if not found
3583
+ */
3584
+ get(key) {
3585
+ return this.values[key];
3586
+ }
3587
+ };
3588
+
3589
+ let context$1 = null;
3590
+ function inject(service, _context) {
3591
+ const c = _context ?? context$1;
3592
+ if (!c) throw new Error("Context is not set. use setInject() to set the context");
3593
+ return inject$1(c, service);
3594
+ }
3595
+ function setInject(_context) {
3596
+ context$1 = _context;
3597
+ }
3598
+ function clearInject() {
3599
+ context$1 = null;
3600
+ }
3601
+
3602
+ const context = new Context();
3603
+ context["side"] = "server";
3604
+
3605
+ const MAP_UPDATE_TOKEN_HEADER = "x-rpgjs-map-update-token";
3606
+ const MAP_UPDATE_TOKEN_ENV = "RPGJS_MAP_UPDATE_TOKEN";
3607
+ function getRuntimeProcess() {
3608
+ return globalThis.process;
3609
+ }
3610
+ function readEnvVariable(name) {
3611
+ const value = getRuntimeProcess()?.env?.[name];
3612
+ return typeof value === "string" ? value : void 0;
3613
+ }
3614
+ function getWorkingDirectory() {
3615
+ const cwd = getRuntimeProcess()?.cwd;
3616
+ if (typeof cwd !== "function") {
3617
+ return void 0;
3618
+ }
3619
+ try {
3620
+ return cwd();
3621
+ } catch {
3622
+ return void 0;
3623
+ }
3624
+ }
3625
+ function normalizeRoomMapId(roomId) {
3626
+ return roomId.startsWith("map-") ? roomId.slice(4) : roomId;
3627
+ }
3628
+ function toBasePathPrefix(basePath) {
3629
+ const trimmed = basePath.trim();
3630
+ if (!trimmed) {
3631
+ return "";
3632
+ }
3633
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
3634
+ }
3635
+ function extractFileLikeMapDefinition(maps, mapId) {
3636
+ for (const mapDef of maps) {
3637
+ if (typeof mapDef === "object" && mapDef) {
3638
+ const candidateId = typeof mapDef.id === "string" ? mapDef.id.replace(/^map-/, "") : "";
3639
+ if (candidateId === mapId) {
3640
+ return mapDef;
3641
+ }
3642
+ continue;
3643
+ }
3644
+ if (typeof mapDef === "string") {
3645
+ const fileName = mapDef.split("/").pop()?.replace(/\.tmx$/i, "");
3646
+ if (fileName === mapId) {
3647
+ return { id: mapId, file: mapDef };
3648
+ }
3649
+ }
3650
+ }
3651
+ return null;
3652
+ }
3653
+ async function fetchTextByUrl(url) {
3654
+ try {
3655
+ const response = await fetch(url);
3656
+ if (!response.ok) {
3657
+ return null;
3658
+ }
3659
+ return await response.text();
3660
+ } catch {
3661
+ return null;
3662
+ }
3663
+ }
3664
+ async function readTextByFilePath(pathLike) {
3665
+ try {
3666
+ const { readFile } = await import('node:fs/promises');
3667
+ const { isAbsolute, join } = await import('node:path');
3668
+ const cwd = getWorkingDirectory();
3669
+ const candidates = isAbsolute(pathLike) || !cwd ? [pathLike] : [pathLike, join(cwd, pathLike)];
3670
+ for (const candidate of candidates) {
3671
+ try {
3672
+ return await readFile(candidate, "utf8");
3673
+ } catch {
3674
+ continue;
3675
+ }
3676
+ }
3677
+ } catch {
3678
+ return null;
3679
+ }
3680
+ return null;
3681
+ }
3682
+ function getTiledBasePaths(paths) {
3683
+ const values = [
3684
+ ...paths || [],
3685
+ readEnvVariable("RPGJS_TILED_BASE_PATH"),
3686
+ "map",
3687
+ "data",
3688
+ "assets/data",
3689
+ "assets/map"
3690
+ ].filter((value) => !!value);
3691
+ return Array.from(new Set(values));
3692
+ }
3693
+ function resolveMapUpdateToken(explicitToken) {
3694
+ return explicitToken ?? readEnvVariable(MAP_UPDATE_TOKEN_ENV) ?? "";
3695
+ }
3696
+ function createMapUpdateHeaders(token, init) {
3697
+ const headers = new Headers(init);
3698
+ if (!headers.has("content-type")) {
3699
+ headers.set("content-type", "application/json");
3700
+ }
3701
+ const resolvedToken = resolveMapUpdateToken(token);
3702
+ if (resolvedToken) {
3703
+ headers.set(MAP_UPDATE_TOKEN_HEADER, resolvedToken);
3704
+ }
3705
+ return headers;
3706
+ }
3707
+ function readMapUpdateToken(headers) {
3708
+ const directToken = headers.get(MAP_UPDATE_TOKEN_HEADER);
3709
+ if (directToken) {
3710
+ return directToken;
3711
+ }
3712
+ const authorization = headers.get("authorization");
3713
+ if (!authorization) {
3714
+ return "";
3715
+ }
3716
+ const [scheme, value] = authorization.split(/\s+/, 2);
3717
+ if (scheme?.toLowerCase() !== "bearer" || !value) {
3718
+ return "";
3719
+ }
3720
+ return value.trim();
3721
+ }
3722
+ function isMapUpdateAuthorized(headers, expectedToken) {
3723
+ const requiredToken = resolveMapUpdateToken(expectedToken);
3724
+ if (!requiredToken) {
3725
+ return true;
3726
+ }
3727
+ return readMapUpdateToken(headers) === requiredToken;
3728
+ }
3729
+ async function resolveMapDocument(mapId, mapDefinition, options) {
3730
+ if (typeof mapDefinition?.data === "string" && mapDefinition.data.includes("<map")) {
3731
+ return { xml: mapDefinition.data };
3732
+ }
3733
+ if (typeof mapDefinition?.file === "string") {
3734
+ const file = mapDefinition.file.trim();
3735
+ if (file.includes("<map")) {
3736
+ return { xml: file };
3737
+ }
3738
+ if (/^https?:\/\//i.test(file)) {
3739
+ const xml = await fetchTextByUrl(file);
3740
+ if (xml) {
3741
+ return { xml, sourceUrl: file };
3742
+ }
3743
+ }
3744
+ if (file.startsWith("/") && options.host) {
3745
+ const sourceUrl = `http://${options.host}${file}`;
3746
+ const xml = await fetchTextByUrl(sourceUrl);
3747
+ if (xml) {
3748
+ return { xml, sourceUrl };
3749
+ }
3750
+ }
3751
+ const xmlFromFile = await readTextByFilePath(file);
3752
+ if (xmlFromFile) {
3753
+ return { xml: xmlFromFile };
3754
+ }
3755
+ }
3756
+ if (options.host) {
3757
+ for (const basePath of getTiledBasePaths(options.tiledBasePaths)) {
3758
+ const prefix = toBasePathPrefix(basePath);
3759
+ const sourceUrl = `http://${options.host}${prefix}/${mapId}.tmx`;
3760
+ const xml = await fetchTextByUrl(sourceUrl);
3761
+ if (xml) {
3762
+ return { xml, sourceUrl };
3763
+ }
3764
+ }
3765
+ }
3766
+ return { xml: "" };
3767
+ }
3768
+ async function enrichMapWithParsedTiledData(payload, options = {}) {
3769
+ if (payload?.parsedMap || typeof payload?.id !== "string") {
3770
+ return;
3771
+ }
3772
+ const maps = Array.isArray(payload.__maps) ? payload.__maps : [];
3773
+ const mapDefinition = extractFileLikeMapDefinition(maps, payload.id);
3774
+ const mapDoc = await resolveMapDocument(payload.id, mapDefinition, options);
3775
+ if (!mapDoc.xml) {
3776
+ return;
3777
+ }
3778
+ try {
3779
+ const tiledModuleName = "@canvasengine/tiled";
3780
+ const tiledModule = await import(
3781
+ /* @vite-ignore */
3782
+ tiledModuleName
3783
+ );
3784
+ const TiledParser = tiledModule?.TiledParser;
3785
+ if (!TiledParser) {
3786
+ return;
3787
+ }
3788
+ const mapParser = new TiledParser(mapDoc.xml);
3789
+ const parsedMap = mapParser.parseMap();
3790
+ const tilesets = Array.isArray(parsedMap?.tilesets) ? parsedMap.tilesets : [];
3791
+ const mergedTilesets = [];
3792
+ for (const tileset of tilesets) {
3793
+ if (!tileset?.source) {
3794
+ mergedTilesets.push(tileset);
3795
+ continue;
3796
+ }
3797
+ let tilesetUrl;
3798
+ if (mapDoc.sourceUrl) {
3799
+ try {
3800
+ tilesetUrl = new URL(tileset.source, mapDoc.sourceUrl).toString();
3801
+ } catch {
3802
+ tilesetUrl = void 0;
3803
+ }
3804
+ } else if (options.host) {
3805
+ const prefix = toBasePathPrefix(getTiledBasePaths(options.tiledBasePaths)[0] || "map");
3806
+ const candidatePath = tileset.source.startsWith("/") ? tileset.source : `${prefix}/${tileset.source}`.replace(/\/{2,}/g, "/");
3807
+ tilesetUrl = `http://${options.host}${candidatePath.startsWith("/") ? candidatePath : `/${candidatePath}`}`;
3808
+ }
3809
+ const tilesetRaw = tilesetUrl ? await fetchTextByUrl(tilesetUrl) : await readTextByFilePath(tileset.source);
3810
+ if (!tilesetRaw) {
3811
+ mergedTilesets.push(tileset);
3812
+ continue;
3813
+ }
3814
+ try {
3815
+ const tilesetParser = new TiledParser(tilesetRaw);
3816
+ const parsedTileset = tilesetParser.parseTileset();
3817
+ mergedTilesets.push({
3818
+ ...tileset,
3819
+ ...parsedTileset
3820
+ });
3821
+ } catch {
3822
+ mergedTilesets.push(tileset);
3823
+ }
3824
+ }
3825
+ parsedMap.tilesets = mergedTilesets;
3826
+ payload.data = mapDoc.xml;
3827
+ payload.parsedMap = parsedMap;
3828
+ if (typeof parsedMap?.width === "number" && typeof parsedMap?.tilewidth === "number") {
3829
+ payload.width = parsedMap.width * parsedMap.tilewidth;
3830
+ }
3831
+ if (typeof parsedMap?.height === "number" && typeof parsedMap?.tileheight === "number") {
3832
+ payload.height = parsedMap.height * parsedMap.tileheight;
3833
+ }
3834
+ } catch {
3835
+ return;
3836
+ }
3837
+ }
3838
+ async function updateMap(roomId, rpgServer, options = {}) {
3839
+ if (!roomId.startsWith("map-")) {
3840
+ return;
3841
+ }
3842
+ try {
3843
+ const mapId = normalizeRoomMapId(roomId);
3844
+ const serverMaps = Array.isArray(rpgServer.maps) ? rpgServer.maps : [];
3845
+ const defaultMapPayload = {
3846
+ id: mapId,
3847
+ width: 0,
3848
+ height: 0,
3849
+ events: [],
3850
+ __maps: serverMaps
3851
+ };
3852
+ await enrichMapWithParsedTiledData(defaultMapPayload, options);
3853
+ delete defaultMapPayload.__maps;
3854
+ const headers = createMapUpdateHeaders(options.mapUpdateToken, options.headers);
3855
+ await rpgServer.onRequest?.({
3856
+ url: `http://localhost/parties/main/${roomId}/map/update`,
3857
+ method: "POST",
3858
+ headers,
3859
+ json: async () => defaultMapPayload,
3860
+ text: async () => JSON.stringify(defaultMapPayload)
3861
+ });
3862
+ console.log(`Initialized map for room ${roomId} via POST /map/update`);
3863
+ } catch (error) {
3864
+ console.warn(`Failed initializing map for room ${roomId}:`, error);
3865
+ }
3866
+ }
3867
+
3868
+ function provideServerModules(modules) {
3869
+ return provideModules(modules, "server", (modules2, context) => {
3870
+ const mainModuleServer = findModules(context, "Server");
3871
+ modules2 = [...mainModuleServer, ...modules2];
3872
+ modules2 = modules2.map((module) => {
3873
+ if (typeof module === "function") {
3874
+ const instance = new module();
3875
+ const moduleObj = {};
3876
+ for (const key in instance) {
3877
+ moduleObj[key] = instance[key];
3878
+ }
3879
+ module = moduleObj;
3880
+ }
3881
+ if ("server" in module) {
3882
+ module = module.server;
3883
+ }
3884
+ if (module.player?.props) {
3885
+ module = {
3886
+ ...module,
3887
+ playerProps: {
3888
+ load: (player) => {
3889
+ player.setSync(module.player.props);
3890
+ }
3891
+ }
3892
+ };
3893
+ }
3894
+ if (module.maps && Array.isArray(module.maps)) {
3895
+ const maps = [...module.maps];
3896
+ module = {
3897
+ ...module,
3898
+ maps: {
3899
+ load: (engine) => {
3900
+ maps.forEach((map) => {
3901
+ let mapInstance;
3902
+ if (typeof map === "function") {
3903
+ const MapClass = map;
3904
+ mapInstance = {
3905
+ id: MapClass.prototype?.id ?? MapClass.id,
3906
+ file: MapClass.prototype?.file ?? MapClass.file,
3907
+ type: MapClass.type,
3908
+ name: MapClass.prototype?.name,
3909
+ sounds: MapClass.prototype?.sounds,
3910
+ weather: MapClass.prototype?.weather,
3911
+ lowMemory: MapClass.prototype?.lowMemory,
3912
+ stopAllSoundsBeforeJoin: MapClass.prototype?.stopAllSoundsBeforeJoin,
3913
+ events: MapClass.prototype?._events,
3914
+ syncSchema: MapClass.prototype?.$schema,
3915
+ onLoad: MapClass.prototype?.onLoad,
3916
+ onJoin: MapClass.prototype?.onJoin,
3917
+ onLeave: MapClass.prototype?.onLeave
3918
+ };
3919
+ } else {
3920
+ mapInstance = map;
3921
+ }
3922
+ engine.maps.push(mapInstance);
3923
+ });
3924
+ }
3925
+ }
3926
+ };
3927
+ }
3928
+ if (module.worldMaps && Array.isArray(module.worldMaps)) {
3929
+ const worldMaps = [...module.worldMaps];
3930
+ module = {
3931
+ ...module,
3932
+ worldMaps: {
3933
+ load: (engine) => {
3934
+ worldMaps.forEach((worldMap) => {
3935
+ engine.createDynamicWorldMaps(worldMap);
3936
+ });
3937
+ }
3938
+ }
3939
+ };
3940
+ }
3941
+ if (module.database) {
3942
+ const database = module.database;
3943
+ module = {
3944
+ ...module,
3945
+ databaseHooks: {
3946
+ load: async (engine) => {
3947
+ const data = typeof database === "function" ? await database(engine) : database;
3948
+ if (!data || typeof data !== "object") {
3949
+ return;
3950
+ }
3951
+ for (const key in data) {
3952
+ engine.addInDatabase(key, data[key]);
3953
+ }
3954
+ }
3955
+ }
3956
+ };
3957
+ }
3958
+ return module;
3959
+ });
3960
+ return modules2;
3961
+ });
3962
+ }
3963
+
3964
+ export { updateMap as $, MAP_UPDATE_TOKEN_ENV as A, BehaviorSubject as B, users as C, DELETE_TOKEN as D, setInject as E, injector as F, RpgModule as G, context$1 as H, Item as I, clearInject as J, provideServerModules as K, ArraySubject as L, ModulesToken as M, ObjectSubject as N, Observable as O, effect as P, isArraySubject as Q, RpgCommonPlayer as R, SafeSubscriber as S, isComputed as T, isObjectSubject as U, Vector2 as V, isSignal as W, linkedSignal as X, untracked as Y, resolveMapUpdateToken as Z, __spreadArray as _, Subject as a, createMapUpdateHeaders as a0, readMapUpdateToken as a1, __read as b, createErrorClass as c, createStatesSnapshotDeep as d, signal as e, id as f, generateShortUUID as g, sync as h, innerFrom as i, getByPath as j, createStatesSnapshot as k, load as l, Direction as m, inject as n, operate as o, persist as p, computed as q, Skill as r, syncClass as s, type as t, combineLatest as u, inject$1 as v, context as w, finalize as x, isMapUpdateAuthorized as y, MAP_UPDATE_TOKEN_HEADER as z };
3965
+ //# sourceMappingURL=module-CuaepWlN.js.map