@effect-ak/tg-bot 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -20,3555 +20,47 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
- BatchUpdateResult: () => BatchUpdateResult,
24
- BotPollSettings: () => BotPollSettings,
25
- BotPollSettingsTag: () => BotPollSettingsTag,
26
23
  BotResponse: () => BotResponse,
27
- BotRunService: () => BotRunService,
28
- BotTgClientTag: () => BotTgClientTag,
29
- BotUpdateHandlersTag: () => BotUpdateHandlersTag,
30
- HandleUpdateError: () => HandleUpdateError,
24
+ createBot: () => createBot,
31
25
  createBotContext: () => createBotContext,
32
- createWebhookHandler: () => createWebhookHandler,
26
+ createWebhook: () => createWebhook,
33
27
  defineBot: () => defineBot,
34
28
  extractUpdate: () => extractUpdate,
35
- handleEntireBatch: () => handleEntireBatch,
36
- handleOneByOne: () => handleOneByOne,
37
- handleOneUpdate: () => handleOneUpdate,
38
- handleUpdates: () => handleUpdates,
39
- launchBot: () => launchBot,
40
- runTgChatBot: () => runTgChatBot
29
+ runBot: () => runBot
41
30
  });
42
31
  module.exports = __toCommonJS(index_exports);
43
32
 
44
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Function.js
45
- var isFunction = (input) => typeof input === "function";
46
- var dual = function(arity, body) {
47
- if (typeof arity === "function") {
48
- return function() {
49
- if (arity(arguments)) {
50
- return body.apply(this, arguments);
51
- }
52
- return (self) => body(self, ...arguments);
53
- };
54
- }
55
- switch (arity) {
56
- case 0:
57
- case 1:
58
- throw new RangeError(`Invalid arity ${arity}`);
59
- case 2:
60
- return function(a, b) {
61
- if (arguments.length >= 2) {
62
- return body(a, b);
63
- }
64
- return function(self) {
65
- return body(self, a);
66
- };
67
- };
68
- case 3:
69
- return function(a, b, c) {
70
- if (arguments.length >= 3) {
71
- return body(a, b, c);
72
- }
73
- return function(self) {
74
- return body(self, a, b);
75
- };
76
- };
77
- case 4:
78
- return function(a, b, c, d) {
79
- if (arguments.length >= 4) {
80
- return body(a, b, c, d);
81
- }
82
- return function(self) {
83
- return body(self, a, b, c);
84
- };
85
- };
86
- case 5:
87
- return function(a, b, c, d, e) {
88
- if (arguments.length >= 5) {
89
- return body(a, b, c, d, e);
90
- }
91
- return function(self) {
92
- return body(self, a, b, c, d);
93
- };
94
- };
95
- default:
96
- return function() {
97
- if (arguments.length >= arity) {
98
- return body.apply(this, arguments);
99
- }
100
- const args2 = arguments;
101
- return function(self) {
102
- return body(self, ...args2);
103
- };
104
- };
105
- }
106
- };
107
- var identity = (a) => a;
108
- var constant = (value) => () => value;
109
- var constTrue = /* @__PURE__ */ constant(true);
110
- var constFalse = /* @__PURE__ */ constant(false);
111
- var constUndefined = /* @__PURE__ */ constant(void 0);
112
- var constVoid = constUndefined;
113
- function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) {
114
- switch (arguments.length) {
115
- case 1:
116
- return a;
117
- case 2:
118
- return ab(a);
119
- case 3:
120
- return bc(ab(a));
121
- case 4:
122
- return cd(bc(ab(a)));
123
- case 5:
124
- return de(cd(bc(ab(a))));
125
- case 6:
126
- return ef(de(cd(bc(ab(a)))));
127
- case 7:
128
- return fg(ef(de(cd(bc(ab(a))))));
129
- case 8:
130
- return gh(fg(ef(de(cd(bc(ab(a)))))));
131
- case 9:
132
- return hi(gh(fg(ef(de(cd(bc(ab(a))))))));
133
- default: {
134
- let ret = arguments[0];
135
- for (let i = 1; i < arguments.length; i++) {
136
- ret = arguments[i](ret);
137
- }
138
- return ret;
139
- }
140
- }
141
- }
142
-
143
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Equivalence.js
144
- var make = (isEquivalent) => (self, that) => self === that || isEquivalent(self, that);
145
-
146
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/version.js
147
- var moduleVersion = "3.12.0";
148
- var getCurrentVersion = () => moduleVersion;
149
-
150
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/GlobalValue.js
151
- var globalStoreId = /* @__PURE__ */ Symbol.for(`effect/GlobalValue/globalStoreId/${/* @__PURE__ */ getCurrentVersion()}`);
152
- if (!(globalStoreId in globalThis)) {
153
- ;
154
- globalThis[globalStoreId] = /* @__PURE__ */ new Map();
155
- }
156
- var globalStore = globalThis[globalStoreId];
157
- var globalValue = (id, compute) => {
158
- if (!globalStore.has(id)) {
159
- globalStore.set(id, compute());
160
- }
161
- return globalStore.get(id);
162
- };
163
-
164
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Predicate.js
165
- var isFunction2 = isFunction;
166
- var isRecordOrArray = (input) => typeof input === "object" && input !== null;
167
- var isObject = (input) => isRecordOrArray(input) || isFunction2(input);
168
- var hasProperty = /* @__PURE__ */ dual(2, (self, property) => isObject(self) && property in self);
169
- var isTagged = /* @__PURE__ */ dual(2, (self, tag) => hasProperty(self, "_tag") && self["_tag"] === tag);
170
-
171
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/errors.js
172
- var getBugErrorMessage = (message) => `BUG: ${message} - please report an issue at https://github.com/Effect-TS/effect/issues`;
173
-
174
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Utils.js
175
- var GenKindTypeId = /* @__PURE__ */ Symbol.for("effect/Gen/GenKind");
176
- var GenKindImpl = class {
177
- value;
178
- constructor(value) {
179
- this.value = value;
180
- }
181
- /**
182
- * @since 2.0.0
183
- */
184
- get _F() {
185
- return identity;
186
- }
187
- /**
188
- * @since 2.0.0
189
- */
190
- get _R() {
191
- return (_) => _;
192
- }
193
- /**
194
- * @since 2.0.0
195
- */
196
- get _O() {
197
- return (_) => _;
198
- }
199
- /**
200
- * @since 2.0.0
201
- */
202
- get _E() {
203
- return (_) => _;
204
- }
205
- /**
206
- * @since 2.0.0
207
- */
208
- [GenKindTypeId] = GenKindTypeId;
209
- /**
210
- * @since 2.0.0
211
- */
212
- [Symbol.iterator]() {
213
- return new SingleShotGen(this);
214
- }
215
- };
216
- var SingleShotGen = class _SingleShotGen {
217
- self;
218
- called = false;
219
- constructor(self) {
220
- this.self = self;
221
- }
222
- /**
223
- * @since 2.0.0
224
- */
225
- next(a) {
226
- return this.called ? {
227
- value: a,
228
- done: true
229
- } : (this.called = true, {
230
- value: this.self,
231
- done: false
232
- });
233
- }
234
- /**
235
- * @since 2.0.0
236
- */
237
- return(a) {
238
- return {
239
- value: a,
240
- done: true
241
- };
242
- }
243
- /**
244
- * @since 2.0.0
245
- */
246
- throw(e) {
247
- throw e;
248
- }
249
- /**
250
- * @since 2.0.0
251
- */
252
- [Symbol.iterator]() {
253
- return new _SingleShotGen(this.self);
254
- }
255
- };
256
- var MUL_HI = 1481765933 >>> 0;
257
- var MUL_LO = 1284865837 >>> 0;
258
- var YieldWrapTypeId = /* @__PURE__ */ Symbol.for("effect/Utils/YieldWrap");
259
- var YieldWrap = class {
260
- /**
261
- * @since 3.0.6
262
- */
263
- #value;
264
- constructor(value) {
265
- this.#value = value;
266
- }
267
- /**
268
- * @since 3.0.6
269
- */
270
- [YieldWrapTypeId]() {
271
- return this.#value;
272
- }
273
- };
274
- function yieldWrapGet(self) {
275
- if (typeof self === "object" && self !== null && YieldWrapTypeId in self) {
276
- return self[YieldWrapTypeId]();
277
- }
278
- throw new Error(getBugErrorMessage("yieldWrapGet"));
279
- }
280
- var structuralRegionState = /* @__PURE__ */ globalValue("effect/Utils/isStructuralRegion", () => ({
281
- enabled: false,
282
- tester: void 0
283
- }));
284
- var genConstructor = function* () {
285
- }.constructor;
286
-
287
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Hash.js
288
- var randomHashCache = /* @__PURE__ */ globalValue(/* @__PURE__ */ Symbol.for("effect/Hash/randomHashCache"), () => /* @__PURE__ */ new WeakMap());
289
- var symbol = /* @__PURE__ */ Symbol.for("effect/Hash");
290
- var hash = (self) => {
291
- if (structuralRegionState.enabled === true) {
292
- return 0;
293
- }
294
- switch (typeof self) {
295
- case "number":
296
- return number(self);
297
- case "bigint":
298
- return string(self.toString(10));
299
- case "boolean":
300
- return string(String(self));
301
- case "symbol":
302
- return string(String(self));
303
- case "string":
304
- return string(self);
305
- case "undefined":
306
- return string("undefined");
307
- case "function":
308
- case "object": {
309
- if (self === null) {
310
- return string("null");
311
- } else if (self instanceof Date) {
312
- return hash(self.toISOString());
313
- } else if (isHash(self)) {
314
- return self[symbol]();
315
- } else {
316
- return random(self);
317
- }
318
- }
319
- default:
320
- throw new Error(`BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues`);
321
- }
322
- };
323
- var random = (self) => {
324
- if (!randomHashCache.has(self)) {
325
- randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)));
326
- }
327
- return randomHashCache.get(self);
328
- };
329
- var combine = (b) => (self) => self * 53 ^ b;
330
- var optimize = (n) => n & 3221225471 | n >>> 1 & 1073741824;
331
- var isHash = (u) => hasProperty(u, symbol);
332
- var number = (n) => {
333
- if (n !== n || n === Infinity) {
334
- return 0;
335
- }
336
- let h = n | 0;
337
- if (h !== n) {
338
- h ^= n * 4294967295;
339
- }
340
- while (n > 4294967295) {
341
- h ^= n /= 4294967295;
342
- }
343
- return optimize(h);
344
- };
345
- var string = (str) => {
346
- let h = 5381, i = str.length;
347
- while (i) {
348
- h = h * 33 ^ str.charCodeAt(--i);
349
- }
350
- return optimize(h);
351
- };
352
- var structureKeys = (o, keys2) => {
353
- let h = 12289;
354
- for (let i = 0; i < keys2.length; i++) {
355
- h ^= pipe(string(keys2[i]), combine(hash(o[keys2[i]])));
356
- }
357
- return optimize(h);
358
- };
359
- var structure = (o) => structureKeys(o, Object.keys(o));
360
- var array = (arr) => {
361
- let h = 6151;
362
- for (let i = 0; i < arr.length; i++) {
363
- h = pipe(h, combine(hash(arr[i])));
364
- }
365
- return optimize(h);
366
- };
367
- var cached = function() {
368
- if (arguments.length === 1) {
369
- const self2 = arguments[0];
370
- return function(hash3) {
371
- Object.defineProperty(self2, symbol, {
372
- value() {
373
- return hash3;
374
- },
375
- enumerable: false
376
- });
377
- return hash3;
378
- };
379
- }
380
- const self = arguments[0];
381
- const hash2 = arguments[1];
382
- Object.defineProperty(self, symbol, {
383
- value() {
384
- return hash2;
385
- },
386
- enumerable: false
387
- });
388
- return hash2;
389
- };
390
-
391
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Equal.js
392
- var symbol2 = /* @__PURE__ */ Symbol.for("effect/Equal");
393
- function equals() {
394
- if (arguments.length === 1) {
395
- return (self) => compareBoth(self, arguments[0]);
396
- }
397
- return compareBoth(arguments[0], arguments[1]);
398
- }
399
- function compareBoth(self, that) {
400
- if (self === that) {
401
- return true;
402
- }
403
- const selfType = typeof self;
404
- if (selfType !== typeof that) {
405
- return false;
406
- }
407
- if (selfType === "object" || selfType === "function") {
408
- if (self !== null && that !== null) {
409
- if (isEqual(self) && isEqual(that)) {
410
- if (hash(self) === hash(that) && self[symbol2](that)) {
411
- return true;
412
- } else {
413
- return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
414
- }
415
- } else if (self instanceof Date && that instanceof Date) {
416
- return self.toISOString() === that.toISOString();
417
- }
418
- }
419
- if (structuralRegionState.enabled) {
420
- if (Array.isArray(self) && Array.isArray(that)) {
421
- return self.length === that.length && self.every((v, i) => compareBoth(v, that[i]));
422
- }
423
- if (Object.getPrototypeOf(self) === Object.prototype && Object.getPrototypeOf(self) === Object.prototype) {
424
- const keysSelf = Object.keys(self);
425
- const keysThat = Object.keys(that);
426
- if (keysSelf.length === keysThat.length) {
427
- for (const key of keysSelf) {
428
- if (!(key in that && compareBoth(self[key], that[key]))) {
429
- return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
430
- }
431
- }
432
- return true;
433
- }
434
- }
435
- return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
436
- }
437
- }
438
- return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self, that) : false;
439
- }
440
- var isEqual = (u) => hasProperty(u, symbol2);
441
-
442
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Inspectable.js
443
- var NodeInspectSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
444
- var toJSON = (x) => {
445
- try {
446
- if (hasProperty(x, "toJSON") && isFunction2(x["toJSON"]) && x["toJSON"].length === 0) {
447
- return x.toJSON();
448
- } else if (Array.isArray(x)) {
449
- return x.map(toJSON);
450
- }
451
- } catch (_) {
452
- return {};
453
- }
454
- return redact(x);
455
- };
456
- var format = (x) => JSON.stringify(x, null, 2);
457
- var BaseProto = {
458
- toJSON() {
459
- return toJSON(this);
460
- },
461
- [NodeInspectSymbol]() {
462
- return this.toJSON();
463
- },
464
- toString() {
465
- return format(this.toJSON());
466
- }
467
- };
468
- var Class = class {
469
- /**
470
- * @since 2.0.0
471
- */
472
- [NodeInspectSymbol]() {
473
- return this.toJSON();
474
- }
475
- /**
476
- * @since 2.0.0
477
- */
478
- toString() {
479
- return format(this.toJSON());
480
- }
481
- };
482
- var toStringUnknown = (u, whitespace = 2) => {
483
- if (typeof u === "string") {
484
- return u;
485
- }
486
- try {
487
- return typeof u === "object" ? stringifyCircular(u, whitespace) : String(u);
488
- } catch (_) {
489
- return String(u);
490
- }
491
- };
492
- var stringifyCircular = (obj, whitespace) => {
493
- let cache = [];
494
- const retVal = JSON.stringify(obj, (_key, value) => typeof value === "object" && value !== null ? cache.includes(value) ? void 0 : cache.push(value) && (redactableState.fiberRefs !== void 0 && isRedactable(value) ? value[symbolRedactable](redactableState.fiberRefs) : value) : value, whitespace);
495
- cache = void 0;
496
- return retVal;
497
- };
498
- var symbolRedactable = /* @__PURE__ */ Symbol.for("effect/Inspectable/Redactable");
499
- var isRedactable = (u) => typeof u === "object" && u !== null && symbolRedactable in u;
500
- var redactableState = /* @__PURE__ */ globalValue("effect/Inspectable/redactableState", () => ({
501
- fiberRefs: void 0
502
- }));
503
- var redact = (u) => {
504
- if (isRedactable(u) && redactableState.fiberRefs !== void 0) {
505
- return u[symbolRedactable](redactableState.fiberRefs);
506
- }
507
- return u;
508
- };
509
-
510
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Pipeable.js
511
- var pipeArguments = (self, args2) => {
512
- switch (args2.length) {
513
- case 0:
514
- return self;
515
- case 1:
516
- return args2[0](self);
517
- case 2:
518
- return args2[1](args2[0](self));
519
- case 3:
520
- return args2[2](args2[1](args2[0](self)));
521
- case 4:
522
- return args2[3](args2[2](args2[1](args2[0](self))));
523
- case 5:
524
- return args2[4](args2[3](args2[2](args2[1](args2[0](self)))));
525
- case 6:
526
- return args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self))))));
527
- case 7:
528
- return args2[6](args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self)))))));
529
- case 8:
530
- return args2[7](args2[6](args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self))))))));
531
- case 9:
532
- return args2[8](args2[7](args2[6](args2[5](args2[4](args2[3](args2[2](args2[1](args2[0](self)))))))));
533
- default: {
534
- let ret = self;
535
- for (let i = 0, len = args2.length; i < len; i++) {
536
- ret = args2[i](ret);
537
- }
538
- return ret;
539
- }
540
- }
541
- };
542
-
543
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/opCodes/effect.js
544
- var OP_COMMIT = "Commit";
545
- var OP_FAILURE = "Failure";
546
- var OP_WITH_RUNTIME = "WithRuntime";
547
-
548
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/effectable.js
549
- var EffectTypeId = /* @__PURE__ */ Symbol.for("effect/Effect");
550
- var StreamTypeId = /* @__PURE__ */ Symbol.for("effect/Stream");
551
- var SinkTypeId = /* @__PURE__ */ Symbol.for("effect/Sink");
552
- var ChannelTypeId = /* @__PURE__ */ Symbol.for("effect/Channel");
553
- var effectVariance = {
554
- /* c8 ignore next */
555
- _R: (_) => _,
556
- /* c8 ignore next */
557
- _E: (_) => _,
558
- /* c8 ignore next */
559
- _A: (_) => _,
560
- _V: /* @__PURE__ */ getCurrentVersion()
561
- };
562
- var sinkVariance = {
563
- /* c8 ignore next */
564
- _A: (_) => _,
565
- /* c8 ignore next */
566
- _In: (_) => _,
567
- /* c8 ignore next */
568
- _L: (_) => _,
569
- /* c8 ignore next */
570
- _E: (_) => _,
571
- /* c8 ignore next */
572
- _R: (_) => _
573
- };
574
- var channelVariance = {
575
- /* c8 ignore next */
576
- _Env: (_) => _,
577
- /* c8 ignore next */
578
- _InErr: (_) => _,
579
- /* c8 ignore next */
580
- _InElem: (_) => _,
581
- /* c8 ignore next */
582
- _InDone: (_) => _,
583
- /* c8 ignore next */
584
- _OutErr: (_) => _,
585
- /* c8 ignore next */
586
- _OutElem: (_) => _,
587
- /* c8 ignore next */
588
- _OutDone: (_) => _
589
- };
590
- var EffectPrototype = {
591
- [EffectTypeId]: effectVariance,
592
- [StreamTypeId]: effectVariance,
593
- [SinkTypeId]: sinkVariance,
594
- [ChannelTypeId]: channelVariance,
595
- [symbol2](that) {
596
- return this === that;
597
- },
598
- [symbol]() {
599
- return cached(this, random(this));
600
- },
601
- [Symbol.iterator]() {
602
- return new SingleShotGen(new YieldWrap(this));
603
- },
604
- pipe() {
605
- return pipeArguments(this, arguments);
606
- }
607
- };
608
- var StructuralPrototype = {
609
- [symbol]() {
610
- return cached(this, structure(this));
611
- },
612
- [symbol2](that) {
613
- const selfKeys = Object.keys(this);
614
- const thatKeys = Object.keys(that);
615
- if (selfKeys.length !== thatKeys.length) {
616
- return false;
617
- }
618
- for (const key of selfKeys) {
619
- if (!(key in that && equals(this[key], that[key]))) {
620
- return false;
621
- }
622
- }
623
- return true;
624
- }
625
- };
626
- var CommitPrototype = {
627
- ...EffectPrototype,
628
- _op: OP_COMMIT
629
- };
630
- var StructuralCommitPrototype = {
631
- ...CommitPrototype,
632
- ...StructuralPrototype
633
- };
634
-
635
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/option.js
636
- var TypeId = /* @__PURE__ */ Symbol.for("effect/Option");
637
- var CommonProto = {
638
- ...EffectPrototype,
639
- [TypeId]: {
640
- _A: (_) => _
641
- },
642
- [NodeInspectSymbol]() {
643
- return this.toJSON();
644
- },
645
- toString() {
646
- return format(this.toJSON());
647
- }
648
- };
649
- var SomeProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
650
- _tag: "Some",
651
- _op: "Some",
652
- [symbol2](that) {
653
- return isOption(that) && isSome(that) && equals(this.value, that.value);
654
- },
655
- [symbol]() {
656
- return cached(this, combine(hash(this._tag))(hash(this.value)));
657
- },
658
- toJSON() {
659
- return {
660
- _id: "Option",
661
- _tag: this._tag,
662
- value: toJSON(this.value)
663
- };
664
- }
665
- });
666
- var NoneHash = /* @__PURE__ */ hash("None");
667
- var NoneProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto), {
668
- _tag: "None",
669
- _op: "None",
670
- [symbol2](that) {
671
- return isOption(that) && isNone(that);
672
- },
673
- [symbol]() {
674
- return NoneHash;
675
- },
676
- toJSON() {
677
- return {
678
- _id: "Option",
679
- _tag: this._tag
680
- };
681
- }
682
- });
683
- var isOption = (input) => hasProperty(input, TypeId);
684
- var isNone = (fa) => fa._tag === "None";
685
- var isSome = (fa) => fa._tag === "Some";
686
- var none = /* @__PURE__ */ Object.create(NoneProto);
687
- var some = (value) => {
688
- const a = Object.create(SomeProto);
689
- a.value = value;
690
- return a;
691
- };
692
-
693
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/either.js
694
- var TypeId2 = /* @__PURE__ */ Symbol.for("effect/Either");
695
- var CommonProto2 = {
696
- ...EffectPrototype,
697
- [TypeId2]: {
698
- _R: (_) => _
699
- },
700
- [NodeInspectSymbol]() {
701
- return this.toJSON();
702
- },
703
- toString() {
704
- return format(this.toJSON());
705
- }
706
- };
707
- var RightProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
708
- _tag: "Right",
709
- _op: "Right",
710
- [symbol2](that) {
711
- return isEither(that) && isRight(that) && equals(this.right, that.right);
712
- },
713
- [symbol]() {
714
- return combine(hash(this._tag))(hash(this.right));
715
- },
716
- toJSON() {
717
- return {
718
- _id: "Either",
719
- _tag: this._tag,
720
- right: toJSON(this.right)
721
- };
722
- }
723
- });
724
- var LeftProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(CommonProto2), {
725
- _tag: "Left",
726
- _op: "Left",
727
- [symbol2](that) {
728
- return isEither(that) && isLeft(that) && equals(this.left, that.left);
729
- },
730
- [symbol]() {
731
- return combine(hash(this._tag))(hash(this.left));
732
- },
733
- toJSON() {
734
- return {
735
- _id: "Either",
736
- _tag: this._tag,
737
- left: toJSON(this.left)
738
- };
739
- }
740
- });
741
- var isEither = (input) => hasProperty(input, TypeId2);
742
- var isLeft = (ma) => ma._tag === "Left";
743
- var isRight = (ma) => ma._tag === "Right";
744
- var left = (left3) => {
745
- const a = Object.create(LeftProto);
746
- a.left = left3;
747
- return a;
748
- };
749
- var right = (right3) => {
750
- const a = Object.create(RightProto);
751
- a.right = right3;
752
- return a;
753
- };
754
-
755
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Either.js
756
- var right2 = right;
757
- var left2 = left;
758
-
759
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Option.js
760
- var none2 = () => none;
761
- var some2 = some;
762
- var isNone2 = isNone;
763
- var isSome2 = isSome;
764
- var getOrElse = /* @__PURE__ */ dual(2, (self, onNone) => isNone2(self) ? onNone() : self.value);
765
- var getOrUndefined = /* @__PURE__ */ getOrElse(constUndefined);
766
-
767
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Array.js
768
- var fromIterable = (collection) => Array.isArray(collection) ? collection : Array.from(collection);
769
- var isArray = Array.isArray;
770
- var reverse = (self) => Array.from(self).reverse();
771
- var reduce = /* @__PURE__ */ dual(3, (self, b, f) => fromIterable(self).reduce((b2, a, i) => f(b2, a, i), b));
772
-
773
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Chunk.js
774
- var TypeId3 = /* @__PURE__ */ Symbol.for("effect/Chunk");
775
- function copy(src, srcPos, dest, destPos, len) {
776
- for (let i = srcPos; i < Math.min(src.length, srcPos + len); i++) {
777
- dest[destPos + i - srcPos] = src[i];
778
- }
779
- return dest;
780
- }
781
- var emptyArray = [];
782
- var getEquivalence = (isEquivalent) => make((self, that) => self.length === that.length && toReadonlyArray(self).every((value, i) => isEquivalent(value, unsafeGet(that, i))));
783
- var _equivalence = /* @__PURE__ */ getEquivalence(equals);
784
- var ChunkProto = {
785
- [TypeId3]: {
786
- _A: (_) => _
787
- },
788
- toString() {
789
- return format(this.toJSON());
790
- },
791
- toJSON() {
792
- return {
793
- _id: "Chunk",
794
- values: toReadonlyArray(this).map(toJSON)
795
- };
796
- },
797
- [NodeInspectSymbol]() {
798
- return this.toJSON();
799
- },
800
- [symbol2](that) {
801
- return isChunk(that) && _equivalence(this, that);
802
- },
803
- [symbol]() {
804
- return cached(this, array(toReadonlyArray(this)));
805
- },
806
- [Symbol.iterator]() {
807
- switch (this.backing._tag) {
808
- case "IArray": {
809
- return this.backing.array[Symbol.iterator]();
810
- }
811
- case "IEmpty": {
812
- return emptyArray[Symbol.iterator]();
813
- }
814
- default: {
815
- return toReadonlyArray(this)[Symbol.iterator]();
816
- }
817
- }
818
- },
819
- pipe() {
820
- return pipeArguments(this, arguments);
821
- }
822
- };
823
- var makeChunk = (backing) => {
824
- const chunk = Object.create(ChunkProto);
825
- chunk.backing = backing;
826
- switch (backing._tag) {
827
- case "IEmpty": {
828
- chunk.length = 0;
829
- chunk.depth = 0;
830
- chunk.left = chunk;
831
- chunk.right = chunk;
832
- break;
833
- }
834
- case "IConcat": {
835
- chunk.length = backing.left.length + backing.right.length;
836
- chunk.depth = 1 + Math.max(backing.left.depth, backing.right.depth);
837
- chunk.left = backing.left;
838
- chunk.right = backing.right;
839
- break;
840
- }
841
- case "IArray": {
842
- chunk.length = backing.array.length;
843
- chunk.depth = 0;
844
- chunk.left = _empty;
845
- chunk.right = _empty;
846
- break;
847
- }
848
- case "ISingleton": {
849
- chunk.length = 1;
850
- chunk.depth = 0;
851
- chunk.left = _empty;
852
- chunk.right = _empty;
853
- break;
854
- }
855
- case "ISlice": {
856
- chunk.length = backing.length;
857
- chunk.depth = backing.chunk.depth + 1;
858
- chunk.left = _empty;
859
- chunk.right = _empty;
860
- break;
861
- }
862
- }
863
- return chunk;
864
- };
865
- var isChunk = (u) => hasProperty(u, TypeId3);
866
- var _empty = /* @__PURE__ */ makeChunk({
867
- _tag: "IEmpty"
868
- });
869
- var empty = () => _empty;
870
- var make2 = (...as2) => as2.length === 1 ? of(as2[0]) : unsafeFromNonEmptyArray(as2);
871
- var of = (a) => makeChunk({
872
- _tag: "ISingleton",
873
- a
874
- });
875
- var fromIterable2 = (self) => isChunk(self) ? self : makeChunk({
876
- _tag: "IArray",
877
- array: fromIterable(self)
878
- });
879
- var copyToArray = (self, array2, initial) => {
880
- switch (self.backing._tag) {
881
- case "IArray": {
882
- copy(self.backing.array, 0, array2, initial, self.length);
883
- break;
884
- }
885
- case "IConcat": {
886
- copyToArray(self.left, array2, initial);
887
- copyToArray(self.right, array2, initial + self.left.length);
888
- break;
889
- }
890
- case "ISingleton": {
891
- array2[initial] = self.backing.a;
892
- break;
893
- }
894
- case "ISlice": {
895
- let i = 0;
896
- let j = initial;
897
- while (i < self.length) {
898
- array2[j] = unsafeGet(self, i);
899
- i += 1;
900
- j += 1;
901
- }
902
- break;
903
- }
904
- }
905
- };
906
- var toReadonlyArray_ = (self) => {
907
- switch (self.backing._tag) {
908
- case "IEmpty": {
909
- return emptyArray;
910
- }
911
- case "IArray": {
912
- return self.backing.array;
913
- }
914
- default: {
915
- const arr = new Array(self.length);
916
- copyToArray(self, arr, 0);
917
- self.backing = {
918
- _tag: "IArray",
919
- array: arr
920
- };
921
- self.left = _empty;
922
- self.right = _empty;
923
- self.depth = 0;
924
- return arr;
925
- }
926
- }
927
- };
928
- var toReadonlyArray = toReadonlyArray_;
929
- var reverseChunk = (self) => {
930
- switch (self.backing._tag) {
931
- case "IEmpty":
932
- case "ISingleton":
933
- return self;
934
- case "IArray": {
935
- return makeChunk({
936
- _tag: "IArray",
937
- array: reverse(self.backing.array)
938
- });
939
- }
940
- case "IConcat": {
941
- return makeChunk({
942
- _tag: "IConcat",
943
- left: reverse2(self.backing.right),
944
- right: reverse2(self.backing.left)
945
- });
946
- }
947
- case "ISlice":
948
- return unsafeFromArray(reverse(toReadonlyArray(self)));
949
- }
950
- };
951
- var reverse2 = reverseChunk;
952
- var unsafeFromArray = (self) => makeChunk({
953
- _tag: "IArray",
954
- array: self
955
- });
956
- var unsafeFromNonEmptyArray = (self) => unsafeFromArray(self);
957
- var unsafeGet = /* @__PURE__ */ dual(2, (self, index) => {
958
- switch (self.backing._tag) {
959
- case "IEmpty": {
960
- throw new Error(`Index out of bounds`);
961
- }
962
- case "ISingleton": {
963
- if (index !== 0) {
964
- throw new Error(`Index out of bounds`);
965
- }
966
- return self.backing.a;
967
- }
968
- case "IArray": {
969
- if (index >= self.length || index < 0) {
970
- throw new Error(`Index out of bounds`);
971
- }
972
- return self.backing.array[index];
973
- }
974
- case "IConcat": {
975
- return index < self.left.length ? unsafeGet(self.left, index) : unsafeGet(self.right, index - self.left.length);
976
- }
977
- case "ISlice": {
978
- return unsafeGet(self.backing.chunk, index + self.backing.offset);
979
- }
980
- }
981
- });
982
- var prepend = /* @__PURE__ */ dual(2, (self, elem) => appendAll(of(elem), self));
983
- var appendAll = /* @__PURE__ */ dual(2, (self, that) => {
984
- if (self.backing._tag === "IEmpty") {
985
- return that;
986
- }
987
- if (that.backing._tag === "IEmpty") {
988
- return self;
989
- }
990
- const diff = that.depth - self.depth;
991
- if (Math.abs(diff) <= 1) {
992
- return makeChunk({
993
- _tag: "IConcat",
994
- left: self,
995
- right: that
996
- });
997
- } else if (diff < -1) {
998
- if (self.left.depth >= self.right.depth) {
999
- const nr = appendAll(self.right, that);
1000
- return makeChunk({
1001
- _tag: "IConcat",
1002
- left: self.left,
1003
- right: nr
1004
- });
1005
- } else {
1006
- const nrr = appendAll(self.right.right, that);
1007
- if (nrr.depth === self.depth - 3) {
1008
- const nr = makeChunk({
1009
- _tag: "IConcat",
1010
- left: self.right.left,
1011
- right: nrr
1012
- });
1013
- return makeChunk({
1014
- _tag: "IConcat",
1015
- left: self.left,
1016
- right: nr
1017
- });
1018
- } else {
1019
- const nl = makeChunk({
1020
- _tag: "IConcat",
1021
- left: self.left,
1022
- right: self.right.left
1023
- });
1024
- return makeChunk({
1025
- _tag: "IConcat",
1026
- left: nl,
1027
- right: nrr
1028
- });
1029
- }
1030
- }
1031
- } else {
1032
- if (that.right.depth >= that.left.depth) {
1033
- const nl = appendAll(self, that.left);
1034
- return makeChunk({
1035
- _tag: "IConcat",
1036
- left: nl,
1037
- right: that.right
1038
- });
1039
- } else {
1040
- const nll = appendAll(self, that.left.left);
1041
- if (nll.depth === that.depth - 3) {
1042
- const nl = makeChunk({
1043
- _tag: "IConcat",
1044
- left: nll,
1045
- right: that.left.right
1046
- });
1047
- return makeChunk({
1048
- _tag: "IConcat",
1049
- left: nl,
1050
- right: that.right
1051
- });
1052
- } else {
1053
- const nr = makeChunk({
1054
- _tag: "IConcat",
1055
- left: that.left.right,
1056
- right: that.right
1057
- });
1058
- return makeChunk({
1059
- _tag: "IConcat",
1060
- left: nll,
1061
- right: nr
1062
- });
1063
- }
1064
- }
1065
- }
1066
- });
1067
- var isEmpty = (self) => self.length === 0;
1068
- var isNonEmpty = (self) => self.length > 0;
1069
- var unsafeHead = (self) => unsafeGet(self, 0);
1070
- var headNonEmpty = unsafeHead;
1071
-
1072
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/context.js
1073
- var TagTypeId = /* @__PURE__ */ Symbol.for("effect/Context/Tag");
1074
- var ReferenceTypeId = /* @__PURE__ */ Symbol.for("effect/Context/Reference");
1075
- var STMSymbolKey = "effect/STM";
1076
- var STMTypeId = /* @__PURE__ */ Symbol.for(STMSymbolKey);
1077
- var TagProto = {
1078
- ...EffectPrototype,
1079
- _op: "Tag",
1080
- [STMTypeId]: effectVariance,
1081
- [TagTypeId]: {
1082
- _Service: (_) => _,
1083
- _Identifier: (_) => _
1084
- },
1085
- toString() {
1086
- return format(this.toJSON());
1087
- },
1088
- toJSON() {
1089
- return {
1090
- _id: "Tag",
1091
- key: this.key,
1092
- stack: this.stack
1093
- };
1094
- },
1095
- [NodeInspectSymbol]() {
1096
- return this.toJSON();
1097
- },
1098
- of(self) {
1099
- return self;
1100
- },
1101
- context(self) {
1102
- return make3(this, self);
1103
- }
1104
- };
1105
- var ReferenceProto = {
1106
- ...TagProto,
1107
- [ReferenceTypeId]: ReferenceTypeId
1108
- };
1109
- var Tag = (id) => () => {
1110
- const limit = Error.stackTraceLimit;
1111
- Error.stackTraceLimit = 2;
1112
- const creationError = new Error();
1113
- Error.stackTraceLimit = limit;
1114
- function TagClass() {
1115
- }
1116
- Object.setPrototypeOf(TagClass, TagProto);
1117
- TagClass.key = id;
1118
- Object.defineProperty(TagClass, "stack", {
1119
- get() {
1120
- return creationError.stack;
1121
- }
1122
- });
1123
- return TagClass;
1124
- };
1125
- var Reference = () => (id, options) => {
1126
- const limit = Error.stackTraceLimit;
1127
- Error.stackTraceLimit = 2;
1128
- const creationError = new Error();
1129
- Error.stackTraceLimit = limit;
1130
- function ReferenceClass() {
1131
- }
1132
- Object.setPrototypeOf(ReferenceClass, ReferenceProto);
1133
- ReferenceClass.key = id;
1134
- ReferenceClass.defaultValue = options.defaultValue;
1135
- Object.defineProperty(ReferenceClass, "stack", {
1136
- get() {
1137
- return creationError.stack;
1138
- }
1139
- });
1140
- return ReferenceClass;
1141
- };
1142
- var TypeId4 = /* @__PURE__ */ Symbol.for("effect/Context");
1143
- var ContextProto = {
1144
- [TypeId4]: {
1145
- _Services: (_) => _
1146
- },
1147
- [symbol2](that) {
1148
- if (isContext(that)) {
1149
- if (this.unsafeMap.size === that.unsafeMap.size) {
1150
- for (const k of this.unsafeMap.keys()) {
1151
- if (!that.unsafeMap.has(k) || !equals(this.unsafeMap.get(k), that.unsafeMap.get(k))) {
1152
- return false;
1153
- }
1154
- }
1155
- return true;
1156
- }
1157
- }
1158
- return false;
1159
- },
1160
- [symbol]() {
1161
- return cached(this, number(this.unsafeMap.size));
1162
- },
1163
- pipe() {
1164
- return pipeArguments(this, arguments);
1165
- },
1166
- toString() {
1167
- return format(this.toJSON());
1168
- },
1169
- toJSON() {
1170
- return {
1171
- _id: "Context",
1172
- services: Array.from(this.unsafeMap).map(toJSON)
1173
- };
1174
- },
1175
- [NodeInspectSymbol]() {
1176
- return this.toJSON();
1177
- }
1178
- };
1179
- var makeContext = (unsafeMap) => {
1180
- const context = Object.create(ContextProto);
1181
- context.unsafeMap = unsafeMap;
1182
- return context;
1183
- };
1184
- var serviceNotFoundError = (tag) => {
1185
- const error = new Error(`Service not found${tag.key ? `: ${String(tag.key)}` : ""}`);
1186
- if (tag.stack) {
1187
- const lines = tag.stack.split("\n");
1188
- if (lines.length > 2) {
1189
- const afterAt = lines[2].match(/at (.*)/);
1190
- if (afterAt) {
1191
- error.message = error.message + ` (defined at ${afterAt[1]})`;
1192
- }
1193
- }
1194
- }
1195
- if (error.stack) {
1196
- const lines = error.stack.split("\n");
1197
- lines.splice(1, 3);
1198
- error.stack = lines.join("\n");
1199
- }
1200
- return error;
1201
- };
1202
- var isContext = (u) => hasProperty(u, TypeId4);
1203
- var make3 = (tag, service2) => makeContext(/* @__PURE__ */ new Map([[tag.key, service2]]));
1204
- var add = /* @__PURE__ */ dual(3, (self, tag, service2) => {
1205
- const map7 = new Map(self.unsafeMap);
1206
- map7.set(tag.key, service2);
1207
- return makeContext(map7);
1208
- });
1209
- var defaultValueCache = /* @__PURE__ */ globalValue("effect/Context/defaultValueCache", () => /* @__PURE__ */ new Map());
1210
- var getDefaultValue = (tag) => {
1211
- if (defaultValueCache.has(tag.key)) {
1212
- return defaultValueCache.get(tag.key);
1213
- }
1214
- const value = tag.defaultValue();
1215
- defaultValueCache.set(tag.key, value);
1216
- return value;
1217
- };
1218
- var unsafeGetReference = (self, tag) => {
1219
- return self.unsafeMap.has(tag.key) ? self.unsafeMap.get(tag.key) : getDefaultValue(tag);
1220
- };
1221
- var unsafeGet2 = /* @__PURE__ */ dual(2, (self, tag) => {
1222
- if (!self.unsafeMap.has(tag.key)) {
1223
- if (ReferenceTypeId in tag) return getDefaultValue(tag);
1224
- throw serviceNotFoundError(tag);
1225
- }
1226
- return self.unsafeMap.get(tag.key);
1227
- });
1228
- var merge = /* @__PURE__ */ dual(2, (self, that) => {
1229
- const map7 = new Map(self.unsafeMap);
1230
- for (const [tag, s] of that.unsafeMap) {
1231
- map7.set(tag, s);
1232
- }
1233
- return makeContext(map7);
1234
- });
1235
-
1236
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Context.js
1237
- var make4 = make3;
1238
- var add2 = add;
1239
- var unsafeGet3 = unsafeGet2;
1240
- var merge2 = merge;
1241
- var Tag2 = Tag;
1242
- var Reference2 = Reference;
1243
-
1244
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/hashMap/config.js
1245
- var SIZE = 5;
1246
- var BUCKET_SIZE = /* @__PURE__ */ Math.pow(2, SIZE);
1247
- var MASK = BUCKET_SIZE - 1;
1248
- var MAX_INDEX_NODE = BUCKET_SIZE / 2;
1249
- var MIN_ARRAY_NODE = BUCKET_SIZE / 4;
1250
-
1251
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/hashMap/bitwise.js
1252
- function popcount(x) {
1253
- x -= x >> 1 & 1431655765;
1254
- x = (x & 858993459) + (x >> 2 & 858993459);
1255
- x = x + (x >> 4) & 252645135;
1256
- x += x >> 8;
1257
- x += x >> 16;
1258
- return x & 127;
1259
- }
1260
- function hashFragment(shift, h) {
1261
- return h >>> shift & MASK;
1262
- }
1263
- function toBitmap(x) {
1264
- return 1 << x;
1265
- }
1266
- function fromBitmap(bitmap, bit) {
1267
- return popcount(bitmap & bit - 1);
1268
- }
1269
-
1270
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/stack.js
1271
- var make5 = (value, previous) => ({
1272
- value,
1273
- previous
1274
- });
1275
-
1276
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/hashMap/array.js
1277
- function arrayUpdate(mutate2, at, v, arr) {
1278
- let out = arr;
1279
- if (!mutate2) {
1280
- const len = arr.length;
1281
- out = new Array(len);
1282
- for (let i = 0; i < len; ++i) out[i] = arr[i];
1283
- }
1284
- out[at] = v;
1285
- return out;
1286
- }
1287
- function arraySpliceOut(mutate2, at, arr) {
1288
- const newLen = arr.length - 1;
1289
- let i = 0;
1290
- let g = 0;
1291
- let out = arr;
1292
- if (mutate2) {
1293
- i = g = at;
1294
- } else {
1295
- out = new Array(newLen);
1296
- while (i < at) out[g++] = arr[i++];
1297
- }
1298
- ;
1299
- ++i;
1300
- while (i <= newLen) out[g++] = arr[i++];
1301
- if (mutate2) {
1302
- out.length = newLen;
1303
- }
1304
- return out;
1305
- }
1306
- function arraySpliceIn(mutate2, at, v, arr) {
1307
- const len = arr.length;
1308
- if (mutate2) {
1309
- let i2 = len;
1310
- while (i2 >= at) arr[i2--] = arr[i2];
1311
- arr[at] = v;
1312
- return arr;
1313
- }
1314
- let i = 0, g = 0;
1315
- const out = new Array(len + 1);
1316
- while (i < at) out[g++] = arr[i++];
1317
- out[at] = v;
1318
- while (i < len) out[++g] = arr[i++];
1319
- return out;
1320
- }
1321
-
1322
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/hashMap/node.js
1323
- var EmptyNode = class _EmptyNode {
1324
- _tag = "EmptyNode";
1325
- modify(edit, _shift, f, hash2, key, size4) {
1326
- const v = f(none2());
1327
- if (isNone2(v)) return new _EmptyNode();
1328
- ++size4.value;
1329
- return new LeafNode(edit, hash2, key, v);
1330
- }
1331
- };
1332
- function isEmptyNode(a) {
1333
- return isTagged(a, "EmptyNode");
1334
- }
1335
- function isLeafNode(node) {
1336
- return isEmptyNode(node) || node._tag === "LeafNode" || node._tag === "CollisionNode";
1337
- }
1338
- function canEditNode(node, edit) {
1339
- return isEmptyNode(node) ? false : edit === node.edit;
1340
- }
1341
- var LeafNode = class _LeafNode {
1342
- edit;
1343
- hash;
1344
- key;
1345
- value;
1346
- _tag = "LeafNode";
1347
- constructor(edit, hash2, key, value) {
1348
- this.edit = edit;
1349
- this.hash = hash2;
1350
- this.key = key;
1351
- this.value = value;
1352
- }
1353
- modify(edit, shift, f, hash2, key, size4) {
1354
- if (equals(key, this.key)) {
1355
- const v2 = f(this.value);
1356
- if (v2 === this.value) return this;
1357
- else if (isNone2(v2)) {
1358
- ;
1359
- --size4.value;
1360
- return new EmptyNode();
1361
- }
1362
- if (canEditNode(this, edit)) {
1363
- this.value = v2;
1364
- return this;
1365
- }
1366
- return new _LeafNode(edit, hash2, key, v2);
1367
- }
1368
- const v = f(none2());
1369
- if (isNone2(v)) return this;
1370
- ++size4.value;
1371
- return mergeLeaves(edit, shift, this.hash, this, hash2, new _LeafNode(edit, hash2, key, v));
1372
- }
1373
- };
1374
- var CollisionNode = class _CollisionNode {
1375
- edit;
1376
- hash;
1377
- children;
1378
- _tag = "CollisionNode";
1379
- constructor(edit, hash2, children) {
1380
- this.edit = edit;
1381
- this.hash = hash2;
1382
- this.children = children;
1383
- }
1384
- modify(edit, shift, f, hash2, key, size4) {
1385
- if (hash2 === this.hash) {
1386
- const canEdit = canEditNode(this, edit);
1387
- const list = this.updateCollisionList(canEdit, edit, this.hash, this.children, f, key, size4);
1388
- if (list === this.children) return this;
1389
- return list.length > 1 ? new _CollisionNode(edit, this.hash, list) : list[0];
1390
- }
1391
- const v = f(none2());
1392
- if (isNone2(v)) return this;
1393
- ++size4.value;
1394
- return mergeLeaves(edit, shift, this.hash, this, hash2, new LeafNode(edit, hash2, key, v));
1395
- }
1396
- updateCollisionList(mutate2, edit, hash2, list, f, key, size4) {
1397
- const len = list.length;
1398
- for (let i = 0; i < len; ++i) {
1399
- const child = list[i];
1400
- if ("key" in child && equals(key, child.key)) {
1401
- const value = child.value;
1402
- const newValue2 = f(value);
1403
- if (newValue2 === value) return list;
1404
- if (isNone2(newValue2)) {
1405
- ;
1406
- --size4.value;
1407
- return arraySpliceOut(mutate2, i, list);
1408
- }
1409
- return arrayUpdate(mutate2, i, new LeafNode(edit, hash2, key, newValue2), list);
1410
- }
1411
- }
1412
- const newValue = f(none2());
1413
- if (isNone2(newValue)) return list;
1414
- ++size4.value;
1415
- return arrayUpdate(mutate2, len, new LeafNode(edit, hash2, key, newValue), list);
1416
- }
1417
- };
1418
- var IndexedNode = class _IndexedNode {
1419
- edit;
1420
- mask;
1421
- children;
1422
- _tag = "IndexedNode";
1423
- constructor(edit, mask, children) {
1424
- this.edit = edit;
1425
- this.mask = mask;
1426
- this.children = children;
1427
- }
1428
- modify(edit, shift, f, hash2, key, size4) {
1429
- const mask = this.mask;
1430
- const children = this.children;
1431
- const frag = hashFragment(shift, hash2);
1432
- const bit = toBitmap(frag);
1433
- const indx = fromBitmap(mask, bit);
1434
- const exists = mask & bit;
1435
- const canEdit = canEditNode(this, edit);
1436
- if (!exists) {
1437
- const _newChild = new EmptyNode().modify(edit, shift + SIZE, f, hash2, key, size4);
1438
- if (!_newChild) return this;
1439
- return children.length >= MAX_INDEX_NODE ? expand(edit, frag, _newChild, mask, children) : new _IndexedNode(edit, mask | bit, arraySpliceIn(canEdit, indx, _newChild, children));
1440
- }
1441
- const current = children[indx];
1442
- const child = current.modify(edit, shift + SIZE, f, hash2, key, size4);
1443
- if (current === child) return this;
1444
- let bitmap = mask;
1445
- let newChildren;
1446
- if (isEmptyNode(child)) {
1447
- bitmap &= ~bit;
1448
- if (!bitmap) return new EmptyNode();
1449
- if (children.length <= 2 && isLeafNode(children[indx ^ 1])) {
1450
- return children[indx ^ 1];
1451
- }
1452
- newChildren = arraySpliceOut(canEdit, indx, children);
1453
- } else {
1454
- newChildren = arrayUpdate(canEdit, indx, child, children);
1455
- }
1456
- if (canEdit) {
1457
- this.mask = bitmap;
1458
- this.children = newChildren;
1459
- return this;
1460
- }
1461
- return new _IndexedNode(edit, bitmap, newChildren);
1462
- }
1463
- };
1464
- var ArrayNode = class _ArrayNode {
1465
- edit;
1466
- size;
1467
- children;
1468
- _tag = "ArrayNode";
1469
- constructor(edit, size4, children) {
1470
- this.edit = edit;
1471
- this.size = size4;
1472
- this.children = children;
1473
- }
1474
- modify(edit, shift, f, hash2, key, size4) {
1475
- let count = this.size;
1476
- const children = this.children;
1477
- const frag = hashFragment(shift, hash2);
1478
- const child = children[frag];
1479
- const newChild = (child || new EmptyNode()).modify(edit, shift + SIZE, f, hash2, key, size4);
1480
- if (child === newChild) return this;
1481
- const canEdit = canEditNode(this, edit);
1482
- let newChildren;
1483
- if (isEmptyNode(child) && !isEmptyNode(newChild)) {
1484
- ;
1485
- ++count;
1486
- newChildren = arrayUpdate(canEdit, frag, newChild, children);
1487
- } else if (!isEmptyNode(child) && isEmptyNode(newChild)) {
1488
- ;
1489
- --count;
1490
- if (count <= MIN_ARRAY_NODE) {
1491
- return pack(edit, count, frag, children);
1492
- }
1493
- newChildren = arrayUpdate(canEdit, frag, new EmptyNode(), children);
1494
- } else {
1495
- newChildren = arrayUpdate(canEdit, frag, newChild, children);
1496
- }
1497
- if (canEdit) {
1498
- this.size = count;
1499
- this.children = newChildren;
1500
- return this;
1501
- }
1502
- return new _ArrayNode(edit, count, newChildren);
1503
- }
1504
- };
1505
- function pack(edit, count, removed, elements) {
1506
- const children = new Array(count - 1);
1507
- let g = 0;
1508
- let bitmap = 0;
1509
- for (let i = 0, len = elements.length; i < len; ++i) {
1510
- if (i !== removed) {
1511
- const elem = elements[i];
1512
- if (elem && !isEmptyNode(elem)) {
1513
- children[g++] = elem;
1514
- bitmap |= 1 << i;
1515
- }
1516
- }
1517
- }
1518
- return new IndexedNode(edit, bitmap, children);
1519
- }
1520
- function expand(edit, frag, child, bitmap, subNodes) {
1521
- const arr = [];
1522
- let bit = bitmap;
1523
- let count = 0;
1524
- for (let i = 0; bit; ++i) {
1525
- if (bit & 1) arr[i] = subNodes[count++];
1526
- bit >>>= 1;
1527
- }
1528
- arr[frag] = child;
1529
- return new ArrayNode(edit, count + 1, arr);
1530
- }
1531
- function mergeLeavesInner(edit, shift, h1, n1, h2, n2) {
1532
- if (h1 === h2) return new CollisionNode(edit, h1, [n2, n1]);
1533
- const subH1 = hashFragment(shift, h1);
1534
- const subH2 = hashFragment(shift, h2);
1535
- if (subH1 === subH2) {
1536
- return (child) => new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), [child]);
1537
- } else {
1538
- const children = subH1 < subH2 ? [n1, n2] : [n2, n1];
1539
- return new IndexedNode(edit, toBitmap(subH1) | toBitmap(subH2), children);
1540
- }
1541
- }
1542
- function mergeLeaves(edit, shift, h1, n1, h2, n2) {
1543
- let stack = void 0;
1544
- let currentShift = shift;
1545
- while (true) {
1546
- const res = mergeLeavesInner(edit, currentShift, h1, n1, h2, n2);
1547
- if (typeof res === "function") {
1548
- stack = make5(res, stack);
1549
- currentShift = currentShift + SIZE;
1550
- } else {
1551
- let final = res;
1552
- while (stack != null) {
1553
- final = stack.value(final);
1554
- stack = stack.previous;
1555
- }
1556
- return final;
1557
- }
1558
- }
1559
- }
1560
-
1561
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/hashMap.js
1562
- var HashMapSymbolKey = "effect/HashMap";
1563
- var HashMapTypeId = /* @__PURE__ */ Symbol.for(HashMapSymbolKey);
1564
- var HashMapProto = {
1565
- [HashMapTypeId]: HashMapTypeId,
1566
- [Symbol.iterator]() {
1567
- return new HashMapIterator(this, (k, v) => [k, v]);
1568
- },
1569
- [symbol]() {
1570
- let hash2 = hash(HashMapSymbolKey);
1571
- for (const item of this) {
1572
- hash2 ^= pipe(hash(item[0]), combine(hash(item[1])));
1573
- }
1574
- return cached(this, hash2);
1575
- },
1576
- [symbol2](that) {
1577
- if (isHashMap(that)) {
1578
- if (that._size !== this._size) {
1579
- return false;
1580
- }
1581
- for (const item of this) {
1582
- const elem = pipe(that, getHash(item[0], hash(item[0])));
1583
- if (isNone2(elem)) {
1584
- return false;
1585
- } else {
1586
- if (!equals(item[1], elem.value)) {
1587
- return false;
1588
- }
1589
- }
1590
- }
1591
- return true;
1592
- }
1593
- return false;
1594
- },
1595
- toString() {
1596
- return format(this.toJSON());
1597
- },
1598
- toJSON() {
1599
- return {
1600
- _id: "HashMap",
1601
- values: Array.from(this).map(toJSON)
1602
- };
1603
- },
1604
- [NodeInspectSymbol]() {
1605
- return this.toJSON();
1606
- },
1607
- pipe() {
1608
- return pipeArguments(this, arguments);
1609
- }
1610
- };
1611
- var makeImpl = (editable, edit, root, size4) => {
1612
- const map7 = Object.create(HashMapProto);
1613
- map7._editable = editable;
1614
- map7._edit = edit;
1615
- map7._root = root;
1616
- map7._size = size4;
1617
- return map7;
1618
- };
1619
- var HashMapIterator = class _HashMapIterator {
1620
- map;
1621
- f;
1622
- v;
1623
- constructor(map7, f) {
1624
- this.map = map7;
1625
- this.f = f;
1626
- this.v = visitLazy(this.map._root, this.f, void 0);
1627
- }
1628
- next() {
1629
- if (isNone2(this.v)) {
1630
- return {
1631
- done: true,
1632
- value: void 0
1633
- };
1634
- }
1635
- const v0 = this.v.value;
1636
- this.v = applyCont(v0.cont);
1637
- return {
1638
- done: false,
1639
- value: v0.value
1640
- };
1641
- }
1642
- [Symbol.iterator]() {
1643
- return new _HashMapIterator(this.map, this.f);
1644
- }
1645
- };
1646
- var applyCont = (cont) => cont ? visitLazyChildren(cont[0], cont[1], cont[2], cont[3], cont[4]) : none2();
1647
- var visitLazy = (node, f, cont = void 0) => {
1648
- switch (node._tag) {
1649
- case "LeafNode": {
1650
- if (isSome2(node.value)) {
1651
- return some2({
1652
- value: f(node.key, node.value.value),
1653
- cont
1654
- });
1655
- }
1656
- return applyCont(cont);
1657
- }
1658
- case "CollisionNode":
1659
- case "ArrayNode":
1660
- case "IndexedNode": {
1661
- const children = node.children;
1662
- return visitLazyChildren(children.length, children, 0, f, cont);
1663
- }
1664
- default: {
1665
- return applyCont(cont);
1666
- }
1667
- }
1668
- };
1669
- var visitLazyChildren = (len, children, i, f, cont) => {
1670
- while (i < len) {
1671
- const child = children[i++];
1672
- if (child && !isEmptyNode(child)) {
1673
- return visitLazy(child, f, [len, children, i, f, cont]);
1674
- }
1675
- }
1676
- return applyCont(cont);
1677
- };
1678
- var _empty2 = /* @__PURE__ */ makeImpl(false, 0, /* @__PURE__ */ new EmptyNode(), 0);
1679
- var empty3 = () => _empty2;
1680
- var isHashMap = (u) => hasProperty(u, HashMapTypeId);
1681
- var getHash = /* @__PURE__ */ dual(3, (self, key, hash2) => {
1682
- let node = self._root;
1683
- let shift = 0;
1684
- while (true) {
1685
- switch (node._tag) {
1686
- case "LeafNode": {
1687
- return equals(key, node.key) ? node.value : none2();
1688
- }
1689
- case "CollisionNode": {
1690
- if (hash2 === node.hash) {
1691
- const children = node.children;
1692
- for (let i = 0, len = children.length; i < len; ++i) {
1693
- const child = children[i];
1694
- if ("key" in child && equals(key, child.key)) {
1695
- return child.value;
1696
- }
1697
- }
1698
- }
1699
- return none2();
1700
- }
1701
- case "IndexedNode": {
1702
- const frag = hashFragment(shift, hash2);
1703
- const bit = toBitmap(frag);
1704
- if (node.mask & bit) {
1705
- node = node.children[fromBitmap(node.mask, bit)];
1706
- shift += SIZE;
1707
- break;
1708
- }
1709
- return none2();
1710
- }
1711
- case "ArrayNode": {
1712
- node = node.children[hashFragment(shift, hash2)];
1713
- if (node) {
1714
- shift += SIZE;
1715
- break;
1716
- }
1717
- return none2();
1718
- }
1719
- default:
1720
- return none2();
1721
- }
1722
- }
1723
- });
1724
- var set = /* @__PURE__ */ dual(3, (self, key, value) => modifyAt(self, key, () => some2(value)));
1725
- var setTree = /* @__PURE__ */ dual(3, (self, newRoot, newSize) => {
1726
- if (self._editable) {
1727
- ;
1728
- self._root = newRoot;
1729
- self._size = newSize;
1730
- return self;
1731
- }
1732
- return newRoot === self._root ? self : makeImpl(self._editable, self._edit, newRoot, newSize);
1733
- });
1734
- var keys = (self) => new HashMapIterator(self, (key) => key);
1735
- var size = (self) => self._size;
1736
- var beginMutation = (self) => makeImpl(true, self._edit + 1, self._root, self._size);
1737
- var modifyAt = /* @__PURE__ */ dual(3, (self, key, f) => modifyHash(self, key, hash(key), f));
1738
- var modifyHash = /* @__PURE__ */ dual(4, (self, key, hash2, f) => {
1739
- const size4 = {
1740
- value: self._size
1741
- };
1742
- const newRoot = self._root.modify(self._editable ? self._edit : NaN, 0, f, hash2, key, size4);
1743
- return pipe(self, setTree(newRoot, size4.value));
1744
- });
1745
- var forEach = /* @__PURE__ */ dual(2, (self, f) => reduce2(self, void 0, (_, value, key) => f(value, key)));
1746
- var reduce2 = /* @__PURE__ */ dual(3, (self, zero, f) => {
1747
- const root = self._root;
1748
- if (root._tag === "LeafNode") {
1749
- return isSome2(root.value) ? f(zero, root.value.value, root.key) : zero;
1750
- }
1751
- if (root._tag === "EmptyNode") {
1752
- return zero;
1753
- }
1754
- const toVisit = [root.children];
1755
- let children;
1756
- while (children = toVisit.pop()) {
1757
- for (let i = 0, len = children.length; i < len; ) {
1758
- const child = children[i++];
1759
- if (child && !isEmptyNode(child)) {
1760
- if (child._tag === "LeafNode") {
1761
- if (isSome2(child.value)) {
1762
- zero = f(zero, child.value.value, child.key);
1763
- }
1764
- } else {
1765
- toVisit.push(child.children);
1766
- }
1767
- }
1768
- }
1769
- }
1770
- return zero;
1771
- });
1772
-
1773
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/hashSet.js
1774
- var HashSetSymbolKey = "effect/HashSet";
1775
- var HashSetTypeId = /* @__PURE__ */ Symbol.for(HashSetSymbolKey);
1776
- var HashSetProto = {
1777
- [HashSetTypeId]: HashSetTypeId,
1778
- [Symbol.iterator]() {
1779
- return keys(this._keyMap);
1780
- },
1781
- [symbol]() {
1782
- return cached(this, combine(hash(this._keyMap))(hash(HashSetSymbolKey)));
1783
- },
1784
- [symbol2](that) {
1785
- if (isHashSet(that)) {
1786
- return size(this._keyMap) === size(that._keyMap) && equals(this._keyMap, that._keyMap);
1787
- }
1788
- return false;
1789
- },
1790
- toString() {
1791
- return format(this.toJSON());
1792
- },
1793
- toJSON() {
1794
- return {
1795
- _id: "HashSet",
1796
- values: Array.from(this).map(toJSON)
1797
- };
1798
- },
1799
- [NodeInspectSymbol]() {
1800
- return this.toJSON();
1801
- },
1802
- pipe() {
1803
- return pipeArguments(this, arguments);
1804
- }
1805
- };
1806
- var makeImpl2 = (keyMap) => {
1807
- const set2 = Object.create(HashSetProto);
1808
- set2._keyMap = keyMap;
1809
- return set2;
1810
- };
1811
- var isHashSet = (u) => hasProperty(u, HashSetTypeId);
1812
- var _empty3 = /* @__PURE__ */ makeImpl2(/* @__PURE__ */ empty3());
1813
- var empty4 = () => _empty3;
1814
- var size2 = (self) => size(self._keyMap);
1815
- var beginMutation2 = (self) => makeImpl2(beginMutation(self._keyMap));
1816
- var endMutation = (self) => {
1817
- ;
1818
- self._keyMap._editable = false;
1819
- return self;
1820
- };
1821
- var mutate = /* @__PURE__ */ dual(2, (self, f) => {
1822
- const transient = beginMutation2(self);
1823
- f(transient);
1824
- return endMutation(transient);
1825
- });
1826
- var add3 = /* @__PURE__ */ dual(2, (self, value) => self._keyMap._editable ? (set(value, true)(self._keyMap), self) : makeImpl2(set(value, true)(self._keyMap)));
1827
- var union2 = /* @__PURE__ */ dual(2, (self, that) => mutate(empty4(), (set2) => {
1828
- forEach2(self, (value) => add3(set2, value));
1829
- for (const value of that) {
1830
- add3(set2, value);
1831
- }
1832
- }));
1833
- var forEach2 = /* @__PURE__ */ dual(2, (self, f) => forEach(self._keyMap, (_, k) => f(k)));
1834
-
1835
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/HashSet.js
1836
- var empty5 = empty4;
1837
- var size3 = size2;
1838
- var add4 = add3;
1839
- var union3 = union2;
1840
-
1841
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/data.js
1842
- var ArrayProto = /* @__PURE__ */ Object.assign(/* @__PURE__ */ Object.create(Array.prototype), {
1843
- [symbol]() {
1844
- return cached(this, array(this));
1845
- },
1846
- [symbol2](that) {
1847
- if (Array.isArray(that) && this.length === that.length) {
1848
- return this.every((v, i) => equals(v, that[i]));
1849
- } else {
1850
- return false;
1851
- }
1852
- }
1853
- });
1854
- var Structural = /* @__PURE__ */ function() {
1855
- function Structural2(args2) {
1856
- if (args2) {
1857
- Object.assign(this, args2);
1858
- }
1859
- }
1860
- Structural2.prototype = StructuralPrototype;
1861
- return Structural2;
1862
- }();
1863
-
1864
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/opCodes/cause.js
1865
- var OP_DIE = "Die";
1866
- var OP_EMPTY = "Empty";
1867
- var OP_FAIL = "Fail";
1868
- var OP_INTERRUPT = "Interrupt";
1869
- var OP_PARALLEL = "Parallel";
1870
- var OP_SEQUENTIAL = "Sequential";
1871
-
1872
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/cause.js
1873
- var CauseSymbolKey = "effect/Cause";
1874
- var CauseTypeId = /* @__PURE__ */ Symbol.for(CauseSymbolKey);
1875
- var variance = {
1876
- /* c8 ignore next */
1877
- _E: (_) => _
1878
- };
1879
- var proto = {
1880
- [CauseTypeId]: variance,
1881
- [symbol]() {
1882
- return pipe(hash(CauseSymbolKey), combine(hash(flattenCause(this))), cached(this));
1883
- },
1884
- [symbol2](that) {
1885
- return isCause(that) && causeEquals(this, that);
1886
- },
1887
- pipe() {
1888
- return pipeArguments(this, arguments);
1889
- },
1890
- toJSON() {
1891
- switch (this._tag) {
1892
- case "Empty":
1893
- return {
1894
- _id: "Cause",
1895
- _tag: this._tag
1896
- };
1897
- case "Die":
1898
- return {
1899
- _id: "Cause",
1900
- _tag: this._tag,
1901
- defect: toJSON(this.defect)
1902
- };
1903
- case "Interrupt":
1904
- return {
1905
- _id: "Cause",
1906
- _tag: this._tag,
1907
- fiberId: this.fiberId.toJSON()
1908
- };
1909
- case "Fail":
1910
- return {
1911
- _id: "Cause",
1912
- _tag: this._tag,
1913
- failure: toJSON(this.error)
1914
- };
1915
- case "Sequential":
1916
- case "Parallel":
1917
- return {
1918
- _id: "Cause",
1919
- _tag: this._tag,
1920
- left: toJSON(this.left),
1921
- right: toJSON(this.right)
1922
- };
1923
- }
1924
- },
1925
- toString() {
1926
- return pretty(this);
1927
- },
1928
- [NodeInspectSymbol]() {
1929
- return this.toJSON();
1930
- }
1931
- };
1932
- var fail = (error) => {
1933
- const o = Object.create(proto);
1934
- o._tag = OP_FAIL;
1935
- o.error = error;
1936
- return o;
1937
- };
1938
- var parallel = (left3, right3) => {
1939
- const o = Object.create(proto);
1940
- o._tag = OP_PARALLEL;
1941
- o.left = left3;
1942
- o.right = right3;
1943
- return o;
1944
- };
1945
- var sequential = (left3, right3) => {
1946
- const o = Object.create(proto);
1947
- o._tag = OP_SEQUENTIAL;
1948
- o.left = left3;
1949
- o.right = right3;
1950
- return o;
1951
- };
1952
- var isCause = (u) => hasProperty(u, CauseTypeId);
1953
- var isInterruptedOnly = (self) => reduceWithContext(void 0, IsInterruptedOnlyCauseReducer)(self);
1954
- var causeEquals = (left3, right3) => {
1955
- let leftStack = of(left3);
1956
- let rightStack = of(right3);
1957
- while (isNonEmpty(leftStack) && isNonEmpty(rightStack)) {
1958
- const [leftParallel, leftSequential] = pipe(headNonEmpty(leftStack), reduce4([empty5(), empty()], ([parallel2, sequential2], cause) => {
1959
- const [par, seq] = evaluateCause(cause);
1960
- return some2([pipe(parallel2, union3(par)), pipe(sequential2, appendAll(seq))]);
1961
- }));
1962
- const [rightParallel, rightSequential] = pipe(headNonEmpty(rightStack), reduce4([empty5(), empty()], ([parallel2, sequential2], cause) => {
1963
- const [par, seq] = evaluateCause(cause);
1964
- return some2([pipe(parallel2, union3(par)), pipe(sequential2, appendAll(seq))]);
1965
- }));
1966
- if (!equals(leftParallel, rightParallel)) {
1967
- return false;
1968
- }
1969
- leftStack = leftSequential;
1970
- rightStack = rightSequential;
1971
- }
1972
- return true;
1973
- };
1974
- var flattenCause = (cause) => {
1975
- return flattenCauseLoop(of(cause), empty());
1976
- };
1977
- var flattenCauseLoop = (causes, flattened) => {
1978
- while (1) {
1979
- const [parallel2, sequential2] = pipe(causes, reduce([empty5(), empty()], ([parallel3, sequential3], cause) => {
1980
- const [par, seq] = evaluateCause(cause);
1981
- return [pipe(parallel3, union3(par)), pipe(sequential3, appendAll(seq))];
1982
- }));
1983
- const updated = size3(parallel2) > 0 ? pipe(flattened, prepend(parallel2)) : flattened;
1984
- if (isEmpty(sequential2)) {
1985
- return reverse2(updated);
1986
- }
1987
- causes = sequential2;
1988
- flattened = updated;
1989
- }
1990
- throw new Error(getBugErrorMessage("Cause.flattenCauseLoop"));
1991
- };
1992
- var evaluateCause = (self) => {
1993
- let cause = self;
1994
- const stack = [];
1995
- let _parallel = empty5();
1996
- let _sequential = empty();
1997
- while (cause !== void 0) {
1998
- switch (cause._tag) {
1999
- case OP_EMPTY: {
2000
- if (stack.length === 0) {
2001
- return [_parallel, _sequential];
2002
- }
2003
- cause = stack.pop();
2004
- break;
2005
- }
2006
- case OP_FAIL: {
2007
- _parallel = add4(_parallel, make2(cause._tag, cause.error));
2008
- if (stack.length === 0) {
2009
- return [_parallel, _sequential];
2010
- }
2011
- cause = stack.pop();
2012
- break;
2013
- }
2014
- case OP_DIE: {
2015
- _parallel = add4(_parallel, make2(cause._tag, cause.defect));
2016
- if (stack.length === 0) {
2017
- return [_parallel, _sequential];
2018
- }
2019
- cause = stack.pop();
2020
- break;
2021
- }
2022
- case OP_INTERRUPT: {
2023
- _parallel = add4(_parallel, make2(cause._tag, cause.fiberId));
2024
- if (stack.length === 0) {
2025
- return [_parallel, _sequential];
2026
- }
2027
- cause = stack.pop();
2028
- break;
2029
- }
2030
- case OP_SEQUENTIAL: {
2031
- switch (cause.left._tag) {
2032
- case OP_EMPTY: {
2033
- cause = cause.right;
2034
- break;
2035
- }
2036
- case OP_SEQUENTIAL: {
2037
- cause = sequential(cause.left.left, sequential(cause.left.right, cause.right));
2038
- break;
2039
- }
2040
- case OP_PARALLEL: {
2041
- cause = parallel(sequential(cause.left.left, cause.right), sequential(cause.left.right, cause.right));
2042
- break;
2043
- }
2044
- default: {
2045
- _sequential = prepend(_sequential, cause.right);
2046
- cause = cause.left;
2047
- break;
2048
- }
2049
- }
2050
- break;
2051
- }
2052
- case OP_PARALLEL: {
2053
- stack.push(cause.right);
2054
- cause = cause.left;
2055
- break;
2056
- }
2057
- }
2058
- }
2059
- throw new Error(getBugErrorMessage("Cause.evaluateCauseLoop"));
2060
- };
2061
- var IsInterruptedOnlyCauseReducer = {
2062
- emptyCase: constTrue,
2063
- failCase: constFalse,
2064
- dieCase: constFalse,
2065
- interruptCase: constTrue,
2066
- sequentialCase: (_, left3, right3) => left3 && right3,
2067
- parallelCase: (_, left3, right3) => left3 && right3
2068
- };
2069
- var OP_SEQUENTIAL_CASE = "SequentialCase";
2070
- var OP_PARALLEL_CASE = "ParallelCase";
2071
- var reduce4 = /* @__PURE__ */ dual(3, (self, zero, pf) => {
2072
- let accumulator = zero;
2073
- let cause = self;
2074
- const causes = [];
2075
- while (cause !== void 0) {
2076
- const option = pf(accumulator, cause);
2077
- accumulator = isSome2(option) ? option.value : accumulator;
2078
- switch (cause._tag) {
2079
- case OP_SEQUENTIAL: {
2080
- causes.push(cause.right);
2081
- cause = cause.left;
2082
- break;
2083
- }
2084
- case OP_PARALLEL: {
2085
- causes.push(cause.right);
2086
- cause = cause.left;
2087
- break;
2088
- }
2089
- default: {
2090
- cause = void 0;
2091
- break;
2092
- }
2093
- }
2094
- if (cause === void 0 && causes.length > 0) {
2095
- cause = causes.pop();
2096
- }
2097
- }
2098
- return accumulator;
2099
- });
2100
- var reduceWithContext = /* @__PURE__ */ dual(3, (self, context, reducer) => {
2101
- const input = [self];
2102
- const output = [];
2103
- while (input.length > 0) {
2104
- const cause = input.pop();
2105
- switch (cause._tag) {
2106
- case OP_EMPTY: {
2107
- output.push(right2(reducer.emptyCase(context)));
2108
- break;
2109
- }
2110
- case OP_FAIL: {
2111
- output.push(right2(reducer.failCase(context, cause.error)));
2112
- break;
2113
- }
2114
- case OP_DIE: {
2115
- output.push(right2(reducer.dieCase(context, cause.defect)));
2116
- break;
2117
- }
2118
- case OP_INTERRUPT: {
2119
- output.push(right2(reducer.interruptCase(context, cause.fiberId)));
2120
- break;
2121
- }
2122
- case OP_SEQUENTIAL: {
2123
- input.push(cause.right);
2124
- input.push(cause.left);
2125
- output.push(left2({
2126
- _tag: OP_SEQUENTIAL_CASE
2127
- }));
2128
- break;
2129
- }
2130
- case OP_PARALLEL: {
2131
- input.push(cause.right);
2132
- input.push(cause.left);
2133
- output.push(left2({
2134
- _tag: OP_PARALLEL_CASE
2135
- }));
2136
- break;
2137
- }
2138
- }
2139
- }
2140
- const accumulator = [];
2141
- while (output.length > 0) {
2142
- const either = output.pop();
2143
- switch (either._tag) {
2144
- case "Left": {
2145
- switch (either.left._tag) {
2146
- case OP_SEQUENTIAL_CASE: {
2147
- const left3 = accumulator.pop();
2148
- const right3 = accumulator.pop();
2149
- const value = reducer.sequentialCase(context, left3, right3);
2150
- accumulator.push(value);
2151
- break;
2152
- }
2153
- case OP_PARALLEL_CASE: {
2154
- const left3 = accumulator.pop();
2155
- const right3 = accumulator.pop();
2156
- const value = reducer.parallelCase(context, left3, right3);
2157
- accumulator.push(value);
2158
- break;
2159
- }
2160
- }
2161
- break;
2162
- }
2163
- case "Right": {
2164
- accumulator.push(either.right);
2165
- break;
2166
- }
2167
- }
2168
- }
2169
- if (accumulator.length === 0) {
2170
- throw new Error("BUG: Cause.reduceWithContext - please report an issue at https://github.com/Effect-TS/effect/issues");
2171
- }
2172
- return accumulator.pop();
2173
- });
2174
- var pretty = (cause, options) => {
2175
- if (isInterruptedOnly(cause)) {
2176
- return "All fibers interrupted without errors.";
2177
- }
2178
- return prettyErrors(cause).map(function(e) {
2179
- if (options?.renderErrorCause !== true || e.cause === void 0) {
2180
- return e.stack;
2181
- }
2182
- return `${e.stack} {
2183
- ${renderErrorCause(e.cause, " ")}
2184
- }`;
2185
- }).join("\n");
2186
- };
2187
- var renderErrorCause = (cause, prefix) => {
2188
- const lines = cause.stack.split("\n");
2189
- let stack = `${prefix}[cause]: ${lines[0]}`;
2190
- for (let i = 1, len = lines.length; i < len; i++) {
2191
- stack += `
2192
- ${prefix}${lines[i]}`;
2193
- }
2194
- if (cause.cause) {
2195
- stack += ` {
2196
- ${renderErrorCause(cause.cause, `${prefix} `)}
2197
- ${prefix}}`;
2198
- }
2199
- return stack;
2200
- };
2201
- var PrettyError = class _PrettyError extends globalThis.Error {
2202
- span = void 0;
2203
- constructor(originalError) {
2204
- const originalErrorIsObject = typeof originalError === "object" && originalError !== null;
2205
- const prevLimit = Error.stackTraceLimit;
2206
- Error.stackTraceLimit = 1;
2207
- super(prettyErrorMessage(originalError), originalErrorIsObject && "cause" in originalError && typeof originalError.cause !== "undefined" ? {
2208
- cause: new _PrettyError(originalError.cause)
2209
- } : void 0);
2210
- if (this.message === "") {
2211
- this.message = "An error has occurred";
2212
- }
2213
- Error.stackTraceLimit = prevLimit;
2214
- this.name = originalError instanceof Error ? originalError.name : "Error";
2215
- if (originalErrorIsObject) {
2216
- if (spanSymbol in originalError) {
2217
- this.span = originalError[spanSymbol];
2218
- }
2219
- Object.keys(originalError).forEach((key) => {
2220
- if (!(key in this)) {
2221
- this[key] = originalError[key];
2222
- }
2223
- });
2224
- }
2225
- this.stack = prettyErrorStack(`${this.name}: ${this.message}`, originalError instanceof Error && originalError.stack ? originalError.stack : "", this.span);
2226
- }
2227
- };
2228
- var prettyErrorMessage = (u) => {
2229
- if (typeof u === "string") {
2230
- return u;
2231
- }
2232
- if (typeof u === "object" && u !== null && u instanceof Error) {
2233
- return u.message;
2234
- }
2235
- try {
2236
- if (hasProperty(u, "toString") && isFunction2(u["toString"]) && u["toString"] !== Object.prototype.toString && u["toString"] !== globalThis.Array.prototype.toString) {
2237
- return u["toString"]();
2238
- }
2239
- } catch {
2240
- }
2241
- return stringifyCircular(u);
2242
- };
2243
- var locationRegex = /\((.*)\)/g;
2244
- var spanToTrace = /* @__PURE__ */ globalValue("effect/Tracer/spanToTrace", () => /* @__PURE__ */ new WeakMap());
2245
- var prettyErrorStack = (message, stack, span) => {
2246
- const out = [message];
2247
- const lines = stack.startsWith(message) ? stack.slice(message.length).split("\n") : stack.split("\n");
2248
- for (let i = 1; i < lines.length; i++) {
2249
- if (lines[i].includes("Generator.next")) {
2250
- break;
2251
- }
2252
- if (lines[i].includes("effect_internal_function")) {
2253
- out.pop();
2254
- break;
2255
- }
2256
- out.push(lines[i].replace(/at .*effect_instruction_i.*\((.*)\)/, "at $1").replace(/EffectPrimitive\.\w+/, "<anonymous>"));
2257
- }
2258
- if (span) {
2259
- let current = span;
2260
- let i = 0;
2261
- while (current && current._tag === "Span" && i < 10) {
2262
- const stackFn = spanToTrace.get(current);
2263
- if (typeof stackFn === "function") {
2264
- const stack2 = stackFn();
2265
- if (typeof stack2 === "string") {
2266
- const locationMatchAll = stack2.matchAll(locationRegex);
2267
- let match2 = false;
2268
- for (const [, location] of locationMatchAll) {
2269
- match2 = true;
2270
- out.push(` at ${current.name} (${location})`);
2271
- }
2272
- if (!match2) {
2273
- out.push(` at ${current.name} (${stack2.replace(/^at /, "")})`);
2274
- }
2275
- } else {
2276
- out.push(` at ${current.name}`);
2277
- }
2278
- } else {
2279
- out.push(` at ${current.name}`);
2280
- }
2281
- current = getOrUndefined(current.parent);
2282
- i++;
2283
- }
2284
- }
2285
- return out.join("\n");
2286
- };
2287
- var spanSymbol = /* @__PURE__ */ Symbol.for("effect/SpanAnnotation");
2288
- var prettyErrors = (cause) => reduceWithContext(cause, void 0, {
2289
- emptyCase: () => [],
2290
- dieCase: (_, unknownError) => {
2291
- return [new PrettyError(unknownError)];
2292
- },
2293
- failCase: (_, error) => {
2294
- return [new PrettyError(error)];
2295
- },
2296
- interruptCase: () => [],
2297
- parallelCase: (_, l, r) => [...l, ...r],
2298
- sequentialCase: (_, l, r) => [...l, ...r]
2299
- });
2300
-
2301
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/singleShotGen.js
2302
- var SingleShotGen2 = class _SingleShotGen {
2303
- self;
2304
- called = false;
2305
- constructor(self) {
2306
- this.self = self;
2307
- }
2308
- next(a) {
2309
- return this.called ? {
2310
- value: a,
2311
- done: true
2312
- } : (this.called = true, {
2313
- value: this.self,
2314
- done: false
2315
- });
2316
- }
2317
- return(a) {
2318
- return {
2319
- value: a,
2320
- done: true
2321
- };
2322
- }
2323
- throw(e) {
2324
- throw e;
2325
- }
2326
- [Symbol.iterator]() {
2327
- return new _SingleShotGen(this.self);
2328
- }
2329
- };
2330
-
2331
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/internal/core.js
2332
- var EffectTypeId2 = /* @__PURE__ */ Symbol.for("effect/Effect");
2333
- var EffectPrimitive = class {
2334
- _op;
2335
- effect_instruction_i0 = void 0;
2336
- effect_instruction_i1 = void 0;
2337
- effect_instruction_i2 = void 0;
2338
- trace = void 0;
2339
- [EffectTypeId2] = effectVariance;
2340
- constructor(_op) {
2341
- this._op = _op;
2342
- }
2343
- [symbol2](that) {
2344
- return this === that;
2345
- }
2346
- [symbol]() {
2347
- return cached(this, random(this));
2348
- }
2349
- pipe() {
2350
- return pipeArguments(this, arguments);
2351
- }
2352
- toJSON() {
2353
- return {
2354
- _id: "Effect",
2355
- _op: this._op,
2356
- effect_instruction_i0: toJSON(this.effect_instruction_i0),
2357
- effect_instruction_i1: toJSON(this.effect_instruction_i1),
2358
- effect_instruction_i2: toJSON(this.effect_instruction_i2)
2359
- };
2360
- }
2361
- toString() {
2362
- return format(this.toJSON());
2363
- }
2364
- [NodeInspectSymbol]() {
2365
- return this.toJSON();
2366
- }
2367
- [Symbol.iterator]() {
2368
- return new SingleShotGen2(new YieldWrap(this));
2369
- }
2370
- };
2371
- var EffectPrimitiveFailure = class {
2372
- _op;
2373
- effect_instruction_i0 = void 0;
2374
- effect_instruction_i1 = void 0;
2375
- effect_instruction_i2 = void 0;
2376
- trace = void 0;
2377
- [EffectTypeId2] = effectVariance;
2378
- constructor(_op) {
2379
- this._op = _op;
2380
- this._tag = _op;
2381
- }
2382
- [symbol2](that) {
2383
- return exitIsExit(that) && that._op === "Failure" && // @ts-expect-error
2384
- equals(this.effect_instruction_i0, that.effect_instruction_i0);
2385
- }
2386
- [symbol]() {
2387
- return pipe(
2388
- // @ts-expect-error
2389
- string(this._tag),
2390
- // @ts-expect-error
2391
- combine(hash(this.effect_instruction_i0)),
2392
- cached(this)
2393
- );
2394
- }
2395
- get cause() {
2396
- return this.effect_instruction_i0;
2397
- }
2398
- pipe() {
2399
- return pipeArguments(this, arguments);
2400
- }
2401
- toJSON() {
2402
- return {
2403
- _id: "Exit",
2404
- _tag: this._op,
2405
- cause: this.cause.toJSON()
2406
- };
2407
- }
2408
- toString() {
2409
- return format(this.toJSON());
2410
- }
2411
- [NodeInspectSymbol]() {
2412
- return this.toJSON();
2413
- }
2414
- [Symbol.iterator]() {
2415
- return new SingleShotGen2(new YieldWrap(this));
2416
- }
2417
- };
2418
- var EffectPrimitiveSuccess = class {
2419
- _op;
2420
- effect_instruction_i0 = void 0;
2421
- effect_instruction_i1 = void 0;
2422
- effect_instruction_i2 = void 0;
2423
- trace = void 0;
2424
- [EffectTypeId2] = effectVariance;
2425
- constructor(_op) {
2426
- this._op = _op;
2427
- this._tag = _op;
2428
- }
2429
- [symbol2](that) {
2430
- return exitIsExit(that) && that._op === "Success" && // @ts-expect-error
2431
- equals(this.effect_instruction_i0, that.effect_instruction_i0);
2432
- }
2433
- [symbol]() {
2434
- return pipe(
2435
- // @ts-expect-error
2436
- string(this._tag),
2437
- // @ts-expect-error
2438
- combine(hash(this.effect_instruction_i0)),
2439
- cached(this)
2440
- );
2441
- }
2442
- get value() {
2443
- return this.effect_instruction_i0;
2444
- }
2445
- pipe() {
2446
- return pipeArguments(this, arguments);
2447
- }
2448
- toJSON() {
2449
- return {
2450
- _id: "Exit",
2451
- _tag: this._op,
2452
- value: toJSON(this.value)
2453
- };
2454
- }
2455
- toString() {
2456
- return format(this.toJSON());
2457
- }
2458
- [NodeInspectSymbol]() {
2459
- return this.toJSON();
2460
- }
2461
- [Symbol.iterator]() {
2462
- return new SingleShotGen2(new YieldWrap(this));
2463
- }
2464
- };
2465
- var isEffect = (u) => hasProperty(u, EffectTypeId2);
2466
- var withFiberRuntime = (withRuntime) => {
2467
- const effect = new EffectPrimitive(OP_WITH_RUNTIME);
2468
- effect.effect_instruction_i0 = withRuntime;
2469
- return effect;
2470
- };
2471
- var spanSymbol2 = /* @__PURE__ */ Symbol.for("effect/SpanAnnotation");
2472
- var originalSymbol = /* @__PURE__ */ Symbol.for("effect/OriginalAnnotation");
2473
- var capture = (obj, span) => {
2474
- if (isSome2(span)) {
2475
- return new Proxy(obj, {
2476
- has(target, p) {
2477
- return p === spanSymbol2 || p === originalSymbol || p in target;
2478
- },
2479
- get(target, p) {
2480
- if (p === spanSymbol2) {
2481
- return span.value;
2482
- }
2483
- if (p === originalSymbol) {
2484
- return obj;
2485
- }
2486
- return target[p];
2487
- }
2488
- });
2489
- }
2490
- return obj;
2491
- };
2492
- var fail2 = (error) => isObject(error) && !(spanSymbol2 in error) ? withFiberRuntime((fiber) => failCause(fail(capture(error, currentSpanFromFiber(fiber))))) : failCause(fail(error));
2493
- var failCause = (cause) => {
2494
- const effect = new EffectPrimitiveFailure(OP_FAILURE);
2495
- effect.effect_instruction_i0 = cause;
2496
- return effect;
2497
- };
2498
- var logLevelAll = {
2499
- _tag: "All",
2500
- syslog: 0,
2501
- label: "ALL",
2502
- ordinal: Number.MIN_SAFE_INTEGER,
2503
- pipe() {
2504
- return pipeArguments(this, arguments);
2505
- }
2506
- };
2507
- var logLevelNone = {
2508
- _tag: "None",
2509
- syslog: 7,
2510
- label: "OFF",
2511
- ordinal: Number.MAX_SAFE_INTEGER,
2512
- pipe() {
2513
- return pipeArguments(this, arguments);
2514
- }
2515
- };
2516
- var RequestResolverSymbolKey = "effect/RequestResolver";
2517
- var RequestResolverTypeId = /* @__PURE__ */ Symbol.for(RequestResolverSymbolKey);
2518
- var requestResolverVariance = {
2519
- /* c8 ignore next */
2520
- _A: (_) => _,
2521
- /* c8 ignore next */
2522
- _R: (_) => _
2523
- };
2524
- var RequestResolverImpl = class _RequestResolverImpl {
2525
- runAll;
2526
- target;
2527
- [RequestResolverTypeId] = requestResolverVariance;
2528
- constructor(runAll, target) {
2529
- this.runAll = runAll;
2530
- this.target = target;
2531
- }
2532
- [symbol]() {
2533
- return cached(this, this.target ? hash(this.target) : random(this));
2534
- }
2535
- [symbol2](that) {
2536
- return this.target ? isRequestResolver(that) && equals(this.target, that.target) : this === that;
2537
- }
2538
- identified(...ids) {
2539
- return new _RequestResolverImpl(this.runAll, fromIterable2(ids));
2540
- }
2541
- pipe() {
2542
- return pipeArguments(this, arguments);
2543
- }
2544
- };
2545
- var isRequestResolver = (u) => hasProperty(u, RequestResolverTypeId);
2546
- var YieldableError = /* @__PURE__ */ function() {
2547
- class YieldableError2 extends globalThis.Error {
2548
- commit() {
2549
- return fail2(this);
2550
- }
2551
- toJSON() {
2552
- return {
2553
- ...this
2554
- };
2555
- }
2556
- [NodeInspectSymbol]() {
2557
- if (this.toString !== globalThis.Error.prototype.toString) {
2558
- return this.stack ? `${this.toString()}
2559
- ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
2560
- } else if ("Bun" in globalThis) {
2561
- return pretty(fail(this), {
2562
- renderErrorCause: true
2563
- });
2564
- }
2565
- return this;
2566
- }
2567
- }
2568
- Object.assign(YieldableError2.prototype, StructuralCommitPrototype);
2569
- return YieldableError2;
2570
- }();
2571
- var makeException = (proto2, tag) => {
2572
- class Base2 extends YieldableError {
2573
- _tag = tag;
2574
- }
2575
- Object.assign(Base2.prototype, proto2);
2576
- Base2.prototype.name = tag;
2577
- return Base2;
2578
- };
2579
- var RuntimeExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/RuntimeException");
2580
- var RuntimeException = /* @__PURE__ */ makeException({
2581
- [RuntimeExceptionTypeId]: RuntimeExceptionTypeId
2582
- }, "RuntimeException");
2583
- var InterruptedExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/InterruptedException");
2584
- var InterruptedException = /* @__PURE__ */ makeException({
2585
- [InterruptedExceptionTypeId]: InterruptedExceptionTypeId
2586
- }, "InterruptedException");
2587
- var IllegalArgumentExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/IllegalArgument");
2588
- var IllegalArgumentException = /* @__PURE__ */ makeException({
2589
- [IllegalArgumentExceptionTypeId]: IllegalArgumentExceptionTypeId
2590
- }, "IllegalArgumentException");
2591
- var NoSuchElementExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/NoSuchElement");
2592
- var NoSuchElementException = /* @__PURE__ */ makeException({
2593
- [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId
2594
- }, "NoSuchElementException");
2595
- var InvalidPubSubCapacityExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/InvalidPubSubCapacityException");
2596
- var InvalidPubSubCapacityException = /* @__PURE__ */ makeException({
2597
- [InvalidPubSubCapacityExceptionTypeId]: InvalidPubSubCapacityExceptionTypeId
2598
- }, "InvalidPubSubCapacityException");
2599
- var ExceededCapacityExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/ExceededCapacityException");
2600
- var ExceededCapacityException = /* @__PURE__ */ makeException({
2601
- [ExceededCapacityExceptionTypeId]: ExceededCapacityExceptionTypeId
2602
- }, "ExceededCapacityException");
2603
- var TimeoutExceptionTypeId = /* @__PURE__ */ Symbol.for("effect/Cause/errors/Timeout");
2604
- var TimeoutException = /* @__PURE__ */ makeException({
2605
- [TimeoutExceptionTypeId]: TimeoutExceptionTypeId
2606
- }, "TimeoutException");
2607
- var exitIsExit = (u) => isEffect(u) && "_tag" in u && (u._tag === "Success" || u._tag === "Failure");
2608
- var currentSpanFromFiber = (fiber) => {
2609
- const span = fiber.currentSpan;
2610
- return span !== void 0 && span._tag === "Span" ? some2(span) : none2();
2611
- };
2612
-
2613
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Data.js
2614
- var Class2 = Structural;
2615
- var TaggedClass = (tag) => {
2616
- class Base2 extends Class2 {
2617
- _tag = tag;
2618
- }
2619
- return Base2;
2620
- };
2621
- var Error2 = /* @__PURE__ */ function() {
2622
- const plainArgsSymbol = /* @__PURE__ */ Symbol.for("effect/Data/Error/plainArgs");
2623
- return class Base extends YieldableError {
2624
- constructor(args2) {
2625
- super(args2?.message, args2?.cause ? {
2626
- cause: args2.cause
2627
- } : void 0);
2628
- if (args2) {
2629
- Object.assign(this, args2);
2630
- Object.defineProperty(this, plainArgsSymbol, {
2631
- value: args2,
2632
- enumerable: false
2633
- });
2634
- }
2635
- }
2636
- toJSON() {
2637
- return {
2638
- ...this[plainArgsSymbol],
2639
- ...this
2640
- };
2641
- }
2642
- };
2643
- }();
2644
- var TaggedError = (tag) => {
2645
- class Base2 extends Error2 {
2646
- _tag = tag;
2647
- }
2648
- ;
2649
- Base2.prototype.name = tag;
2650
- return Base2;
2651
- };
2652
-
2653
- // src/internal/bot-response.ts
2654
- var BotResponse = class _BotResponse extends TaggedClass("BotResponse") {
2655
- static make(result) {
2656
- return new _BotResponse({ response: result });
2657
- }
2658
- static ignore = new _BotResponse({});
2659
- };
2660
-
2661
- // src/internal/bot-context.ts
2662
- var extractCommand = (update) => {
2663
- if (typeof update !== "object" || update === null) return void 0;
2664
- const u = update;
2665
- if (!u.entities || !u.text) return void 0;
2666
- const entity = u.entities.find((e) => e.type === "bot_command");
2667
- if (!entity) return void 0;
2668
- return u.text.slice(entity.offset, entity.offset + entity.length);
2669
- };
2670
- var createBotContext = (update) => {
2671
- const command = extractCommand(update);
2672
- return {
2673
- command,
2674
- reply: (text, options) => BotResponse.make({ type: "message", text, ...options }),
2675
- replyWithDocument: (document, options) => BotResponse.make({ type: "document", document, ...options }),
2676
- replyWithPhoto: (photo, options) => BotResponse.make({ type: "photo", photo, ...options }),
2677
- ignore: BotResponse.ignore
2678
- };
2679
- };
2680
-
2681
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Effectable.js
2682
- var EffectPrototype2 = EffectPrototype;
2683
-
2684
- // ../../node_modules/.pnpm/effect@3.12.0/node_modules/effect/dist/esm/Micro.js
2685
- var TypeId5 = /* @__PURE__ */ Symbol.for("effect/Micro");
2686
- var MicroExitTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroExit");
2687
- var isMicro = (u) => typeof u === "object" && u !== null && TypeId5 in u;
2688
- var MicroCauseTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroCause");
2689
- var microCauseVariance = {
2690
- _E: identity
2691
- };
2692
- var MicroCauseImpl = class extends globalThis.Error {
2693
- _tag;
2694
- traces;
2695
- [MicroCauseTypeId];
2696
- constructor(_tag, originalError, traces) {
2697
- const causeName = `MicroCause.${_tag}`;
2698
- let name;
2699
- let message;
2700
- let stack;
2701
- if (originalError instanceof globalThis.Error) {
2702
- name = `(${causeName}) ${originalError.name}`;
2703
- message = originalError.message;
2704
- const messageLines = message.split("\n").length;
2705
- stack = originalError.stack ? `(${causeName}) ${originalError.stack.split("\n").slice(0, messageLines + 3).join("\n")}` : `${name}: ${message}`;
2706
- } else {
2707
- name = causeName;
2708
- message = toStringUnknown(originalError, 0);
2709
- stack = `${name}: ${message}`;
2710
- }
2711
- if (traces.length > 0) {
2712
- stack += `
2713
- ${traces.join("\n ")}`;
2714
- }
2715
- super(message);
2716
- this._tag = _tag;
2717
- this.traces = traces;
2718
- this[MicroCauseTypeId] = microCauseVariance;
2719
- this.name = name;
2720
- this.stack = stack;
2721
- }
2722
- pipe() {
2723
- return pipeArguments(this, arguments);
2724
- }
2725
- toString() {
2726
- return this.stack;
2727
- }
2728
- [NodeInspectSymbol]() {
2729
- return this.stack;
2730
- }
2731
- };
2732
- var Fail = class extends MicroCauseImpl {
2733
- error;
2734
- constructor(error, traces = []) {
2735
- super("Fail", error, traces);
2736
- this.error = error;
2737
- }
2738
- };
2739
- var causeFail = (error, traces = []) => new Fail(error, traces);
2740
- var Die = class extends MicroCauseImpl {
2741
- defect;
2742
- constructor(defect, traces = []) {
2743
- super("Die", defect, traces);
2744
- this.defect = defect;
2745
- }
2746
- };
2747
- var causeDie = (defect, traces = []) => new Die(defect, traces);
2748
- var Interrupt = class extends MicroCauseImpl {
2749
- constructor(traces = []) {
2750
- super("Interrupt", "interrupted", traces);
2751
- }
2752
- };
2753
- var causeInterrupt = (traces = []) => new Interrupt(traces);
2754
- var causeIsFail = (self) => self._tag === "Fail";
2755
- var causeIsInterrupt = (self) => self._tag === "Interrupt";
2756
- var MicroFiberTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroFiber");
2757
- var fiberVariance = {
2758
- _A: identity,
2759
- _E: identity
2760
- };
2761
- var MicroFiberImpl = class {
2762
- context;
2763
- interruptible;
2764
- [MicroFiberTypeId];
2765
- _stack = [];
2766
- _observers = [];
2767
- _exit;
2768
- _children;
2769
- currentOpCount = 0;
2770
- constructor(context, interruptible2 = true) {
2771
- this.context = context;
2772
- this.interruptible = interruptible2;
2773
- this[MicroFiberTypeId] = fiberVariance;
2774
- }
2775
- getRef(ref) {
2776
- return unsafeGetReference(this.context, ref);
2777
- }
2778
- addObserver(cb) {
2779
- if (this._exit) {
2780
- cb(this._exit);
2781
- return constVoid;
2782
- }
2783
- this._observers.push(cb);
2784
- return () => {
2785
- const index = this._observers.indexOf(cb);
2786
- if (index >= 0) {
2787
- this._observers.splice(index, 1);
2788
- }
2789
- };
2790
- }
2791
- _interrupted = false;
2792
- unsafeInterrupt() {
2793
- if (this._exit) {
2794
- return;
2795
- }
2796
- this._interrupted = true;
2797
- if (this.interruptible) {
2798
- this.evaluate(exitInterrupt);
2799
- }
2800
- }
2801
- unsafePoll() {
2802
- return this._exit;
2803
- }
2804
- evaluate(effect) {
2805
- if (this._exit) {
2806
- return;
2807
- } else if (this._yielded !== void 0) {
2808
- const yielded = this._yielded;
2809
- this._yielded = void 0;
2810
- yielded();
2811
- }
2812
- const exit2 = this.runLoop(effect);
2813
- if (exit2 === Yield) {
2814
- return;
2815
- }
2816
- const interruptChildren = fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this);
2817
- if (interruptChildren !== void 0) {
2818
- return this.evaluate(flatMap3(interruptChildren, () => exit2));
2819
- }
2820
- this._exit = exit2;
2821
- for (let i = 0; i < this._observers.length; i++) {
2822
- this._observers[i](exit2);
2823
- }
2824
- this._observers.length = 0;
2825
- }
2826
- runLoop(effect) {
2827
- let yielding = false;
2828
- let current = effect;
2829
- this.currentOpCount = 0;
2830
- try {
2831
- while (true) {
2832
- this.currentOpCount++;
2833
- if (!yielding && this.getRef(CurrentScheduler).shouldYield(this)) {
2834
- yielding = true;
2835
- const prev = current;
2836
- current = flatMap3(yieldNow, () => prev);
2837
- }
2838
- current = current[evaluate](this);
2839
- if (current === Yield) {
2840
- const yielded = this._yielded;
2841
- if (MicroExitTypeId in yielded) {
2842
- this._yielded = void 0;
2843
- return yielded;
2844
- }
2845
- return Yield;
2846
- }
2847
- }
2848
- } catch (error) {
2849
- if (!hasProperty(current, evaluate)) {
2850
- return exitDie(`MicroFiber.runLoop: Not a valid effect: ${String(current)}`);
2851
- }
2852
- return exitDie(error);
2853
- }
2854
- }
2855
- getCont(symbol3) {
2856
- while (true) {
2857
- const op = this._stack.pop();
2858
- if (!op) return void 0;
2859
- const cont = op[ensureCont] && op[ensureCont](this);
2860
- if (cont) return {
2861
- [symbol3]: cont
2862
- };
2863
- if (op[symbol3]) return op;
2864
- }
2865
- }
2866
- // cancel the yielded operation, or for the yielded exit value
2867
- _yielded = void 0;
2868
- yieldWith(value) {
2869
- this._yielded = value;
2870
- return Yield;
2871
- }
2872
- children() {
2873
- return this._children ??= /* @__PURE__ */ new Set();
2874
- }
2875
- };
2876
- var fiberMiddleware = /* @__PURE__ */ globalValue("effect/Micro/fiberMiddleware", () => ({
2877
- interruptChildren: void 0
2878
- }));
2879
- var fiberAwait = (self) => async((resume) => sync(self.addObserver((exit2) => resume(succeed(exit2)))));
2880
- var fiberInterrupt = (self) => suspend(() => {
2881
- self.unsafeInterrupt();
2882
- return asVoid(fiberAwait(self));
2883
- });
2884
- var fiberInterruptAll = (fibers) => suspend(() => {
2885
- for (const fiber of fibers) fiber.unsafeInterrupt();
2886
- const iter = fibers[Symbol.iterator]();
2887
- const wait = suspend(() => {
2888
- let result = iter.next();
2889
- while (!result.done) {
2890
- if (result.value.unsafePoll()) {
2891
- result = iter.next();
2892
- continue;
2893
- }
2894
- const fiber = result.value;
2895
- return async((resume) => {
2896
- fiber.addObserver((_) => {
2897
- resume(wait);
2898
- });
2899
- });
2900
- }
2901
- return exitVoid;
2902
- });
2903
- return wait;
2904
- });
2905
- var identifier = /* @__PURE__ */ Symbol.for("effect/Micro/identifier");
2906
- var args = /* @__PURE__ */ Symbol.for("effect/Micro/args");
2907
- var evaluate = /* @__PURE__ */ Symbol.for("effect/Micro/evaluate");
2908
- var successCont = /* @__PURE__ */ Symbol.for("effect/Micro/successCont");
2909
- var failureCont = /* @__PURE__ */ Symbol.for("effect/Micro/failureCont");
2910
- var ensureCont = /* @__PURE__ */ Symbol.for("effect/Micro/ensureCont");
2911
- var Yield = /* @__PURE__ */ Symbol.for("effect/Micro/Yield");
2912
- var microVariance = {
2913
- _A: identity,
2914
- _E: identity,
2915
- _R: identity
2916
- };
2917
- var MicroProto = {
2918
- ...EffectPrototype2,
2919
- _op: "Micro",
2920
- [TypeId5]: microVariance,
2921
- pipe() {
2922
- return pipeArguments(this, arguments);
2923
- },
2924
- [Symbol.iterator]() {
2925
- return new SingleShotGen(new YieldWrap(this));
2926
- },
2927
- toJSON() {
2928
- return {
2929
- _id: "Micro",
2930
- op: this[identifier],
2931
- ...args in this ? {
2932
- args: this[args]
2933
- } : void 0
2934
- };
2935
- },
2936
- toString() {
2937
- return format(this);
2938
- },
2939
- [NodeInspectSymbol]() {
2940
- return format(this);
2941
- }
2942
- };
2943
- function defaultEvaluate(_fiber) {
2944
- return exitDie(`Micro.evaluate: Not implemented`);
2945
- }
2946
- var makePrimitiveProto = (options) => ({
2947
- ...MicroProto,
2948
- [identifier]: options.op,
2949
- [evaluate]: options.eval ?? defaultEvaluate,
2950
- [successCont]: options.contA,
2951
- [failureCont]: options.contE,
2952
- [ensureCont]: options.ensure
2953
- });
2954
- var makePrimitive = (options) => {
2955
- const Proto = makePrimitiveProto(options);
2956
- return function() {
2957
- const self = Object.create(Proto);
2958
- self[args] = options.single === false ? arguments : arguments[0];
2959
- return self;
2960
- };
2961
- };
2962
- var makeExit = (options) => {
2963
- const Proto = {
2964
- ...makePrimitiveProto(options),
2965
- [MicroExitTypeId]: MicroExitTypeId,
2966
- _tag: options.op,
2967
- get [options.prop]() {
2968
- return this[args];
2969
- },
2970
- toJSON() {
2971
- return {
2972
- _id: "MicroExit",
2973
- _tag: options.op,
2974
- [options.prop]: this[args]
2975
- };
2976
- },
2977
- [symbol2](that) {
2978
- return isMicroExit(that) && that._tag === options.op && equals(this[args], that[args]);
2979
- },
2980
- [symbol]() {
2981
- return cached(this, combine(string(options.op))(hash(this[args])));
2982
- }
2983
- };
2984
- return function(value) {
2985
- const self = Object.create(Proto);
2986
- self[args] = value;
2987
- self[successCont] = void 0;
2988
- self[failureCont] = void 0;
2989
- self[ensureCont] = void 0;
2990
- return self;
2991
- };
2992
- };
2993
- var succeed = /* @__PURE__ */ makeExit({
2994
- op: "Success",
2995
- prop: "value",
2996
- eval(fiber) {
2997
- const cont = fiber.getCont(successCont);
2998
- return cont ? cont[successCont](this[args], fiber) : fiber.yieldWith(this);
2999
- }
3000
- });
3001
- var failCause2 = /* @__PURE__ */ makeExit({
3002
- op: "Failure",
3003
- prop: "cause",
3004
- eval(fiber) {
3005
- let cont = fiber.getCont(failureCont);
3006
- while (causeIsInterrupt(this[args]) && cont && fiber.interruptible) {
3007
- cont = fiber.getCont(failureCont);
3008
- }
3009
- return cont ? cont[failureCont](this[args], fiber) : fiber.yieldWith(this);
3010
- }
3011
- });
3012
- var fail3 = (error) => failCause2(causeFail(error));
3013
- var sync = /* @__PURE__ */ makePrimitive({
3014
- op: "Sync",
3015
- eval(fiber) {
3016
- const value = this[args]();
3017
- const cont = fiber.getCont(successCont);
3018
- return cont ? cont[successCont](value, fiber) : fiber.yieldWith(exitSucceed(value));
3019
- }
3020
- });
3021
- var suspend = /* @__PURE__ */ makePrimitive({
3022
- op: "Suspend",
3023
- eval(_fiber) {
3024
- return this[args]();
3025
- }
3026
- });
3027
- var yieldNowWith = /* @__PURE__ */ makePrimitive({
3028
- op: "Yield",
3029
- eval(fiber) {
3030
- let resumed = false;
3031
- fiber.getRef(CurrentScheduler).scheduleTask(() => {
3032
- if (resumed) return;
3033
- fiber.evaluate(exitVoid);
3034
- }, this[args] ?? 0);
3035
- return fiber.yieldWith(() => {
3036
- resumed = true;
3037
- });
3038
- }
3039
- });
3040
- var yieldNow = /* @__PURE__ */ yieldNowWith(0);
3041
- var void_ = /* @__PURE__ */ succeed(void 0);
3042
- var try_ = (options) => suspend(() => {
3043
- try {
3044
- return succeed(options.try());
3045
- } catch (err) {
3046
- return fail3(options.catch(err));
3047
- }
3048
- });
3049
- var tryPromise = (options) => asyncOptions(function(resume, signal) {
3050
- try {
3051
- options.try(signal).then((a) => resume(succeed(a)), (e) => resume(fail3(options.catch(e))));
3052
- } catch (err) {
3053
- resume(fail3(options.catch(err)));
3054
- }
3055
- }, options.try.length !== 0);
3056
- var withMicroFiber = /* @__PURE__ */ makePrimitive({
3057
- op: "WithMicroFiber",
3058
- eval(fiber) {
3059
- return this[args](fiber);
3060
- }
3061
- });
3062
- var asyncOptions = /* @__PURE__ */ makePrimitive({
3063
- op: "Async",
3064
- single: false,
3065
- eval(fiber) {
3066
- const register = this[args][0];
3067
- let resumed = false;
3068
- let yielded = false;
3069
- const controller = this[args][1] ? new AbortController() : void 0;
3070
- const onCancel = register((effect) => {
3071
- if (resumed) return;
3072
- resumed = true;
3073
- if (yielded) {
3074
- fiber.evaluate(effect);
3075
- } else {
3076
- yielded = effect;
3077
- }
3078
- }, controller?.signal);
3079
- if (yielded !== false) return yielded;
3080
- yielded = true;
3081
- fiber._yielded = () => {
3082
- resumed = true;
3083
- };
3084
- if (controller === void 0 && onCancel === void 0) {
3085
- return Yield;
3086
- }
3087
- fiber._stack.push(asyncFinalizer(() => {
3088
- resumed = true;
3089
- controller?.abort();
3090
- return onCancel ?? exitVoid;
3091
- }));
3092
- return Yield;
3093
- }
3094
- });
3095
- var asyncFinalizer = /* @__PURE__ */ makePrimitive({
3096
- op: "AsyncFinalizer",
3097
- ensure(fiber) {
3098
- if (fiber.interruptible) {
3099
- fiber.interruptible = false;
3100
- fiber._stack.push(setInterruptible(true));
3101
- }
3102
- },
3103
- contE(cause, _fiber) {
3104
- return causeIsInterrupt(cause) ? flatMap3(this[args](), () => failCause2(cause)) : failCause2(cause);
3105
- }
3106
- });
3107
- var async = (register) => asyncOptions(register, register.length >= 2);
3108
- var gen = (...args2) => suspend(() => fromIterator(args2.length === 1 ? args2[0]() : args2[1].call(args2[0])));
3109
- var fromIterator = /* @__PURE__ */ makePrimitive({
3110
- op: "Iterator",
3111
- contA(value, fiber) {
3112
- const state = this[args].next(value);
3113
- if (state.done) return succeed(state.value);
3114
- fiber._stack.push(this);
3115
- return yieldWrapGet(state.value);
3116
- },
3117
- eval(fiber) {
3118
- return this[successCont](void 0, fiber);
3119
- }
3120
- });
3121
- var as = /* @__PURE__ */ dual(2, (self, value) => map6(self, (_) => value));
3122
- var andThen = /* @__PURE__ */ dual(2, (self, f) => flatMap3(self, (a) => {
3123
- const value = isMicro(f) ? f : typeof f === "function" ? f(a) : f;
3124
- return isMicro(value) ? value : succeed(value);
3125
- }));
3126
- var tap = /* @__PURE__ */ dual(2, (self, f) => flatMap3(self, (a) => {
3127
- const value = isMicro(f) ? f : typeof f === "function" ? f(a) : f;
3128
- return isMicro(value) ? as(value, a) : succeed(a);
3129
- }));
3130
- var asVoid = (self) => flatMap3(self, (_) => exitVoid);
3131
- var exit = (self) => matchCause(self, {
3132
- onFailure: exitFailCause,
3133
- onSuccess: exitSucceed
3134
- });
3135
- var flatMap3 = /* @__PURE__ */ dual(2, (self, f) => {
3136
- const onSuccess = Object.create(OnSuccessProto);
3137
- onSuccess[args] = self;
3138
- onSuccess[successCont] = f;
3139
- return onSuccess;
3140
- });
3141
- var OnSuccessProto = /* @__PURE__ */ makePrimitiveProto({
3142
- op: "OnSuccess",
3143
- eval(fiber) {
3144
- fiber._stack.push(this);
3145
- return this[args];
3146
- }
3147
- });
3148
- var map6 = /* @__PURE__ */ dual(2, (self, f) => flatMap3(self, (a) => succeed(f(a))));
3149
- var isMicroExit = (u) => hasProperty(u, MicroExitTypeId);
3150
- var exitSucceed = succeed;
3151
- var exitFailCause = failCause2;
3152
- var exitInterrupt = /* @__PURE__ */ exitFailCause(/* @__PURE__ */ causeInterrupt());
3153
- var exitDie = (defect) => exitFailCause(causeDie(defect));
3154
- var exitVoid = /* @__PURE__ */ exitSucceed(void 0);
3155
- var exitVoidAll = (exits) => {
3156
- for (const exit2 of exits) {
3157
- if (exit2._tag === "Failure") {
3158
- return exit2;
3159
- }
3160
- }
3161
- return exitVoid;
3162
- };
3163
- var setImmediate = "setImmediate" in globalThis ? globalThis.setImmediate : (f) => setTimeout(f, 0);
3164
- var MicroSchedulerDefault = class {
3165
- tasks = [];
3166
- running = false;
3167
- /**
3168
- * @since 3.5.9
3169
- */
3170
- scheduleTask(task, _priority) {
3171
- this.tasks.push(task);
3172
- if (!this.running) {
3173
- this.running = true;
3174
- setImmediate(this.afterScheduled);
3175
- }
3176
- }
3177
- /**
3178
- * @since 3.5.9
3179
- */
3180
- afterScheduled = () => {
3181
- this.running = false;
3182
- this.runTasks();
3183
- };
3184
- /**
3185
- * @since 3.5.9
3186
- */
3187
- runTasks() {
3188
- const tasks = this.tasks;
3189
- this.tasks = [];
3190
- for (let i = 0, len = tasks.length; i < len; i++) {
3191
- tasks[i]();
3192
- }
3193
- }
3194
- /**
3195
- * @since 3.5.9
3196
- */
3197
- shouldYield(fiber) {
3198
- return fiber.currentOpCount >= fiber.getRef(MaxOpsBeforeYield);
3199
- }
3200
- /**
3201
- * @since 3.5.9
3202
- */
3203
- flush() {
3204
- while (this.tasks.length > 0) {
3205
- this.runTasks();
3206
- }
3207
- }
3208
- };
3209
- var service = (tag) => withMicroFiber((fiber) => succeed(unsafeGet3(fiber.context, tag)));
3210
- var updateContext = /* @__PURE__ */ dual(2, (self, f) => withMicroFiber((fiber) => {
3211
- const prev = fiber.context;
3212
- fiber.context = f(prev);
3213
- return onExit(self, () => {
3214
- fiber.context = prev;
3215
- return void_;
3216
- });
3217
- }));
3218
- var provideContext = /* @__PURE__ */ dual(2, (self, provided) => updateContext(self, merge2(provided)));
3219
- var provideService = /* @__PURE__ */ dual(3, (self, tag, service2) => updateContext(self, add2(tag, service2)));
3220
- var MaxOpsBeforeYield = class extends (/* @__PURE__ */ Reference2()("effect/Micro/currentMaxOpsBeforeYield", {
3221
- defaultValue: () => 2048
3222
- })) {
3223
- };
3224
- var CurrentConcurrency = class extends (/* @__PURE__ */ Reference2()("effect/Micro/currentConcurrency", {
3225
- defaultValue: () => "unbounded"
3226
- })) {
3227
- };
3228
- var CurrentScheduler = class extends (/* @__PURE__ */ Reference2()("effect/Micro/currentScheduler", {
3229
- defaultValue: () => new MicroSchedulerDefault()
3230
- })) {
3231
- };
3232
- var repeatExit = /* @__PURE__ */ dual(2, (self, options) => suspend(() => {
3233
- const startedAt = options.schedule ? Date.now() : 0;
3234
- let attempt = 0;
3235
- const loop = flatMap3(exit(self), (exit2) => {
3236
- if (options.while !== void 0 && !options.while(exit2)) {
3237
- return exit2;
3238
- } else if (options.times !== void 0 && attempt >= options.times) {
3239
- return exit2;
3240
- }
3241
- attempt++;
3242
- let delayEffect = yieldNow;
3243
- if (options.schedule !== void 0) {
3244
- const elapsed = Date.now() - startedAt;
3245
- const duration = options.schedule(attempt, elapsed);
3246
- if (isNone2(duration)) {
3247
- return exit2;
3248
- }
3249
- delayEffect = sleep(duration.value);
3250
- }
3251
- return flatMap3(delayEffect, () => loop);
3252
- });
3253
- return loop;
3254
- }));
3255
- var repeat = /* @__PURE__ */ dual((args2) => isMicro(args2[0]), (self, options) => repeatExit(self, {
3256
- ...options,
3257
- while: (exit2) => exit2._tag === "Success" && (options?.while === void 0 || options.while(exit2.value))
3258
- }));
3259
- var catchAllCause = /* @__PURE__ */ dual(2, (self, f) => {
3260
- const onFailure = Object.create(OnFailureProto);
3261
- onFailure[args] = self;
3262
- onFailure[failureCont] = f;
3263
- return onFailure;
3264
- });
3265
- var OnFailureProto = /* @__PURE__ */ makePrimitiveProto({
3266
- op: "OnFailure",
3267
- eval(fiber) {
3268
- fiber._stack.push(this);
3269
- return this[args];
33
+ // src/types.ts
34
+ var BotResponse = class _BotResponse {
35
+ response;
36
+ constructor(response) {
37
+ this.response = response;
3270
38
  }
3271
- });
3272
- var catchCauseIf = /* @__PURE__ */ dual(3, (self, predicate, f) => catchAllCause(self, (cause) => predicate(cause) ? f(cause) : failCause2(cause)));
3273
- var catchAll = /* @__PURE__ */ dual(2, (self, f) => catchCauseIf(self, causeIsFail, (cause) => f(cause.error)));
3274
- var matchCauseEffect = /* @__PURE__ */ dual(2, (self, options) => {
3275
- const primitive = Object.create(OnSuccessAndFailureProto);
3276
- primitive[args] = self;
3277
- primitive[successCont] = options.onSuccess;
3278
- primitive[failureCont] = options.onFailure;
3279
- return primitive;
3280
- });
3281
- var OnSuccessAndFailureProto = /* @__PURE__ */ makePrimitiveProto({
3282
- op: "OnSuccessAndFailure",
3283
- eval(fiber) {
3284
- fiber._stack.push(this);
3285
- return this[args];
3286
- }
3287
- });
3288
- var matchCause = /* @__PURE__ */ dual(2, (self, options) => matchCauseEffect(self, {
3289
- onFailure: (cause) => sync(() => options.onFailure(cause)),
3290
- onSuccess: (value) => sync(() => options.onSuccess(value))
3291
- }));
3292
- var sleep = (millis) => async((resume) => {
3293
- const timeout = setTimeout(() => {
3294
- resume(void_);
3295
- }, millis);
3296
- return sync(() => {
3297
- clearTimeout(timeout);
3298
- });
3299
- });
3300
- var delay = /* @__PURE__ */ dual(2, (self, millis) => andThen(sleep(millis), self));
3301
- var MicroScopeTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroScope");
3302
- var MicroScopeImpl = class _MicroScopeImpl {
3303
- [MicroScopeTypeId];
3304
- state = {
3305
- _tag: "Open",
3306
- finalizers: /* @__PURE__ */ new Set()
3307
- };
3308
- constructor() {
3309
- this[MicroScopeTypeId] = MicroScopeTypeId;
3310
- }
3311
- unsafeAddFinalizer(finalizer) {
3312
- if (this.state._tag === "Open") {
3313
- this.state.finalizers.add(finalizer);
3314
- }
3315
- }
3316
- addFinalizer(finalizer) {
3317
- return suspend(() => {
3318
- if (this.state._tag === "Open") {
3319
- this.state.finalizers.add(finalizer);
3320
- return void_;
3321
- }
3322
- return finalizer(this.state.exit);
3323
- });
3324
- }
3325
- unsafeRemoveFinalizer(finalizer) {
3326
- if (this.state._tag === "Open") {
3327
- this.state.finalizers.delete(finalizer);
3328
- }
3329
- }
3330
- close(microExit) {
3331
- return suspend(() => {
3332
- if (this.state._tag === "Open") {
3333
- const finalizers = Array.from(this.state.finalizers).reverse();
3334
- this.state = {
3335
- _tag: "Closed",
3336
- exit: microExit
3337
- };
3338
- return flatMap3(forEach3(finalizers, (finalizer) => exit(finalizer(microExit))), exitVoidAll);
3339
- }
3340
- return void_;
3341
- });
3342
- }
3343
- get fork() {
3344
- return sync(() => {
3345
- const newScope = new _MicroScopeImpl();
3346
- if (this.state._tag === "Closed") {
3347
- newScope.state = this.state;
3348
- return newScope;
3349
- }
3350
- function fin(exit2) {
3351
- return newScope.close(exit2);
3352
- }
3353
- this.state.finalizers.add(fin);
3354
- newScope.unsafeAddFinalizer((_) => sync(() => this.unsafeRemoveFinalizer(fin)));
3355
- return newScope;
3356
- });
3357
- }
3358
- };
3359
- var onExit = /* @__PURE__ */ dual(2, (self, f) => uninterruptibleMask((restore) => matchCauseEffect(restore(self), {
3360
- onFailure: (cause) => flatMap3(f(exitFailCause(cause)), () => failCause2(cause)),
3361
- onSuccess: (a) => flatMap3(f(exitSucceed(a)), () => succeed(a))
3362
- })));
3363
- var setInterruptible = /* @__PURE__ */ makePrimitive({
3364
- op: "SetInterruptible",
3365
- ensure(fiber) {
3366
- fiber.interruptible = this[args];
3367
- if (fiber._interrupted && fiber.interruptible) {
3368
- return () => exitInterrupt;
3369
- }
3370
- }
3371
- });
3372
- var interruptible = (self) => withMicroFiber((fiber) => {
3373
- if (fiber.interruptible) return self;
3374
- fiber.interruptible = true;
3375
- fiber._stack.push(setInterruptible(false));
3376
- if (fiber._interrupted) return exitInterrupt;
3377
- return self;
3378
- });
3379
- var uninterruptibleMask = (f) => withMicroFiber((fiber) => {
3380
- if (!fiber.interruptible) return f(identity);
3381
- fiber.interruptible = false;
3382
- fiber._stack.push(setInterruptible(true));
3383
- return f(interruptible);
3384
- });
3385
- var whileLoop = /* @__PURE__ */ makePrimitive({
3386
- op: "While",
3387
- contA(value, fiber) {
3388
- this[args].step(value);
3389
- if (this[args].while()) {
3390
- fiber._stack.push(this);
3391
- return this[args].body();
3392
- }
3393
- return exitVoid;
3394
- },
3395
- eval(fiber) {
3396
- if (this[args].while()) {
3397
- fiber._stack.push(this);
3398
- return this[args].body();
3399
- }
3400
- return exitVoid;
3401
- }
3402
- });
3403
- var forEach3 = (iterable, f, options) => withMicroFiber((parent) => {
3404
- const concurrencyOption = options?.concurrency === "inherit" ? parent.getRef(CurrentConcurrency) : options?.concurrency ?? 1;
3405
- const concurrency = concurrencyOption === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrencyOption);
3406
- const items = fromIterable(iterable);
3407
- let length = items.length;
3408
- if (length === 0) {
3409
- return options?.discard ? void_ : succeed([]);
3410
- }
3411
- const out = options?.discard ? void 0 : new Array(length);
3412
- let index = 0;
3413
- if (concurrency === 1) {
3414
- return as(whileLoop({
3415
- while: () => index < items.length,
3416
- body: () => f(items[index], index),
3417
- step: out ? (b) => out[index++] = b : (_) => index++
3418
- }), out);
3419
- }
3420
- return async((resume) => {
3421
- const fibers = /* @__PURE__ */ new Set();
3422
- let result = void 0;
3423
- let inProgress = 0;
3424
- let doneCount = 0;
3425
- let pumping = false;
3426
- let interrupted = false;
3427
- function pump() {
3428
- pumping = true;
3429
- while (inProgress < concurrency && index < length) {
3430
- const currentIndex = index;
3431
- const item = items[currentIndex];
3432
- index++;
3433
- inProgress++;
3434
- try {
3435
- const child = unsafeFork(parent, f(item, currentIndex), true, true);
3436
- fibers.add(child);
3437
- child.addObserver((exit2) => {
3438
- fibers.delete(child);
3439
- if (interrupted) {
3440
- return;
3441
- } else if (exit2._tag === "Failure") {
3442
- if (result === void 0) {
3443
- result = exit2;
3444
- length = index;
3445
- fibers.forEach((fiber) => fiber.unsafeInterrupt());
3446
- }
3447
- } else if (out !== void 0) {
3448
- out[currentIndex] = exit2.value;
3449
- }
3450
- doneCount++;
3451
- inProgress--;
3452
- if (doneCount === length) {
3453
- resume(result ?? succeed(out));
3454
- } else if (!pumping && inProgress < concurrency) {
3455
- pump();
3456
- }
3457
- });
3458
- } catch (err) {
3459
- result = exitDie(err);
3460
- length = index;
3461
- fibers.forEach((fiber) => fiber.unsafeInterrupt());
3462
- }
3463
- }
3464
- pumping = false;
3465
- }
3466
- pump();
3467
- return suspend(() => {
3468
- interrupted = true;
3469
- index = length;
3470
- return fiberInterruptAll(fibers);
3471
- });
3472
- });
3473
- });
3474
- var unsafeFork = (parent, effect, immediate = false, daemon = false) => {
3475
- const child = new MicroFiberImpl(parent.context, parent.interruptible);
3476
- if (!daemon) {
3477
- parent.children().add(child);
3478
- child.addObserver(() => parent.children().delete(child));
3479
- }
3480
- if (immediate) {
3481
- child.evaluate(effect);
3482
- } else {
3483
- parent.getRef(CurrentScheduler).scheduleTask(() => child.evaluate(effect), 0);
3484
- }
3485
- return child;
3486
- };
3487
- var forkDaemon = (self) => withMicroFiber((fiber) => succeed(unsafeFork(fiber, self, false, true)));
3488
- var runFork = (effect, options) => {
3489
- const fiber = new MicroFiberImpl(CurrentScheduler.context(options?.scheduler ?? new MicroSchedulerDefault()));
3490
- fiber.evaluate(effect);
3491
- if (options?.signal) {
3492
- if (options.signal.aborted) {
3493
- fiber.unsafeInterrupt();
3494
- } else {
3495
- const abort = () => fiber.unsafeInterrupt();
3496
- options.signal.addEventListener("abort", abort, {
3497
- once: true
3498
- });
3499
- fiber.addObserver(() => options.signal.removeEventListener("abort", abort));
3500
- }
3501
- }
3502
- return fiber;
3503
- };
3504
- var runPromiseExit = (effect, options) => new Promise((resolve, _reject) => {
3505
- const handle = runFork(effect, options);
3506
- handle.addObserver(resolve);
3507
- });
3508
- var runPromise = (effect, options) => runPromiseExit(effect, options).then((exit2) => {
3509
- if (exit2._tag === "Failure") {
3510
- throw exit2.cause;
39
+ static make(result) {
40
+ return new _BotResponse(result);
3511
41
  }
3512
- return exit2.value;
3513
- });
3514
-
3515
- // src/internal/handle-update.ts
3516
- var import_tg_bot_client = require("@effect-ak/tg-bot-client");
3517
-
3518
- // src/internal/poll-settings.ts
3519
- var BotUpdateHandlersTag = class extends Tag2("BotUpdateHandlers")() {
42
+ static ignore = new _BotResponse();
3520
43
  };
3521
- var BotTgClientTag = class extends Tag2("BotTgClient")() {
3522
- };
3523
- var BotPollSettings = class _BotPollSettings extends Class2 {
3524
- static make(input) {
3525
- let batch_size = input.batch_size ?? 10;
3526
- let poll_timeout = input.poll_timeout ?? 10;
3527
- let max_empty_responses = input.max_empty_responses;
3528
- let log_level = input.log_level ?? "info";
3529
- let on_error = input.on_error;
3530
- if (batch_size < 10 || batch_size > 100) {
3531
- console.warn("Wrong batch_size, must be in [10..100], using 10 instead");
3532
- batch_size = 10;
3533
- }
3534
- if (poll_timeout < 2 || poll_timeout > 120) {
3535
- console.warn("Wrong poll_timeout, must be in [2..120], using 20 instead");
3536
- poll_timeout = 20;
3537
- }
3538
- if (max_empty_responses && max_empty_responses < 2) {
3539
- console.warn(
3540
- "Wrong max_empty_responses, must be in [2..infinity], using infinity"
3541
- );
3542
- max_empty_responses = void 0;
3543
- }
3544
- if (!log_level) {
3545
- log_level = "info";
3546
- }
3547
- if (!on_error) {
3548
- on_error = "stop";
3549
- }
3550
- const config = new _BotPollSettings({
3551
- batch_size,
3552
- poll_timeout,
3553
- max_empty_responses,
3554
- log_level,
3555
- on_error
3556
- });
3557
- console.log("bot poll settings", config);
3558
- return config;
3559
- }
44
+ var extractCommand = (update) => {
45
+ if (typeof update !== "object" || update === null) return void 0;
46
+ const u = update;
47
+ if (!u.entities || !u.text) return void 0;
48
+ const entity = u.entities.find((e) => e.type === "bot_command");
49
+ if (!entity) return void 0;
50
+ return u.text.slice(entity.offset, entity.offset + entity.length);
3560
51
  };
3561
- var BotPollSettingsTag = class extends Reference2()(
3562
- "BotSettings",
3563
- {
3564
- defaultValue() {
3565
- return BotPollSettings.make({});
3566
- }
3567
- }
3568
- ) {
52
+ var createBotContext = (update) => {
53
+ const command = extractCommand(update);
54
+ return {
55
+ command,
56
+ reply: (text, options) => BotResponse.make({ type: "message", text, ...options }),
57
+ replyWithDocument: (document, options) => BotResponse.make({ type: "document", document, ...options }),
58
+ replyWithPhoto: (photo, options) => BotResponse.make({ type: "photo", photo, ...options }),
59
+ ignore: BotResponse.ignore
60
+ };
3569
61
  };
3570
62
 
3571
- // src/internal/handle-update.ts
63
+ // src/bot-processor.ts
3572
64
  var isGuardedHandler = (handler) => typeof handler === "object" && handler !== null && "handle" in handler;
3573
65
  var executeSingleGuard = async (guard, update, ctx) => {
3574
66
  const input = { update, ctx };
@@ -3585,454 +77,296 @@ var executeGuards = async (guards, update, ctx) => {
3585
77
  }
3586
78
  return BotResponse.ignore;
3587
79
  };
3588
- var executeHandler = (handler, update, ctx) => {
80
+ var executeHandler = async (handler, update, ctx) => {
3589
81
  if (typeof handler === "function") {
3590
- return handler(update);
82
+ return await handler(update);
3591
83
  }
3592
84
  if (Array.isArray(handler)) {
3593
- return executeGuards(handler, update, ctx);
85
+ return await executeGuards(handler, update, ctx);
3594
86
  }
3595
87
  if (isGuardedHandler(handler)) {
3596
- return executeSingleGuard(handler, update, ctx).then(
3597
- (r) => r ?? BotResponse.ignore
3598
- );
88
+ const result = await executeSingleGuard(handler, update, ctx);
89
+ return result ?? BotResponse.ignore;
3599
90
  }
3600
91
  return BotResponse.ignore;
3601
92
  };
3602
93
  var extractUpdate = (input) => {
3603
94
  for (const [field, value] of Object.entries(input)) {
3604
- if (field == "update_id") {
3605
- continue;
3606
- }
3607
- return {
3608
- type: field,
3609
- ...value
3610
- };
95
+ if (field === "update_id") continue;
96
+ return { type: field, ...value };
3611
97
  }
3612
- return;
3613
- };
3614
- var BatchUpdateResult = class extends Class2 {
98
+ return void 0;
3615
99
  };
3616
- var handleUpdates = (updates) => gen(function* () {
3617
- const pollSettings = yield* service(BotPollSettingsTag);
3618
- const updateHandler = yield* service(BotUpdateHandlersTag);
3619
- if (updateHandler.type == "single") {
3620
- return yield* handleOneByOne(updates, updateHandler, pollSettings);
3621
- } else {
3622
- return yield* handleEntireBatch(updates, updateHandler);
100
+ var handleUpdates = async (updates, behavior, client, settings, log, onHandleResult) => {
101
+ if (behavior.type === "single") {
102
+ return handleOneByOne(updates, behavior, client, settings, log, onHandleResult);
3623
103
  }
3624
- });
3625
- var handleEntireBatch = (updates, handlers) => try_({
3626
- try: () => handlers.on_batch(updates),
3627
- catch: identity
3628
- }).pipe(
3629
- andThen((result) => {
3630
- if (result instanceof Promise) {
3631
- return tryPromise({
3632
- try: () => result,
3633
- catch: identity
3634
- });
3635
- } else {
3636
- return succeed(result);
3637
- }
3638
- }),
3639
- andThen(
3640
- (doNext) => new BatchUpdateResult({
3641
- hasErrors: !doNext,
3642
- updates
3643
- })
3644
- ),
3645
- catchAll((error) => {
3646
- console.warn("handle batch error", {
104
+ return handleEntireBatch(updates, behavior, log);
105
+ };
106
+ var handleEntireBatch = async (updates, handlers, log) => {
107
+ try {
108
+ const doNext = await handlers.on_batch(updates);
109
+ return { hasErrors: !doNext, updates };
110
+ } catch (error) {
111
+ log.warn("handle batch error", {
3647
112
  errorMessage: error instanceof Error ? error.message : void 0,
3648
113
  updates: updates.map((_) => Object.keys(_).at(1)),
3649
114
  error
3650
115
  });
3651
- return succeed(
3652
- new BatchUpdateResult({
3653
- hasErrors: true,
3654
- updates
3655
- })
3656
- );
3657
- })
3658
- );
3659
- var HandleUpdateError = class extends TaggedError("HandleUpdateError") {
3660
- logInfo() {
3661
- return {
3662
- updateId: this.update.update_id,
3663
- updateKey: Object.keys(this.update).at(1),
3664
- name: this._tag,
3665
- ...this.cause instanceof Error && { error: this.cause.message }
3666
- };
116
+ return { hasErrors: true, updates };
3667
117
  }
3668
118
  };
3669
- var handleOneByOne = (updates, handlers, pollSettings) => forEach3(
3670
- updates,
3671
- (update) => handleOneUpdate(update, handlers).pipe(
3672
- catchAll((error) => {
3673
- if (error instanceof HandleUpdateError) {
3674
- console.warn("update handle error", error.logInfo());
3675
- } else {
3676
- console.warn("unknown error", error);
3677
- }
3678
- return succeed(error);
3679
- })
3680
- ),
3681
- {
3682
- concurrency: 10
119
+ var handleOneByOne = async (updates, handlers, client, settings, log, onHandleResult) => {
120
+ const results = await Promise.allSettled(
121
+ updates.map((update) => handleOneUpdate(update, handlers, client, settings, log, onHandleResult))
122
+ );
123
+ const hasErrors = results.some(
124
+ (r) => r.status === "rejected" || r.status === "fulfilled" && r.value !== void 0
125
+ );
126
+ if (settings.log_level === "debug") {
127
+ log.debug("handle batch result", results);
3683
128
  }
3684
- ).pipe(
3685
- andThen((batchResult) => {
3686
- if (pollSettings.log_level == "debug") {
3687
- console.debug("handle batch result", batchResult);
3688
- }
3689
- return new BatchUpdateResult({
3690
- hasErrors: !batchResult.every((error) => error == null),
3691
- updates
3692
- });
3693
- })
3694
- );
3695
- var handleOneUpdate = (updateObject, handlers) => gen(function* () {
129
+ return { hasErrors, updates };
130
+ };
131
+ var handleOneUpdate = async (updateObject, handlers, client, settings, log, onHandleResult) => {
3696
132
  const update = extractUpdate(updateObject);
3697
133
  if (!update) {
3698
- return yield* fail3(
3699
- new HandleUpdateError({
3700
- name: "UnknownUpdate",
3701
- update: updateObject
3702
- })
3703
- );
134
+ log.warn("update handle error", {
135
+ updateId: updateObject.update_id,
136
+ name: "UnknownUpdate"
137
+ });
138
+ return "UnknownUpdate";
3704
139
  }
3705
140
  const handler = handlers[`on_${update.type}`];
3706
141
  if (!handler) {
3707
- return yield* fail3(
3708
- new HandleUpdateError({
3709
- name: "HandlerNotDefined",
3710
- update: updateObject
3711
- })
3712
- );
3713
- }
3714
- if (update.type == "message" && "text" in update) {
3715
- console.info("Got a new text message", {
3716
- chatId: update.chat.id,
3717
- chatType: update.chat.type,
3718
- message: `${update.text.slice(0, 5)}...`
142
+ onHandleResult?.({
143
+ update: updateObject,
144
+ updateType: update.type,
145
+ status: "no_handler",
146
+ duration: 0
3719
147
  });
148
+ return "HandlerNotDefined";
3720
149
  }
3721
150
  const ctx = createBotContext(update);
3722
- let handleUpdateError;
3723
- const handleResult = yield* try_({
3724
- try: () => executeHandler(handler, update, ctx),
3725
- catch: (error) => new HandleUpdateError({
151
+ const startTime = performance.now();
152
+ let handleResult;
153
+ let hasError = false;
154
+ let errorMessage;
155
+ try {
156
+ handleResult = await executeHandler(handler, update, ctx);
157
+ } catch (error) {
158
+ hasError = true;
159
+ errorMessage = error instanceof Error ? error.message : String(error);
160
+ const errorInfo = {
161
+ updateId: updateObject.update_id,
162
+ updateKey: Object.keys(updateObject).at(1),
3726
163
  name: "BotHandlerError",
164
+ ...error instanceof Error && { error: error.message }
165
+ };
166
+ log.warn("error", errorInfo);
167
+ handleResult = BotResponse.make({
168
+ type: "message",
169
+ text: `Some internal error has happened (BotHandlerError) while handling this message`,
170
+ message_effect_id: "\u{1F4A9}",
171
+ ...updateObject.message?.message_id ? { reply_parameters: { message_id: updateObject.message.message_id } } : void 0
172
+ });
173
+ }
174
+ const duration = Math.round(performance.now() - startTime);
175
+ if (!handleResult) {
176
+ if (settings.log_level === "debug") {
177
+ log.debug(`Bot response is undefined for update #${updateObject.update_id}`);
178
+ }
179
+ onHandleResult?.({
3727
180
  update: updateObject,
3728
- cause: error
3729
- })
3730
- }).pipe(
3731
- andThen((handleResult2) => {
3732
- if (handleResult2 instanceof Promise) {
3733
- return tryPromise({
3734
- try: () => handleResult2,
3735
- catch: (error) => new HandleUpdateError({
3736
- name: "BotHandlerError",
3737
- update: updateObject,
3738
- cause: error
3739
- })
3740
- });
3741
- }
3742
- return succeed(handleResult2);
3743
- }),
3744
- catchAll((error) => {
3745
- handleUpdateError = error;
3746
- console.warn("error", error.logInfo());
3747
- return succeed(
3748
- BotResponse.make({
3749
- type: "message",
3750
- text: `Some internal error has happend(${error.name}) while handling this message`,
3751
- message_effect_id: import_tg_bot_client.MESSAGE_EFFECTS["\u{1F4A9}"],
3752
- ...updateObject.message?.message_id ? {
3753
- reply_parameters: {
3754
- message_id: updateObject.message?.message_id
3755
- }
3756
- } : void 0
3757
- })
3758
- );
3759
- })
3760
- );
3761
- const pollSettings = yield* service(BotPollSettingsTag);
3762
- if (!handleResult && pollSettings.log_level == "debug") {
3763
- console.log(
3764
- `Bot response is undefined for update with ID #${updateObject.update_id}.`
3765
- );
3766
- return;
181
+ updateType: update.type,
182
+ status: "ignored",
183
+ duration
184
+ });
185
+ return void 0;
3767
186
  }
3768
187
  if ("chat" in update && handleResult.response) {
3769
- const client = yield* service(BotTgClientTag);
3770
188
  const responsePayload = handleResult.response;
3771
- const response = yield* tryPromise({
3772
- try: () => client.execute(`send_${responsePayload.type}`, {
3773
- ...responsePayload,
3774
- chat_id: update.chat.id
3775
- }),
3776
- catch: (error) => error
189
+ const result = await client.execute(`send_${responsePayload.type}`, {
190
+ ...responsePayload,
191
+ chat_id: update.chat.id
3777
192
  });
3778
- if (pollSettings.log_level == "debug" && "text") {
3779
- console.debug("bot response", response);
3780
- }
3781
- }
3782
- return handleUpdateError;
3783
- });
3784
-
3785
- // src/service/fetch-updates.ts
3786
- var BotFetchUpdatesService = class extends Reference2()(
3787
- "BotFetchUpdatesService",
3788
- {
3789
- defaultValue: () => {
3790
- const state = {
3791
- lastUpdateId: void 0,
3792
- emptyResponses: 0
3793
- };
3794
- const fetchUpdates = _fetchUpdates(state).pipe(
3795
- tap((updates) => {
3796
- const id = updates.map((_) => _.update_id).sort().at(-1);
3797
- console.log("updating last update id", id);
3798
- state.lastUpdateId = id ? id + 1 : void 0;
3799
- console.log(state);
3800
- })
3801
- );
3802
- const commit = _commitLastBatch(state);
3803
- return {
3804
- state,
3805
- fetchUpdates,
3806
- commit
3807
- };
3808
- }
3809
- }
3810
- ) {
3811
- };
3812
- var FetchUpdatesError = class extends TaggedError("FetchUpdatesError") {
193
+ if (!result.ok) {
194
+ log.warn("failed to send response", result.error);
195
+ } else if (settings.log_level === "debug") {
196
+ log.debug("bot response", result.data);
197
+ }
198
+ }
199
+ onHandleResult?.({
200
+ update: updateObject,
201
+ updateType: update.type,
202
+ status: hasError ? "error" : handleResult.response ? "handled" : "ignored",
203
+ ...handleResult.response ? { responseType: handleResult.response.type } : {},
204
+ ...errorMessage ? { error: errorMessage } : {},
205
+ duration
206
+ });
207
+ return void 0;
3813
208
  };
3814
- var _fetchUpdates = (pollState) => gen(function* () {
3815
- const pollSettings = yield* service(BotPollSettingsTag);
3816
- const client = yield* service(BotTgClientTag);
3817
- if (pollSettings.max_empty_responses && pollState.emptyResponses == pollSettings.max_empty_responses) {
3818
- return yield* fail3(
3819
- new FetchUpdatesError({ name: "TooManyEmptyResponses" })
3820
- );
3821
- }
3822
- const updateId = pollState.lastUpdateId;
3823
- if (pollSettings.log_level == "debug") {
3824
- console.debug("getting updates", pollState);
3825
- }
3826
- const updates = yield* tryPromise({
3827
- try: () => client.execute("get_updates", {
3828
- timeout: pollSettings.poll_timeout,
3829
- ...updateId ? { offset: updateId } : void 0
3830
- }),
3831
- catch: (error) => error
3832
- }).pipe(andThen((_) => _.sort((_2) => _2.update_id)));
3833
- if (updates.length) {
3834
- console.debug(`got a batch of updates (${updates.length})`);
3835
- pollState.emptyResponses = 0;
3836
- return updates;
3837
- } else {
3838
- pollState.emptyResponses += 1;
3839
- return [];
3840
- }
3841
- });
3842
- var _commitLastBatch = (pollState) => gen(function* () {
3843
- console.log("commit", { pollState });
3844
- if (pollState.lastUpdateId) {
3845
- const client = yield* service(BotTgClientTag);
3846
- const offset = pollState.lastUpdateId;
3847
- return yield* tryPromise({
3848
- try: () => client.execute("get_updates", {
3849
- offset,
3850
- limit: 0
3851
- }),
3852
- catch: (error) => error
3853
- }).pipe(
3854
- andThen(
3855
- andThen(service(BotPollSettingsTag), (pollSettings) => {
3856
- if (pollSettings.log_level == "debug") {
3857
- console.debug("committed offset", pollState);
3858
- }
3859
- })
3860
- )
3861
- );
3862
- } else {
3863
- return yield* fail3(
3864
- new FetchUpdatesError({
3865
- name: "NoUpdatesToCommit"
3866
- })
209
+
210
+ // src/run.ts
211
+ var import_tg_bot_client = require("@effect-ak/tg-bot-client");
212
+
213
+ // src/polling.ts
214
+ function makePollSettings(input, log) {
215
+ let batch_size = input.batch_size ?? 10;
216
+ let poll_timeout = input.poll_timeout ?? 10;
217
+ let max_empty_responses = input.max_empty_responses;
218
+ let log_level = input.log_level ?? "info";
219
+ let on_error = input.on_error ?? "stop";
220
+ if (batch_size < 10 || batch_size > 100) {
221
+ log.warn("Wrong batch_size, must be in [10..100], using 10 instead");
222
+ batch_size = 10;
223
+ }
224
+ if (poll_timeout < 2 || poll_timeout > 120) {
225
+ log.warn("Wrong poll_timeout, must be in [2..120], using 20 instead");
226
+ poll_timeout = 20;
227
+ }
228
+ if (max_empty_responses && max_empty_responses < 2) {
229
+ log.warn(
230
+ "Wrong max_empty_responses, must be in [2..infinity], using infinity"
3867
231
  );
232
+ max_empty_responses = void 0;
233
+ }
234
+ const settings = {
235
+ batch_size,
236
+ poll_timeout,
237
+ max_empty_responses,
238
+ log_level,
239
+ on_error
240
+ };
241
+ log.debug("bot poll settings", settings);
242
+ return settings;
243
+ }
244
+ var UpdateFetcher = class {
245
+ constructor(client, settings) {
246
+ this.client = client;
247
+ this.settings = settings;
248
+ }
249
+ lastUpdateId;
250
+ emptyResponses = 0;
251
+ async fetchUpdates() {
252
+ if (this.settings.max_empty_responses && this.emptyResponses >= this.settings.max_empty_responses) {
253
+ throw new Error("TooManyEmptyResponses");
254
+ }
255
+ if (this.settings.log_level === "debug") {
256
+ console.debug("getting updates", {
257
+ lastUpdateId: this.lastUpdateId,
258
+ emptyResponses: this.emptyResponses
259
+ });
260
+ }
261
+ const result = await this.client.execute("get_updates", {
262
+ timeout: this.settings.poll_timeout,
263
+ ...this.lastUpdateId ? { offset: this.lastUpdateId } : void 0
264
+ });
265
+ if (!result.ok) {
266
+ throw new Error(`Failed to fetch updates: ${result.error._tag}`);
267
+ }
268
+ const sorted = result.data.sort((a, b) => a.update_id - b.update_id);
269
+ if (sorted.length > 0) {
270
+ const lastId = sorted[sorted.length - 1].update_id;
271
+ if (this.settings.log_level === "debug") {
272
+ console.debug("updating last update id", lastId);
273
+ }
274
+ this.lastUpdateId = lastId + 1;
275
+ this.emptyResponses = 0;
276
+ } else {
277
+ this.emptyResponses += 1;
278
+ }
279
+ return sorted;
3868
280
  }
3869
- });
3870
-
3871
- // src/service/run.ts
3872
- var BotRunService = class extends Reference2()(
3873
- "BotRunService",
3874
- {
3875
- defaultValue: () => {
3876
- console.log("Initiating BotRunService");
3877
- const state = {
3878
- fiber: void 0
3879
- };
3880
- const runBotInBackground = _runBotDaemon(state);
3881
- const getFiber = () => state.fiber;
3882
- return {
3883
- runBotInBackground,
3884
- getFiber
3885
- };
281
+ async commit() {
282
+ if (!this.lastUpdateId) return;
283
+ if (this.settings.log_level === "debug") {
284
+ console.debug("committing offset", this.lastUpdateId);
285
+ }
286
+ const result = await this.client.execute("get_updates", {
287
+ offset: this.lastUpdateId,
288
+ limit: 0
289
+ });
290
+ if (!result.ok) {
291
+ throw new Error(`Failed to commit offset: ${result.error._tag}`);
292
+ }
293
+ if (this.settings.log_level === "debug") {
294
+ console.debug("committed offset", this.lastUpdateId);
3886
295
  }
3887
296
  }
3888
- ) {
3889
297
  };
3890
- var _runBotDaemon = (state) => gen(function* () {
3891
- console.log("running telegram chat bot");
3892
- const fetchService = yield* service(BotFetchUpdatesService);
3893
- const settings = yield* service(BotPollSettingsTag);
3894
- const continueOnError = (hasError) => {
3895
- if (settings.on_error == "continue") return true;
3896
- return !hasError;
3897
- };
3898
- const startFiber = delay(1e3)(
3899
- fetchService.fetchUpdates.pipe(
3900
- andThen(handleUpdates),
3901
- tap((result) => {
3902
- const hasUpdates = result.updates.length > 0;
3903
- return hasUpdates && continueOnError(result.hasErrors) ? fetchService.commit : void_;
3904
- })
3905
- )
3906
- ).pipe(
3907
- repeat({
3908
- while: (_) => continueOnError(_.hasErrors)
3909
- }),
3910
- forkDaemon,
3911
- tap(
3912
- (fiber) => fiber.addObserver((exit2) => {
3913
- console.log("bot's fiber has been closed", exit2);
3914
- })
3915
- )
3916
- );
3917
- if (state.fiber) {
3918
- console.log("killing previous bot's fiber");
3919
- yield* fiberInterrupt(state.fiber);
3920
- }
3921
- state.fiber = yield* startFiber;
3922
- console.log("Fetching bot updates via long polling...");
3923
- });
3924
298
 
3925
- // src/internal/launch.ts
3926
- var import_tg_bot_client2 = require("@effect-ak/tg-bot-client");
3927
- var extractMode = (input) => {
299
+ // src/run.ts
300
+ var consoleLogger = {
301
+ debug: (msg, data) => console.debug(msg, ...data !== void 0 ? [data] : []),
302
+ info: (msg, data) => console.log(msg, ...data !== void 0 ? [data] : []),
303
+ warn: (msg, data) => console.warn(msg, ...data !== void 0 ? [data] : []),
304
+ error: (msg, data) => console.error(msg, ...data !== void 0 ? [data] : [])
305
+ };
306
+ var delay = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
307
+ var extractBehavior = (input) => {
3928
308
  if (input.mode === "batch") {
3929
309
  return { type: "batch", on_batch: input.on_batch };
3930
310
  }
3931
- const { bot_token, mode, poll, ...handlers } = input;
311
+ const { bot_token, mode, poll, onUpdate: _, onHandleResult: __, logger: ___, ...handlers } = input;
3932
312
  return { type: "single", ...handlers };
3933
313
  };
3934
- var launchBot = (input) => gen(function* () {
3935
- const service2 = yield* service(BotRunService);
3936
- const client = (0, import_tg_bot_client2.makeTgBotClient)({ bot_token: input.bot_token });
3937
- const contextWithClient = make4(BotTgClientTag, client);
3938
- const mode = extractMode(input);
3939
- yield* service2.runBotInBackground.pipe(
3940
- provideService(BotUpdateHandlersTag, mode),
3941
- provideService(
3942
- BotPollSettingsTag,
3943
- BotPollSettings.make(input.poll ?? {})
3944
- ),
3945
- provideContext(contextWithClient)
3946
- );
3947
- const reload = (mode2) => service2.runBotInBackground.pipe(
3948
- provideService(BotUpdateHandlersTag, mode2),
3949
- provideContext(contextWithClient),
3950
- runPromise
3951
- );
314
+ var runBot = async (input) => {
315
+ const log = input.logger ?? consoleLogger;
316
+ const settings = makePollSettings(input.poll ?? {}, log);
317
+ const client = (0, import_tg_bot_client.makeTgBotClient)({ bot_token: input.bot_token });
318
+ const fetcher = new UpdateFetcher(client, settings);
319
+ let behavior = extractBehavior(input);
320
+ const abortController = new AbortController();
321
+ const poll = async () => {
322
+ if (settings.log_level === "debug") {
323
+ log.debug("running telegram chat bot");
324
+ log.debug("Fetching bot updates via long polling...");
325
+ }
326
+ while (!abortController.signal.aborted) {
327
+ try {
328
+ const updates = await fetcher.fetchUpdates();
329
+ if (input.onUpdate) {
330
+ for (const u of updates) input.onUpdate(u);
331
+ }
332
+ const result = await handleUpdates(updates, behavior, client, settings, log, input.onHandleResult);
333
+ if (updates.length > 0 && !result.hasErrors) {
334
+ await fetcher.commit();
335
+ }
336
+ if (result.hasErrors && settings.on_error === "stop") {
337
+ log.warn("stopping bot due to error (on_error=stop)");
338
+ break;
339
+ }
340
+ } catch (error) {
341
+ log.error("polling error", error instanceof Error ? error.message : error);
342
+ if (settings.on_error === "stop") break;
343
+ }
344
+ await delay(1e3);
345
+ }
346
+ if (settings.log_level === "debug") {
347
+ log.debug("bot polling stopped");
348
+ }
349
+ };
350
+ poll();
3952
351
  return {
3953
- reload,
3954
- fiber: service2.getFiber
352
+ stop: () => abortController.abort(),
353
+ reload: (newBehavior) => {
354
+ behavior = newBehavior;
355
+ }
3955
356
  };
3956
- });
3957
-
3958
- // src/run.ts
3959
- var runTgChatBot = (input) => launchBot(input).pipe(runPromise);
357
+ };
3960
358
  var defineBot = (input) => {
3961
- if (Object.keys(input).length == 0)
359
+ if (Object.keys(input).length === 0)
3962
360
  console.warn("No handlers are defined for bot");
3963
361
  return input;
3964
362
  };
3965
-
3966
- // src/webhook.ts
3967
- var import_tg_bot_client3 = require("@effect-ak/tg-bot-client");
3968
- var isGuardedHandler2 = (handler) => typeof handler === "object" && handler !== null && "handle" in handler;
3969
- var executeSingleGuard2 = async (guard, update, ctx) => {
3970
- const input = { update, ctx };
3971
- if (guard.match) {
3972
- const matched = await guard.match(input);
3973
- if (!matched) return null;
3974
- }
3975
- return await guard.handle(input);
3976
- };
3977
- var executeGuards2 = async (guards, update, ctx) => {
3978
- for (const guard of guards) {
3979
- const result = await executeSingleGuard2(guard, update, ctx);
3980
- if (result !== null) return result;
3981
- }
3982
- return BotResponse.ignore;
3983
- };
3984
- var executeHandler2 = async (handler, update, ctx) => {
3985
- if (typeof handler === "function") {
3986
- return await handler(update);
3987
- }
3988
- if (Array.isArray(handler)) {
3989
- return await executeGuards2(handler, update, ctx);
3990
- }
3991
- if (isGuardedHandler2(handler)) {
3992
- const result = await executeSingleGuard2(handler, update, ctx);
3993
- return result ?? BotResponse.ignore;
3994
- }
3995
- return BotResponse.ignore;
3996
- };
3997
- var extractUpdate2 = (input) => {
3998
- for (const [field, value] of Object.entries(input)) {
3999
- if (field === "update_id") continue;
4000
- return { type: field, ...value };
4001
- }
4002
- return void 0;
4003
- };
4004
- var processUpdate = async (updateObject, handlers, client) => {
4005
- const update = extractUpdate2(updateObject);
4006
- if (!update) {
4007
- console.warn("Unknown update format", updateObject);
4008
- return;
4009
- }
4010
- const handlerKey = `on_${update.type}`;
4011
- const handler = handlers[handlerKey];
4012
- if (!handler) {
4013
- return;
4014
- }
4015
- const ctx = createBotContext(update);
4016
- try {
4017
- const result = await executeHandler2(handler, update, ctx);
4018
- if (result.response && "chat" in update) {
4019
- const responsePayload = result.response;
4020
- await client.execute(`send_${responsePayload.type}`, {
4021
- ...responsePayload,
4022
- chat_id: update.chat.id
4023
- });
4024
- }
4025
- } catch (error) {
4026
- console.error("Error handling update", {
4027
- updateId: updateObject.update_id,
4028
- error: error instanceof Error ? error.message : error
4029
- });
4030
- }
4031
- };
4032
- var createWebhookHandler = (config) => {
4033
- const client = (0, import_tg_bot_client3.makeTgBotClient)({ bot_token: config.bot_token });
363
+ var createWebhook = (config) => {
364
+ const { bot_token, onHandleResult, logger, ...handlers } = config;
365
+ const log = logger ?? consoleLogger;
366
+ const client = (0, import_tg_bot_client.makeTgBotClient)({ bot_token });
367
+ const settings = makePollSettings({}, log);
4034
368
  const handleUpdate = async (update) => {
4035
- await processUpdate(update, config, client);
369
+ await handleUpdates([update], { type: "single", ...handlers }, client, settings, log, onHandleResult);
4036
370
  };
4037
371
  const handler = async (request) => {
4038
372
  try {
@@ -4040,31 +374,147 @@ var createWebhookHandler = (config) => {
4040
374
  await handleUpdate(update);
4041
375
  return new Response("ok", { status: 200 });
4042
376
  } catch (error) {
4043
- console.error("Webhook error", error);
377
+ log.error("Webhook error", error);
4044
378
  return new Response("error", { status: 500 });
4045
379
  }
4046
380
  };
4047
381
  handler.handleUpdate = handleUpdate;
4048
382
  return handler;
4049
383
  };
384
+
385
+ // src/bot-builder.ts
386
+ function makeMessageHelpers() {
387
+ return {
388
+ command: (cmd, handler) => ({
389
+ match: ({ ctx }) => ctx.command === cmd,
390
+ handle: handler
391
+ }),
392
+ text: (handler) => ({
393
+ match: ({ update }) => !!update.text,
394
+ handle: handler
395
+ }),
396
+ photo: (handler) => ({
397
+ match: ({ update }) => !!update.photo,
398
+ handle: handler
399
+ }),
400
+ document: (handler) => ({
401
+ match: ({ update }) => !!update.document,
402
+ handle: handler
403
+ }),
404
+ sticker: (handler) => ({
405
+ match: ({ update }) => !!update.sticker,
406
+ handle: handler
407
+ }),
408
+ fallback: (handler) => ({ handle: handler })
409
+ };
410
+ }
411
+ function makeCallbackQueryHelpers() {
412
+ return {
413
+ data: (pattern, handler) => ({
414
+ match: ({ update }) => typeof pattern === "string" ? update.data === pattern : pattern.test(update.data ?? ""),
415
+ handle: handler
416
+ }),
417
+ fallback: (handler) => ({ handle: handler })
418
+ };
419
+ }
420
+ function makeInlineQueryHelpers() {
421
+ return {
422
+ query: (pattern, handler) => ({
423
+ match: ({ update }) => typeof pattern === "string" ? update.query === pattern : pattern.test(update.query),
424
+ handle: handler
425
+ }),
426
+ fallback: (handler) => ({ handle: handler })
427
+ };
428
+ }
429
+ function makeGenericHelpers() {
430
+ return {
431
+ fallback: (handler) => ({ handle: handler })
432
+ };
433
+ }
434
+ function resolve(makeHelpers, input) {
435
+ if (typeof input === "function") {
436
+ return input(makeHelpers());
437
+ }
438
+ return input;
439
+ }
440
+ function createBot() {
441
+ const handlers = /* @__PURE__ */ new Map();
442
+ function register(type, guards) {
443
+ const existing = handlers.get(type) ?? [];
444
+ handlers.set(type, [...existing, ...guards]);
445
+ }
446
+ function collectHandlers() {
447
+ const result = {};
448
+ for (const [type, guards] of handlers) {
449
+ result[`on_${type}`] = guards;
450
+ }
451
+ return result;
452
+ }
453
+ const bot = {
454
+ onMessage(input) {
455
+ register("message", resolve(makeMessageHelpers, input));
456
+ return bot;
457
+ },
458
+ onEditedMessage(input) {
459
+ register("edited_message", resolve(makeGenericHelpers, input));
460
+ return bot;
461
+ },
462
+ onChannelPost(input) {
463
+ register("channel_post", resolve(makeGenericHelpers, input));
464
+ return bot;
465
+ },
466
+ onEditedChannelPost(input) {
467
+ register("edited_channel_post", resolve(makeGenericHelpers, input));
468
+ return bot;
469
+ },
470
+ onBusinessMessage(input) {
471
+ register("business_message", resolve(makeGenericHelpers, input));
472
+ return bot;
473
+ },
474
+ onEditedBusinessMessage(input) {
475
+ register("edited_business_message", resolve(makeGenericHelpers, input));
476
+ return bot;
477
+ },
478
+ onCallbackQuery(input) {
479
+ register("callback_query", resolve(makeCallbackQueryHelpers, input));
480
+ return bot;
481
+ },
482
+ onInlineQuery(input) {
483
+ register("inline_query", resolve(makeInlineQueryHelpers, input));
484
+ return bot;
485
+ },
486
+ on(type, input) {
487
+ register(type, resolve(makeGenericHelpers, input));
488
+ return bot;
489
+ },
490
+ async run(config) {
491
+ const collected = collectHandlers();
492
+ if (handlers.size === 0) {
493
+ console.warn("No handlers are defined for bot");
494
+ }
495
+ return runBot({
496
+ ...config,
497
+ mode: "single",
498
+ ...collected
499
+ });
500
+ },
501
+ webhook(config) {
502
+ const collected = collectHandlers();
503
+ return createWebhook({
504
+ ...config,
505
+ ...collected
506
+ });
507
+ }
508
+ };
509
+ return bot;
510
+ }
4050
511
  // Annotate the CommonJS export names for ESM import in node:
4051
512
  0 && (module.exports = {
4052
- BatchUpdateResult,
4053
- BotPollSettings,
4054
- BotPollSettingsTag,
4055
513
  BotResponse,
4056
- BotRunService,
4057
- BotTgClientTag,
4058
- BotUpdateHandlersTag,
4059
- HandleUpdateError,
514
+ createBot,
4060
515
  createBotContext,
4061
- createWebhookHandler,
516
+ createWebhook,
4062
517
  defineBot,
4063
518
  extractUpdate,
4064
- handleEntireBatch,
4065
- handleOneByOne,
4066
- handleOneUpdate,
4067
- handleUpdates,
4068
- launchBot,
4069
- runTgChatBot
519
+ runBot
4070
520
  });