@tickean/checkout-js 0.1.0 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -21,10 +21,32 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  TickeanError: () => TickeanError,
24
- createTickean: () => createTickean
24
+ checkoutReducer: () => checkoutReducer,
25
+ createCheckoutController: () => createCheckoutController,
26
+ createEventEmitterTelemetry: () => createEventEmitterTelemetry,
27
+ createInitialState: () => createInitialState,
28
+ createMemoryPersistence: () => createMemoryPersistence,
29
+ createNoopTelemetry: () => createNoopTelemetry,
30
+ createSessionStoragePersistence: () => createSessionStoragePersistence,
31
+ createTickean: () => createTickean,
32
+ navigateTopLevel: () => navigateTopLevel,
33
+ resolveRedirectUrl: () => resolveRedirectUrl,
34
+ watchPaymentSocket: () => watchPaymentSocket
25
35
  });
26
36
  module.exports = __toCommonJS(index_exports);
27
37
 
38
+ // src/types.ts
39
+ var TickeanError = class extends Error {
40
+ constructor(payload, status, requestId) {
41
+ super(payload.message);
42
+ this.name = "TickeanError";
43
+ this.code = payload.code;
44
+ this.details = payload.details;
45
+ this.status = status;
46
+ this.requestId = requestId;
47
+ }
48
+ };
49
+
28
50
  // src/demo.ts
29
51
  var demoEvent = {
30
52
  id: "evt_demo",
@@ -98,10 +120,26 @@ function createDemoTransport() {
98
120
  let unlocked = [];
99
121
  let purchaseId = "purchase_demo";
100
122
  let cartRef = "cart_demo";
123
+ let lastPayment = null;
124
+ let paymentConfirmed = false;
125
+ const publicEvent = () => ({
126
+ ...demoEvent,
127
+ shows: demoEvent.shows.map((show) => ({
128
+ ...show,
129
+ showOptions: [
130
+ ...show.showOptions.filter((o) => o.catalogVisibility !== "PROMO_GATED"),
131
+ ...unlocked.filter((u) => show.showOptions.some((o) => o.id === u.id))
132
+ ]
133
+ }))
134
+ });
101
135
  return {
102
136
  async request(path, init) {
103
137
  if (path === "/v1/checkout/sessions" && init.method === "POST") {
104
138
  sessionToken = `demo_${Date.now()}`;
139
+ buyer = null;
140
+ unlocked = [];
141
+ paymentConfirmed = false;
142
+ lastPayment = null;
105
143
  return {
106
144
  sessionId: "sess_demo",
107
145
  sessionToken,
@@ -120,25 +158,68 @@ function createDemoTransport() {
120
158
  discounts: true,
121
159
  transfer: true,
122
160
  onlinePayments: true
123
- }
161
+ },
162
+ phase: "browsing"
124
163
  };
125
164
  }
126
- if (path === "/v1/checkout/catalog") {
165
+ if (path === "/v1/checkout/recovery/exchange" && init.method === "POST") {
166
+ sessionToken = `demo_resume_${Date.now()}`;
167
+ buyer = {
168
+ id: "buyer_demo_resume",
169
+ name: "Demo Resume",
170
+ email: "resume@demo.tickean",
171
+ phone: "+5491100000000"
172
+ };
173
+ purchaseId = "";
174
+ lastPayment = null;
175
+ paymentConfirmed = false;
127
176
  return {
128
- ...demoEvent,
129
- shows: demoEvent.shows.map((show) => ({
130
- ...show,
131
- showOptions: [
132
- ...show.showOptions.filter(
133
- (o) => o.catalogVisibility !== "PROMO_GATED"
134
- ),
135
- ...unlocked.filter(
136
- (u) => show.showOptions.some((o) => o.id === u.id)
137
- )
138
- ]
139
- }))
177
+ sessionId: "sess_demo_resume",
178
+ sessionToken,
179
+ expiresAt: new Date(Date.now() + 36e5).toISOString(),
180
+ suggestedStep: "BUYER",
181
+ event: publicEvent(),
182
+ capabilities: {
183
+ tickets: true,
184
+ discounts: true,
185
+ transfer: true,
186
+ onlinePayments: true
187
+ },
188
+ cart: [{ showOptionId: "opt_day", amount: 1 }],
189
+ discountCode: null,
190
+ buyer,
191
+ buyerVerified: true,
192
+ purchase: null,
193
+ payment: null,
194
+ nextAction: { type: "none" },
195
+ shoppingCartReference: cartRef,
196
+ phase: "ready_to_purchase"
197
+ };
198
+ }
199
+ if (path === "/v1/checkout/session") {
200
+ return {
201
+ sessionId: "sess_demo",
202
+ sessionToken,
203
+ expiresAt: new Date(Date.now() + 36e5).toISOString(),
204
+ event: publicEvent(),
205
+ capabilities: {
206
+ tickets: true,
207
+ discounts: true,
208
+ transfer: true,
209
+ onlinePayments: true
210
+ },
211
+ status: "ACTIVE",
212
+ otpVerified: Boolean(buyer),
213
+ buyerId: buyer?.id || null,
214
+ purchaseId: purchaseId.startsWith("purchase_") ? purchaseId : null,
215
+ shoppingCartReference: cartRef,
216
+ nextAction: lastPayment?.nextAction || { type: "none" },
217
+ phase: paymentConfirmed ? "completed" : lastPayment ? "requires_action" : buyer ? "ready_to_purchase" : "browsing"
140
218
  };
141
219
  }
220
+ if (path === "/v1/checkout/catalog") {
221
+ return publicEvent();
222
+ }
142
223
  if (path === "/v1/checkout/quote" && init.method === "POST") {
143
224
  const body = init.body;
144
225
  if (body.discountCode?.toUpperCase() === "DEMO2X1") {
@@ -157,6 +238,20 @@ function createDemoTransport() {
157
238
  unlockedShowOptions: unlocked
158
239
  };
159
240
  }
241
+ if (path === "/v1/checkout/buyer/lookup" && init.method === "POST") {
242
+ const body = init.body;
243
+ const isNew = String(body.phone || "").replace(/\D/g, "").endsWith("0000");
244
+ if (isNew) return { exists: false };
245
+ return {
246
+ exists: true,
247
+ buyer: {
248
+ id: "buyer_demo",
249
+ phone: body.phone,
250
+ name: "Demo Buyer",
251
+ email: "demo@tickean.com"
252
+ }
253
+ };
254
+ }
160
255
  if (path === "/v1/checkout/otp/send") {
161
256
  return { sent: true };
162
257
  }
@@ -168,12 +263,13 @@ function createDemoTransport() {
168
263
  name: body.name || "Demo Buyer",
169
264
  email: body.email
170
265
  };
171
- return { verified: true, buyer };
266
+ return { verified: true, isNewBuyer: !body.name, buyer };
172
267
  }
173
268
  if (path === "/v1/checkout/purchases") {
174
269
  if (!buyer) {
175
- throw Object.assign(new Error("OTP required"), {
176
- code: "checkout_otp_required"
270
+ throw new TickeanError({
271
+ code: "checkout_otp_required",
272
+ message: "OTP required"
177
273
  });
178
274
  }
179
275
  const body = init.body;
@@ -198,47 +294,81 @@ function createDemoTransport() {
198
294
  };
199
295
  }
200
296
  if (path === "/v1/checkout/payments") {
201
- return {
202
- id: `pay_${Date.now()}`,
203
- paymentStatus: "PENDING",
204
- paymentMethod: init.body?.paymentMethod,
205
- paymentInstructions: {
206
- alias: "tickean.demo",
207
- cvu: "0000003100010000000001",
208
- amount: init.body?.amount
209
- },
210
- redirectUrl: void 0,
211
- returnUrl: null
297
+ const body = init.body;
298
+ const method = String(body?.paymentMethod || "TRANSFER").toUpperCase();
299
+ if (method === "TRANSFER") {
300
+ lastPayment = {
301
+ id: `pay_${Date.now()}`,
302
+ paymentStatus: "PENDING",
303
+ paymentMethod: method,
304
+ paymentInstructions: {
305
+ alias: "tickean.demo",
306
+ cvu: "0000003100010000000001",
307
+ amount: body?.amount
308
+ },
309
+ redirectUrl: void 0,
310
+ returnUrl: null,
311
+ nextAction: {
312
+ type: "display_instructions",
313
+ paymentInstructions: {
314
+ alias: "tickean.demo",
315
+ cvu: "0000003100010000000001",
316
+ amount: body?.amount
317
+ }
318
+ },
319
+ requiresAction: false
320
+ };
321
+ } else {
322
+ lastPayment = {
323
+ id: `pay_${Date.now()}`,
324
+ paymentStatus: "PENDING",
325
+ paymentMethod: method,
326
+ redirectUrl: "https://example.com/pay/demo",
327
+ returnUrl: null,
328
+ nextAction: {
329
+ type: "redirect",
330
+ url: "https://example.com/pay/demo"
331
+ },
332
+ requiresAction: true
333
+ };
334
+ }
335
+ return lastPayment;
336
+ }
337
+ if (path === "/v1/checkout/payments/confirm" && init.method === "POST") {
338
+ paymentConfirmed = true;
339
+ lastPayment = {
340
+ ...lastPayment || { id: `pay_${Date.now()}` },
341
+ paymentStatus: "COMPLETED",
342
+ nextAction: { type: "none" },
343
+ requiresAction: false
212
344
  };
345
+ return lastPayment;
213
346
  }
214
347
  if (path === "/v1/checkout/payments/status") {
215
348
  return {
216
- status: "PENDING",
349
+ status: paymentConfirmed ? "COMPLETED" : "PENDING",
350
+ requiresAction: Boolean(
351
+ lastPayment?.nextAction && lastPayment.nextAction.type !== "none" && !paymentConfirmed
352
+ ),
353
+ phase: paymentConfirmed ? "completed" : lastPayment ? "requires_action" : "browsing",
354
+ nextAction: lastPayment?.nextAction || { type: "none" },
355
+ payment: lastPayment,
217
356
  purchase: {
218
357
  id: purchaseId,
219
- status: "PENDING",
358
+ status: paymentConfirmed ? "COMPLETED" : "PENDING",
220
359
  totalPrice: 0,
221
360
  currency: "ARS",
222
361
  shoppingCartReference: cartRef
223
362
  }
224
363
  };
225
364
  }
226
- throw new Error(`Demo transport: unhandled ${init.method || "GET"} ${path}`);
365
+ throw new Error(
366
+ `Demo transport: unhandled ${init.method || "GET"} ${path}`
367
+ );
227
368
  }
228
369
  };
229
370
  }
230
371
 
231
- // src/types.ts
232
- var TickeanError = class extends Error {
233
- constructor(payload, status) {
234
- super(payload.message);
235
- this.name = "TickeanError";
236
- this.code = payload.code;
237
- this.details = payload.details;
238
- this.status = status;
239
- }
240
- };
241
-
242
372
  // src/http.ts
243
373
  function createHttpTransport(options) {
244
374
  const fetchImpl = options.fetchImpl || fetch;
@@ -251,6 +381,9 @@ function createHttpTransport(options) {
251
381
  if (init.sessionToken) {
252
382
  headers["X-Tickean-Checkout-Session"] = init.sessionToken;
253
383
  }
384
+ if (init.idempotencyKey) {
385
+ headers["Idempotency-Key"] = init.idempotencyKey;
386
+ }
254
387
  const response = await fetchImpl(
255
388
  `${options.apiBaseUrl.replace(/\/$/, "")}${path}`,
256
389
  {
@@ -260,6 +393,7 @@ function createHttpTransport(options) {
260
393
  credentials: "omit"
261
394
  }
262
395
  );
396
+ const requestId = response.headers.get("X-Request-Id") || response.headers.get("x-request-id") || void 0;
263
397
  const json = await response.json().catch(() => ({}));
264
398
  if (!response.ok) {
265
399
  const err = json?.error || {};
@@ -269,7 +403,8 @@ function createHttpTransport(options) {
269
403
  message: err.message || response.statusText || "Request failed",
270
404
  details: err.details
271
405
  },
272
- response.status
406
+ response.status,
407
+ requestId
273
408
  );
274
409
  }
275
410
  return json;
@@ -277,7 +412,7 @@ function createHttpTransport(options) {
277
412
  };
278
413
  }
279
414
 
280
- // src/index.ts
415
+ // src/client.ts
281
416
  function createTickean(options) {
282
417
  if (!options.publishableKey && !options.demo) {
283
418
  throw new TickeanError({
@@ -304,6 +439,9 @@ function createTickean(options) {
304
439
  get session() {
305
440
  return session;
306
441
  },
442
+ set session(value2) {
443
+ session = value2;
444
+ },
307
445
  async createSession(params) {
308
446
  session = await transport.request("/v1/checkout/sessions", {
309
447
  method: "POST",
@@ -311,6 +449,40 @@ function createTickean(options) {
311
449
  });
312
450
  return session;
313
451
  },
452
+ async exchangeRecovery(params) {
453
+ const result = await transport.request("/v1/checkout/recovery/exchange", {
454
+ method: "POST",
455
+ body: params
456
+ });
457
+ session = {
458
+ sessionId: result.sessionId,
459
+ sessionToken: result.sessionToken,
460
+ expiresAt: result.expiresAt,
461
+ event: result.event,
462
+ capabilities: result.capabilities || {},
463
+ shoppingCartReference: result.shoppingCartReference,
464
+ nextAction: result.nextAction,
465
+ phase: result.phase
466
+ };
467
+ return result;
468
+ },
469
+ async getSession() {
470
+ const active = requireSession();
471
+ const result = await transport.request(
472
+ "/v1/checkout/session",
473
+ {
474
+ sessionToken: active.sessionToken
475
+ }
476
+ );
477
+ session = {
478
+ ...active,
479
+ ...result,
480
+ sessionToken: active.sessionToken,
481
+ event: result.event || active.event,
482
+ capabilities: result.capabilities || active.capabilities || {}
483
+ };
484
+ return session;
485
+ },
314
486
  async getCatalog() {
315
487
  const active = requireSession();
316
488
  return transport.request("/v1/checkout/catalog", {
@@ -325,6 +497,14 @@ function createTickean(options) {
325
497
  sessionToken: active.sessionToken
326
498
  });
327
499
  },
500
+ async lookupBuyer(params) {
501
+ const active = requireSession();
502
+ return transport.request("/v1/checkout/buyer/lookup", {
503
+ method: "POST",
504
+ body: params,
505
+ sessionToken: active.sessionToken
506
+ });
507
+ },
328
508
  async sendOtp(params) {
329
509
  const active = requireSession();
330
510
  return transport.request("/v1/checkout/otp/send", {
@@ -343,18 +523,32 @@ function createTickean(options) {
343
523
  },
344
524
  async createPurchase(params) {
345
525
  const active = requireSession();
526
+ const { idempotencyKey, ...body } = params;
346
527
  return transport.request("/v1/checkout/purchases", {
347
528
  method: "POST",
348
- body: params,
349
- sessionToken: active.sessionToken
529
+ body,
530
+ sessionToken: active.sessionToken,
531
+ idempotencyKey
350
532
  });
351
533
  },
352
534
  async createPayment(params) {
353
535
  const active = requireSession();
536
+ const { idempotencyKey, ...body } = params;
354
537
  return transport.request("/v1/checkout/payments", {
355
538
  method: "POST",
356
- body: params,
357
- sessionToken: active.sessionToken
539
+ body,
540
+ sessionToken: active.sessionToken,
541
+ idempotencyKey
542
+ });
543
+ },
544
+ async confirmPayment(params) {
545
+ const active = requireSession();
546
+ const { idempotencyKey, ...body } = params || {};
547
+ return transport.request("/v1/checkout/payments/confirm", {
548
+ method: "POST",
549
+ body,
550
+ sessionToken: active.sessionToken,
551
+ idempotencyKey
358
552
  });
359
553
  },
360
554
  async getPaymentStatus() {
@@ -375,13 +569,17 @@ function createTickean(options) {
375
569
  });
376
570
  }
377
571
  const status = await this.getPaymentStatus();
378
- if (["COMPLETED", "CONFIRMED", "PAID"].includes(
572
+ if (["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
379
573
  String(status.status || "").toUpperCase()
380
- ) || ["COMPLETED", "CONFIRMED", "PAID"].includes(
574
+ ) || ["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
381
575
  String(status.purchase?.status || "").toUpperCase()
382
576
  )) {
383
577
  return status;
384
578
  }
579
+ const nextType = status.nextAction?.type;
580
+ if (status.nextAction && nextType && nextType !== "none" && nextType !== "display_instructions" && status.requiresAction) {
581
+ return status;
582
+ }
385
583
  await new Promise((resolve) => setTimeout(resolve, intervalMs));
386
584
  }
387
585
  throw new TickeanError({
@@ -391,8 +589,4354 @@ function createTickean(options) {
391
589
  }
392
590
  };
393
591
  }
394
- // Annotate the CommonJS export names for ESM import in node:
395
- 0 && (module.exports = {
396
- TickeanError,
397
- createTickean
592
+
593
+ // src/state.ts
594
+ function createInitialState(partial) {
595
+ return {
596
+ phase: "initializing",
597
+ session: null,
598
+ event: null,
599
+ cart: [],
600
+ discountCode: null,
601
+ quote: null,
602
+ isQuoting: false,
603
+ buyer: null,
604
+ buyerVerified: false,
605
+ otpSent: false,
606
+ purchase: null,
607
+ payment: null,
608
+ nextAction: { type: "none" },
609
+ error: null,
610
+ loading: true,
611
+ ...partial
612
+ };
613
+ }
614
+ function derivePhase(state) {
615
+ if (state.phase === "completed" || state.phase === "failed" || state.phase === "expired" || state.phase === "purchasing" || state.phase === "processing" || state.phase === "requires_action" || state.phase === "initializing") {
616
+ return state.phase;
617
+ }
618
+ if (state.isQuoting) return "quoting";
619
+ if (state.otpSent && !state.buyerVerified) return "verifying_buyer";
620
+ if (state.buyerVerified && state.cart.length > 0) return "ready_to_purchase";
621
+ return "browsing";
622
+ }
623
+ function checkoutReducer(state, action) {
624
+ switch (action.type) {
625
+ case "INIT_START":
626
+ return { ...state, loading: true, error: null, phase: "initializing" };
627
+ case "INIT_SUCCESS": {
628
+ const next = {
629
+ ...state,
630
+ loading: false,
631
+ error: null,
632
+ session: action.session,
633
+ event: action.event,
634
+ phase: "browsing"
635
+ };
636
+ return { ...next, phase: derivePhase(next) };
637
+ }
638
+ case "INIT_FAILURE":
639
+ return {
640
+ ...state,
641
+ loading: false,
642
+ error: action.error,
643
+ phase: "failed"
644
+ };
645
+ case "SET_CART": {
646
+ const next = { ...state, cart: action.cart, error: null };
647
+ return { ...next, phase: derivePhase(next) };
648
+ }
649
+ case "SET_DISCOUNT":
650
+ return { ...state, discountCode: action.discountCode };
651
+ case "QUOTE_START": {
652
+ const next = { ...state, isQuoting: true, error: null };
653
+ return { ...next, phase: "quoting" };
654
+ }
655
+ case "QUOTE_SUCCESS": {
656
+ const next = {
657
+ ...state,
658
+ isQuoting: false,
659
+ quote: action.quote
660
+ };
661
+ return { ...next, phase: derivePhase(next) };
662
+ }
663
+ case "QUOTE_FAILURE":
664
+ return {
665
+ ...state,
666
+ isQuoting: false,
667
+ error: action.error,
668
+ phase: derivePhase({ ...state, isQuoting: false })
669
+ };
670
+ case "OTP_SENT": {
671
+ const next = { ...state, otpSent: true, error: null };
672
+ return { ...next, phase: "verifying_buyer" };
673
+ }
674
+ case "OTP_VERIFIED": {
675
+ const next = {
676
+ ...state,
677
+ buyer: action.buyer,
678
+ buyerVerified: true,
679
+ otpSent: true,
680
+ error: null
681
+ };
682
+ return { ...next, phase: derivePhase(next) };
683
+ }
684
+ case "SET_EVENT":
685
+ return { ...state, event: action.event };
686
+ case "MERGE_UNLOCKED_OPTIONS": {
687
+ if (!state.event || !action.options.length) return state;
688
+ const shows = state.event.shows.map((show) => ({
689
+ ...show,
690
+ showOptions: [...show.showOptions]
691
+ }));
692
+ const byId = /* @__PURE__ */ new Map();
693
+ for (const show of shows) {
694
+ for (const opt of show.showOptions) byId.set(opt.id, opt);
695
+ }
696
+ for (const unlocked of action.options) {
697
+ if (byId.has(unlocked.id)) continue;
698
+ const showId = unlocked.showId;
699
+ let target = showId ? shows.find((s) => s.id === showId) : void 0;
700
+ if (!target) target = shows[0];
701
+ if (!target) continue;
702
+ const option = { ...unlocked };
703
+ target.showOptions.push(option);
704
+ byId.set(option.id, option);
705
+ }
706
+ return {
707
+ ...state,
708
+ event: { ...state.event, shows }
709
+ };
710
+ }
711
+ case "PURCHASE_START":
712
+ return { ...state, phase: "purchasing", error: null };
713
+ case "PURCHASE_SUCCESS": {
714
+ const requiresProviderAction = action.nextAction.type !== "none" && action.nextAction.type !== "display_instructions";
715
+ return {
716
+ ...state,
717
+ purchase: action.purchase,
718
+ payment: action.payment,
719
+ nextAction: action.nextAction,
720
+ phase: requiresProviderAction ? "requires_action" : "processing",
721
+ error: null
722
+ };
723
+ }
724
+ case "PURCHASE_FAILURE": {
725
+ const next = {
726
+ ...state,
727
+ error: action.error,
728
+ phase: "browsing"
729
+ };
730
+ return { ...next, phase: derivePhase(next) };
731
+ }
732
+ case "SET_NEXT_ACTION":
733
+ return {
734
+ ...state,
735
+ nextAction: action.nextAction,
736
+ payment: action.payment === void 0 ? state.payment : action.payment,
737
+ phase: action.nextAction.type !== "none" && action.nextAction.type !== "display_instructions" ? "requires_action" : state.phase === "requires_action" ? "processing" : state.phase
738
+ };
739
+ case "RESET_PAYMENT_FLOW": {
740
+ const next = {
741
+ ...state,
742
+ payment: null,
743
+ nextAction: { type: "none" },
744
+ error: null,
745
+ phase: "browsing"
746
+ };
747
+ return { ...next, phase: derivePhase(next) };
748
+ }
749
+ case "PROCESSING":
750
+ return { ...state, phase: "processing" };
751
+ case "COMPLETED":
752
+ return {
753
+ ...state,
754
+ phase: "completed",
755
+ purchase: action.purchase ?? state.purchase,
756
+ nextAction: { type: "none" },
757
+ error: null
758
+ };
759
+ case "FAILED":
760
+ return { ...state, phase: "failed", error: action.error };
761
+ case "EXPIRED":
762
+ return { ...state, phase: "expired" };
763
+ case "CLEAR_ERROR":
764
+ return { ...state, error: null };
765
+ case "REHYDRATE": {
766
+ const next = { ...state, ...action.partial };
767
+ return { ...next, phase: derivePhase(next) };
768
+ }
769
+ default:
770
+ return state;
771
+ }
772
+ }
773
+
774
+ // src/persistence.ts
775
+ function createMemoryPersistence() {
776
+ const store = /* @__PURE__ */ new Map();
777
+ return {
778
+ get(key) {
779
+ return store.get(key) ?? null;
780
+ },
781
+ set(key, value2) {
782
+ store.set(key, { ...value2 });
783
+ },
784
+ remove(key) {
785
+ store.delete(key);
786
+ }
787
+ };
788
+ }
789
+ function createSessionStoragePersistence(storage) {
790
+ const getStorage = () => {
791
+ if (storage) return storage;
792
+ try {
793
+ if (typeof sessionStorage !== "undefined") return sessionStorage;
794
+ } catch {
795
+ }
796
+ return null;
797
+ };
798
+ return {
799
+ get(key) {
800
+ const s = getStorage();
801
+ if (!s) return null;
802
+ try {
803
+ const raw = s.getItem(key);
804
+ if (!raw) return null;
805
+ return JSON.parse(raw);
806
+ } catch {
807
+ return null;
808
+ }
809
+ },
810
+ set(key, value2) {
811
+ const s = getStorage();
812
+ if (!s) return;
813
+ try {
814
+ const safe = {
815
+ sessionToken: value2.sessionToken,
816
+ eventSlug: value2.eventSlug,
817
+ cart: value2.cart,
818
+ discountCode: value2.discountCode,
819
+ phase: value2.phase,
820
+ buyerVerified: value2.buyerVerified,
821
+ purchaseId: value2.purchaseId
822
+ };
823
+ s.setItem(key, JSON.stringify(safe));
824
+ } catch {
825
+ }
826
+ },
827
+ remove(key) {
828
+ const s = getStorage();
829
+ if (!s) return;
830
+ try {
831
+ s.removeItem(key);
832
+ } catch {
833
+ }
834
+ }
835
+ };
836
+ }
837
+
838
+ // src/telemetry.ts
839
+ function createNoopTelemetry() {
840
+ return {
841
+ track() {
842
+ }
843
+ };
844
+ }
845
+ function createEventEmitterTelemetry(listeners = []) {
846
+ const subs = new Set(listeners);
847
+ return {
848
+ track(event) {
849
+ for (const listener of subs) {
850
+ try {
851
+ listener(event);
852
+ } catch {
853
+ }
854
+ }
855
+ },
856
+ subscribe(listener) {
857
+ subs.add(listener);
858
+ return () => {
859
+ subs.delete(listener);
860
+ };
861
+ }
862
+ };
863
+ }
864
+
865
+ // ../../node_modules/engine.io-parser/build/esm/commons.js
866
+ var PACKET_TYPES = /* @__PURE__ */ Object.create(null);
867
+ PACKET_TYPES["open"] = "0";
868
+ PACKET_TYPES["close"] = "1";
869
+ PACKET_TYPES["ping"] = "2";
870
+ PACKET_TYPES["pong"] = "3";
871
+ PACKET_TYPES["message"] = "4";
872
+ PACKET_TYPES["upgrade"] = "5";
873
+ PACKET_TYPES["noop"] = "6";
874
+ var PACKET_TYPES_REVERSE = /* @__PURE__ */ Object.create(null);
875
+ Object.keys(PACKET_TYPES).forEach((key) => {
876
+ PACKET_TYPES_REVERSE[PACKET_TYPES[key]] = key;
398
877
  });
878
+ var ERROR_PACKET = { type: "error", data: "parser error" };
879
+
880
+ // ../../node_modules/engine.io-parser/build/esm/encodePacket.browser.js
881
+ var withNativeBlob = typeof Blob === "function" || typeof Blob !== "undefined" && Object.prototype.toString.call(Blob) === "[object BlobConstructor]";
882
+ var withNativeArrayBuffer = typeof ArrayBuffer === "function";
883
+ var isView = (obj) => {
884
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj && obj.buffer instanceof ArrayBuffer;
885
+ };
886
+ var encodePacket = ({ type, data }, supportsBinary, callback) => {
887
+ if (withNativeBlob && data instanceof Blob) {
888
+ if (supportsBinary) {
889
+ return callback(data);
890
+ } else {
891
+ return encodeBlobAsBase64(data, callback);
892
+ }
893
+ } else if (withNativeArrayBuffer && (data instanceof ArrayBuffer || isView(data))) {
894
+ if (supportsBinary) {
895
+ return callback(data);
896
+ } else {
897
+ return encodeBlobAsBase64(new Blob([data]), callback);
898
+ }
899
+ }
900
+ return callback(PACKET_TYPES[type] + (data || ""));
901
+ };
902
+ var encodeBlobAsBase64 = (data, callback) => {
903
+ const fileReader = new FileReader();
904
+ fileReader.onload = function() {
905
+ const content = fileReader.result.split(",")[1];
906
+ callback("b" + (content || ""));
907
+ };
908
+ return fileReader.readAsDataURL(data);
909
+ };
910
+ function toArray(data) {
911
+ if (data instanceof Uint8Array) {
912
+ return data;
913
+ } else if (data instanceof ArrayBuffer) {
914
+ return new Uint8Array(data);
915
+ } else {
916
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
917
+ }
918
+ }
919
+ var TEXT_ENCODER;
920
+ function encodePacketToBinary(packet, callback) {
921
+ if (withNativeBlob && packet.data instanceof Blob) {
922
+ return packet.data.arrayBuffer().then(toArray).then(callback);
923
+ } else if (withNativeArrayBuffer && (packet.data instanceof ArrayBuffer || isView(packet.data))) {
924
+ return callback(toArray(packet.data));
925
+ }
926
+ encodePacket(packet, false, (encoded) => {
927
+ if (!TEXT_ENCODER) {
928
+ TEXT_ENCODER = new TextEncoder();
929
+ }
930
+ callback(TEXT_ENCODER.encode(encoded));
931
+ });
932
+ }
933
+
934
+ // ../../node_modules/engine.io-parser/build/esm/contrib/base64-arraybuffer.js
935
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
936
+ var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
937
+ for (let i = 0; i < chars.length; i++) {
938
+ lookup[chars.charCodeAt(i)] = i;
939
+ }
940
+ var decode = (base64) => {
941
+ let bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4;
942
+ if (base64[base64.length - 1] === "=") {
943
+ bufferLength--;
944
+ if (base64[base64.length - 2] === "=") {
945
+ bufferLength--;
946
+ }
947
+ }
948
+ const arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer);
949
+ for (i = 0; i < len; i += 4) {
950
+ encoded1 = lookup[base64.charCodeAt(i)];
951
+ encoded2 = lookup[base64.charCodeAt(i + 1)];
952
+ encoded3 = lookup[base64.charCodeAt(i + 2)];
953
+ encoded4 = lookup[base64.charCodeAt(i + 3)];
954
+ bytes[p++] = encoded1 << 2 | encoded2 >> 4;
955
+ bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;
956
+ bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;
957
+ }
958
+ return arraybuffer;
959
+ };
960
+
961
+ // ../../node_modules/engine.io-parser/build/esm/decodePacket.browser.js
962
+ var withNativeArrayBuffer2 = typeof ArrayBuffer === "function";
963
+ var decodePacket = (encodedPacket, binaryType) => {
964
+ if (typeof encodedPacket !== "string") {
965
+ return {
966
+ type: "message",
967
+ data: mapBinary(encodedPacket, binaryType)
968
+ };
969
+ }
970
+ const type = encodedPacket.charAt(0);
971
+ if (type === "b") {
972
+ return {
973
+ type: "message",
974
+ data: decodeBase64Packet(encodedPacket.substring(1), binaryType)
975
+ };
976
+ }
977
+ const packetType = PACKET_TYPES_REVERSE[type];
978
+ if (!packetType) {
979
+ return ERROR_PACKET;
980
+ }
981
+ return encodedPacket.length > 1 ? {
982
+ type: PACKET_TYPES_REVERSE[type],
983
+ data: encodedPacket.substring(1)
984
+ } : {
985
+ type: PACKET_TYPES_REVERSE[type]
986
+ };
987
+ };
988
+ var decodeBase64Packet = (data, binaryType) => {
989
+ if (withNativeArrayBuffer2) {
990
+ const decoded = decode(data);
991
+ return mapBinary(decoded, binaryType);
992
+ } else {
993
+ return { base64: true, data };
994
+ }
995
+ };
996
+ var mapBinary = (data, binaryType) => {
997
+ switch (binaryType) {
998
+ case "blob":
999
+ if (data instanceof Blob) {
1000
+ return data;
1001
+ } else {
1002
+ return new Blob([data]);
1003
+ }
1004
+ case "arraybuffer":
1005
+ default:
1006
+ if (data instanceof ArrayBuffer) {
1007
+ return data;
1008
+ } else {
1009
+ return data.buffer;
1010
+ }
1011
+ }
1012
+ };
1013
+
1014
+ // ../../node_modules/engine.io-parser/build/esm/index.js
1015
+ var SEPARATOR = String.fromCharCode(30);
1016
+ var encodePayload = (packets, callback) => {
1017
+ const length = packets.length;
1018
+ const encodedPackets = new Array(length);
1019
+ let count = 0;
1020
+ packets.forEach((packet, i) => {
1021
+ encodePacket(packet, false, (encodedPacket) => {
1022
+ encodedPackets[i] = encodedPacket;
1023
+ if (++count === length) {
1024
+ callback(encodedPackets.join(SEPARATOR));
1025
+ }
1026
+ });
1027
+ });
1028
+ };
1029
+ var decodePayload = (encodedPayload, binaryType) => {
1030
+ const encodedPackets = encodedPayload.split(SEPARATOR);
1031
+ const packets = [];
1032
+ for (let i = 0; i < encodedPackets.length; i++) {
1033
+ const decodedPacket = decodePacket(encodedPackets[i], binaryType);
1034
+ packets.push(decodedPacket);
1035
+ if (decodedPacket.type === "error") {
1036
+ break;
1037
+ }
1038
+ }
1039
+ return packets;
1040
+ };
1041
+ function createPacketEncoderStream() {
1042
+ return new TransformStream({
1043
+ transform(packet, controller) {
1044
+ encodePacketToBinary(packet, (encodedPacket) => {
1045
+ const payloadLength = encodedPacket.length;
1046
+ let header;
1047
+ if (payloadLength < 126) {
1048
+ header = new Uint8Array(1);
1049
+ new DataView(header.buffer).setUint8(0, payloadLength);
1050
+ } else if (payloadLength < 65536) {
1051
+ header = new Uint8Array(3);
1052
+ const view = new DataView(header.buffer);
1053
+ view.setUint8(0, 126);
1054
+ view.setUint16(1, payloadLength);
1055
+ } else {
1056
+ header = new Uint8Array(9);
1057
+ const view = new DataView(header.buffer);
1058
+ view.setUint8(0, 127);
1059
+ view.setBigUint64(1, BigInt(payloadLength));
1060
+ }
1061
+ if (packet.data && typeof packet.data !== "string") {
1062
+ header[0] |= 128;
1063
+ }
1064
+ controller.enqueue(header);
1065
+ controller.enqueue(encodedPacket);
1066
+ });
1067
+ }
1068
+ });
1069
+ }
1070
+ var TEXT_DECODER;
1071
+ function totalLength(chunks) {
1072
+ return chunks.reduce((acc, chunk) => acc + chunk.length, 0);
1073
+ }
1074
+ function concatChunks(chunks, size) {
1075
+ if (chunks[0].length === size) {
1076
+ return chunks.shift();
1077
+ }
1078
+ const buffer = new Uint8Array(size);
1079
+ let j = 0;
1080
+ for (let i = 0; i < size; i++) {
1081
+ buffer[i] = chunks[0][j++];
1082
+ if (j === chunks[0].length) {
1083
+ chunks.shift();
1084
+ j = 0;
1085
+ }
1086
+ }
1087
+ if (chunks.length && j < chunks[0].length) {
1088
+ chunks[0] = chunks[0].slice(j);
1089
+ }
1090
+ return buffer;
1091
+ }
1092
+ function createPacketDecoderStream(maxPayload, binaryType) {
1093
+ if (!TEXT_DECODER) {
1094
+ TEXT_DECODER = new TextDecoder();
1095
+ }
1096
+ const chunks = [];
1097
+ let state = 0;
1098
+ let expectedLength = -1;
1099
+ let isBinary2 = false;
1100
+ return new TransformStream({
1101
+ transform(chunk, controller) {
1102
+ chunks.push(chunk);
1103
+ while (true) {
1104
+ if (state === 0) {
1105
+ if (totalLength(chunks) < 1) {
1106
+ break;
1107
+ }
1108
+ const header = concatChunks(chunks, 1);
1109
+ isBinary2 = (header[0] & 128) === 128;
1110
+ expectedLength = header[0] & 127;
1111
+ if (expectedLength < 126) {
1112
+ state = 3;
1113
+ } else if (expectedLength === 126) {
1114
+ state = 1;
1115
+ } else {
1116
+ state = 2;
1117
+ }
1118
+ } else if (state === 1) {
1119
+ if (totalLength(chunks) < 2) {
1120
+ break;
1121
+ }
1122
+ const headerArray = concatChunks(chunks, 2);
1123
+ expectedLength = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length).getUint16(0);
1124
+ state = 3;
1125
+ } else if (state === 2) {
1126
+ if (totalLength(chunks) < 8) {
1127
+ break;
1128
+ }
1129
+ const headerArray = concatChunks(chunks, 8);
1130
+ const view = new DataView(headerArray.buffer, headerArray.byteOffset, headerArray.length);
1131
+ const n = view.getUint32(0);
1132
+ if (n > Math.pow(2, 53 - 32) - 1) {
1133
+ controller.enqueue(ERROR_PACKET);
1134
+ break;
1135
+ }
1136
+ expectedLength = n * Math.pow(2, 32) + view.getUint32(4);
1137
+ state = 3;
1138
+ } else {
1139
+ if (totalLength(chunks) < expectedLength) {
1140
+ break;
1141
+ }
1142
+ const data = concatChunks(chunks, expectedLength);
1143
+ controller.enqueue(decodePacket(isBinary2 ? data : TEXT_DECODER.decode(data), binaryType));
1144
+ state = 0;
1145
+ }
1146
+ if (expectedLength === 0 || expectedLength > maxPayload) {
1147
+ controller.enqueue(ERROR_PACKET);
1148
+ break;
1149
+ }
1150
+ }
1151
+ }
1152
+ });
1153
+ }
1154
+ var protocol = 4;
1155
+
1156
+ // ../../node_modules/@socket.io/component-emitter/lib/esm/index.js
1157
+ function Emitter(obj) {
1158
+ if (obj) return mixin(obj);
1159
+ }
1160
+ function mixin(obj) {
1161
+ for (var key in Emitter.prototype) {
1162
+ obj[key] = Emitter.prototype[key];
1163
+ }
1164
+ return obj;
1165
+ }
1166
+ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn) {
1167
+ this._callbacks = this._callbacks || {};
1168
+ (this._callbacks["$" + event] = this._callbacks["$" + event] || []).push(fn);
1169
+ return this;
1170
+ };
1171
+ Emitter.prototype.once = function(event, fn) {
1172
+ function on2() {
1173
+ this.off(event, on2);
1174
+ fn.apply(this, arguments);
1175
+ }
1176
+ on2.fn = fn;
1177
+ this.on(event, on2);
1178
+ return this;
1179
+ };
1180
+ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn) {
1181
+ this._callbacks = this._callbacks || {};
1182
+ if (0 == arguments.length) {
1183
+ this._callbacks = {};
1184
+ return this;
1185
+ }
1186
+ var callbacks = this._callbacks["$" + event];
1187
+ if (!callbacks) return this;
1188
+ if (1 == arguments.length) {
1189
+ delete this._callbacks["$" + event];
1190
+ return this;
1191
+ }
1192
+ var cb;
1193
+ for (var i = 0; i < callbacks.length; i++) {
1194
+ cb = callbacks[i];
1195
+ if (cb === fn || cb.fn === fn) {
1196
+ callbacks.splice(i, 1);
1197
+ break;
1198
+ }
1199
+ }
1200
+ if (callbacks.length === 0) {
1201
+ delete this._callbacks["$" + event];
1202
+ }
1203
+ return this;
1204
+ };
1205
+ Emitter.prototype.emit = function(event) {
1206
+ this._callbacks = this._callbacks || {};
1207
+ var args = new Array(arguments.length - 1), callbacks = this._callbacks["$" + event];
1208
+ for (var i = 1; i < arguments.length; i++) {
1209
+ args[i - 1] = arguments[i];
1210
+ }
1211
+ if (callbacks) {
1212
+ callbacks = callbacks.slice(0);
1213
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
1214
+ callbacks[i].apply(this, args);
1215
+ }
1216
+ }
1217
+ return this;
1218
+ };
1219
+ Emitter.prototype.emitReserved = Emitter.prototype.emit;
1220
+ Emitter.prototype.listeners = function(event) {
1221
+ this._callbacks = this._callbacks || {};
1222
+ return this._callbacks["$" + event] || [];
1223
+ };
1224
+ Emitter.prototype.hasListeners = function(event) {
1225
+ return !!this.listeners(event).length;
1226
+ };
1227
+
1228
+ // ../../node_modules/engine.io-client/build/esm/globals.js
1229
+ var nextTick = (() => {
1230
+ const isPromiseAvailable = typeof Promise === "function" && typeof Promise.resolve === "function";
1231
+ if (isPromiseAvailable) {
1232
+ return (cb) => Promise.resolve().then(cb);
1233
+ } else {
1234
+ return (cb, setTimeoutFn) => setTimeoutFn(cb, 0);
1235
+ }
1236
+ })();
1237
+ var globalThisShim = (() => {
1238
+ if (typeof self !== "undefined") {
1239
+ return self;
1240
+ } else if (typeof window !== "undefined") {
1241
+ return window;
1242
+ } else {
1243
+ return Function("return this")();
1244
+ }
1245
+ })();
1246
+ var defaultBinaryType = "arraybuffer";
1247
+ function createCookieJar() {
1248
+ }
1249
+
1250
+ // ../../node_modules/engine.io-client/build/esm/util.js
1251
+ function pick(obj, ...attr) {
1252
+ return attr.reduce((acc, k) => {
1253
+ if (obj.hasOwnProperty(k)) {
1254
+ acc[k] = obj[k];
1255
+ }
1256
+ return acc;
1257
+ }, {});
1258
+ }
1259
+ var NATIVE_SET_TIMEOUT = globalThisShim.setTimeout;
1260
+ var NATIVE_CLEAR_TIMEOUT = globalThisShim.clearTimeout;
1261
+ function installTimerFunctions(obj, opts) {
1262
+ if (opts.useNativeTimers) {
1263
+ obj.setTimeoutFn = NATIVE_SET_TIMEOUT.bind(globalThisShim);
1264
+ obj.clearTimeoutFn = NATIVE_CLEAR_TIMEOUT.bind(globalThisShim);
1265
+ } else {
1266
+ obj.setTimeoutFn = globalThisShim.setTimeout.bind(globalThisShim);
1267
+ obj.clearTimeoutFn = globalThisShim.clearTimeout.bind(globalThisShim);
1268
+ }
1269
+ }
1270
+ var BASE64_OVERHEAD = 1.33;
1271
+ function byteLength(obj) {
1272
+ if (typeof obj === "string") {
1273
+ return utf8Length(obj);
1274
+ }
1275
+ return Math.ceil((obj.byteLength || obj.size) * BASE64_OVERHEAD);
1276
+ }
1277
+ function utf8Length(str) {
1278
+ let c = 0, length = 0;
1279
+ for (let i = 0, l = str.length; i < l; i++) {
1280
+ c = str.charCodeAt(i);
1281
+ if (c < 128) {
1282
+ length += 1;
1283
+ } else if (c < 2048) {
1284
+ length += 2;
1285
+ } else if (c < 55296 || c >= 57344) {
1286
+ length += 3;
1287
+ } else {
1288
+ i++;
1289
+ length += 4;
1290
+ }
1291
+ }
1292
+ return length;
1293
+ }
1294
+ function randomString() {
1295
+ return Date.now().toString(36).substring(3) + Math.random().toString(36).substring(2, 5);
1296
+ }
1297
+
1298
+ // ../../node_modules/engine.io-client/build/esm/contrib/parseqs.js
1299
+ function encode(obj) {
1300
+ let str = "";
1301
+ for (let i in obj) {
1302
+ if (obj.hasOwnProperty(i)) {
1303
+ if (str.length)
1304
+ str += "&";
1305
+ str += encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]);
1306
+ }
1307
+ }
1308
+ return str;
1309
+ }
1310
+ function decode2(qs) {
1311
+ let qry = {};
1312
+ let pairs = qs.split("&");
1313
+ for (let i = 0, l = pairs.length; i < l; i++) {
1314
+ let pair = pairs[i].split("=");
1315
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
1316
+ }
1317
+ return qry;
1318
+ }
1319
+
1320
+ // ../../node_modules/engine.io-client/build/esm/transport.js
1321
+ var TransportError = class extends Error {
1322
+ constructor(reason, description, context) {
1323
+ super(reason);
1324
+ this.description = description;
1325
+ this.context = context;
1326
+ this.type = "TransportError";
1327
+ }
1328
+ };
1329
+ var Transport = class extends Emitter {
1330
+ /**
1331
+ * Transport abstract constructor.
1332
+ *
1333
+ * @param {Object} opts - options
1334
+ * @protected
1335
+ */
1336
+ constructor(opts) {
1337
+ super();
1338
+ this.writable = false;
1339
+ installTimerFunctions(this, opts);
1340
+ this.opts = opts;
1341
+ this.query = opts.query;
1342
+ this.socket = opts.socket;
1343
+ this.supportsBinary = !opts.forceBase64;
1344
+ }
1345
+ /**
1346
+ * Emits an error.
1347
+ *
1348
+ * @param {String} reason
1349
+ * @param description
1350
+ * @param context - the error context
1351
+ * @return {Transport} for chaining
1352
+ * @protected
1353
+ */
1354
+ onError(reason, description, context) {
1355
+ super.emitReserved("error", new TransportError(reason, description, context));
1356
+ return this;
1357
+ }
1358
+ /**
1359
+ * Opens the transport.
1360
+ */
1361
+ open() {
1362
+ this.readyState = "opening";
1363
+ this.doOpen();
1364
+ return this;
1365
+ }
1366
+ /**
1367
+ * Closes the transport.
1368
+ */
1369
+ close() {
1370
+ if (this.readyState === "opening" || this.readyState === "open") {
1371
+ this.doClose();
1372
+ this.onClose();
1373
+ }
1374
+ return this;
1375
+ }
1376
+ /**
1377
+ * Sends multiple packets.
1378
+ *
1379
+ * @param {Array} packets
1380
+ */
1381
+ send(packets) {
1382
+ if (this.readyState === "open") {
1383
+ this.write(packets);
1384
+ } else {
1385
+ }
1386
+ }
1387
+ /**
1388
+ * Called upon open
1389
+ *
1390
+ * @protected
1391
+ */
1392
+ onOpen() {
1393
+ this.readyState = "open";
1394
+ this.writable = true;
1395
+ super.emitReserved("open");
1396
+ }
1397
+ /**
1398
+ * Called with data.
1399
+ *
1400
+ * @param {String} data
1401
+ * @protected
1402
+ */
1403
+ onData(data) {
1404
+ const packet = decodePacket(data, this.socket.binaryType);
1405
+ this.onPacket(packet);
1406
+ }
1407
+ /**
1408
+ * Called with a decoded packet.
1409
+ *
1410
+ * @protected
1411
+ */
1412
+ onPacket(packet) {
1413
+ super.emitReserved("packet", packet);
1414
+ }
1415
+ /**
1416
+ * Called upon close.
1417
+ *
1418
+ * @protected
1419
+ */
1420
+ onClose(details) {
1421
+ this.readyState = "closed";
1422
+ super.emitReserved("close", details);
1423
+ }
1424
+ /**
1425
+ * Pauses the transport, in order not to lose packets during an upgrade.
1426
+ *
1427
+ * @param onPause
1428
+ */
1429
+ pause(onPause) {
1430
+ }
1431
+ createUri(schema, query = {}) {
1432
+ return schema + "://" + this._hostname() + this._port() + this.opts.path + this._query(query);
1433
+ }
1434
+ _hostname() {
1435
+ const hostname = this.opts.hostname;
1436
+ return hostname.indexOf(":") === -1 ? hostname : "[" + hostname + "]";
1437
+ }
1438
+ _port() {
1439
+ if (this.opts.port && (this.opts.secure && Number(this.opts.port) !== 443 || !this.opts.secure && Number(this.opts.port) !== 80)) {
1440
+ return ":" + this.opts.port;
1441
+ } else {
1442
+ return "";
1443
+ }
1444
+ }
1445
+ _query(query) {
1446
+ const encodedQuery = encode(query);
1447
+ return encodedQuery.length ? "?" + encodedQuery : "";
1448
+ }
1449
+ };
1450
+
1451
+ // ../../node_modules/engine.io-client/build/esm/transports/polling.js
1452
+ var Polling = class extends Transport {
1453
+ constructor() {
1454
+ super(...arguments);
1455
+ this._polling = false;
1456
+ }
1457
+ get name() {
1458
+ return "polling";
1459
+ }
1460
+ /**
1461
+ * Opens the socket (triggers polling). We write a PING message to determine
1462
+ * when the transport is open.
1463
+ *
1464
+ * @protected
1465
+ */
1466
+ doOpen() {
1467
+ this._poll();
1468
+ }
1469
+ /**
1470
+ * Pauses polling.
1471
+ *
1472
+ * @param {Function} onPause - callback upon buffers are flushed and transport is paused
1473
+ * @package
1474
+ */
1475
+ pause(onPause) {
1476
+ this.readyState = "pausing";
1477
+ const pause = () => {
1478
+ this.readyState = "paused";
1479
+ onPause();
1480
+ };
1481
+ if (this._polling || !this.writable) {
1482
+ let total = 0;
1483
+ if (this._polling) {
1484
+ total++;
1485
+ this.once("pollComplete", function() {
1486
+ --total || pause();
1487
+ });
1488
+ }
1489
+ if (!this.writable) {
1490
+ total++;
1491
+ this.once("drain", function() {
1492
+ --total || pause();
1493
+ });
1494
+ }
1495
+ } else {
1496
+ pause();
1497
+ }
1498
+ }
1499
+ /**
1500
+ * Starts polling cycle.
1501
+ *
1502
+ * @private
1503
+ */
1504
+ _poll() {
1505
+ this._polling = true;
1506
+ this.doPoll();
1507
+ this.emitReserved("poll");
1508
+ }
1509
+ /**
1510
+ * Overloads onData to detect payloads.
1511
+ *
1512
+ * @protected
1513
+ */
1514
+ onData(data) {
1515
+ const callback = (packet) => {
1516
+ if ("opening" === this.readyState && packet.type === "open") {
1517
+ this.onOpen();
1518
+ }
1519
+ if ("close" === packet.type) {
1520
+ this.onClose({ description: "transport closed by the server" });
1521
+ return false;
1522
+ }
1523
+ this.onPacket(packet);
1524
+ };
1525
+ decodePayload(data, this.socket.binaryType).forEach(callback);
1526
+ if ("closed" !== this.readyState) {
1527
+ this._polling = false;
1528
+ this.emitReserved("pollComplete");
1529
+ if ("open" === this.readyState) {
1530
+ this._poll();
1531
+ } else {
1532
+ }
1533
+ }
1534
+ }
1535
+ /**
1536
+ * For polling, send a close packet.
1537
+ *
1538
+ * @protected
1539
+ */
1540
+ doClose() {
1541
+ const close = () => {
1542
+ this.write([{ type: "close" }]);
1543
+ };
1544
+ if ("open" === this.readyState) {
1545
+ close();
1546
+ } else {
1547
+ this.once("open", close);
1548
+ }
1549
+ }
1550
+ /**
1551
+ * Writes a packets payload.
1552
+ *
1553
+ * @param {Array} packets - data packets
1554
+ * @protected
1555
+ */
1556
+ write(packets) {
1557
+ this.writable = false;
1558
+ encodePayload(packets, (data) => {
1559
+ this.doWrite(data, () => {
1560
+ this.writable = true;
1561
+ this.emitReserved("drain");
1562
+ });
1563
+ });
1564
+ }
1565
+ /**
1566
+ * Generates uri for connection.
1567
+ *
1568
+ * @private
1569
+ */
1570
+ uri() {
1571
+ const schema = this.opts.secure ? "https" : "http";
1572
+ const query = this.query || {};
1573
+ if (false !== this.opts.timestampRequests) {
1574
+ query[this.opts.timestampParam] = randomString();
1575
+ }
1576
+ if (!this.supportsBinary && !query.sid) {
1577
+ query.b64 = 1;
1578
+ }
1579
+ return this.createUri(schema, query);
1580
+ }
1581
+ };
1582
+
1583
+ // ../../node_modules/engine.io-client/build/esm/contrib/has-cors.js
1584
+ var value = false;
1585
+ try {
1586
+ value = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest();
1587
+ } catch (err) {
1588
+ }
1589
+ var hasCORS = value;
1590
+
1591
+ // ../../node_modules/engine.io-client/build/esm/transports/polling-xhr.js
1592
+ function empty() {
1593
+ }
1594
+ var BaseXHR = class extends Polling {
1595
+ /**
1596
+ * XHR Polling constructor.
1597
+ *
1598
+ * @param {Object} opts
1599
+ * @package
1600
+ */
1601
+ constructor(opts) {
1602
+ super(opts);
1603
+ if (typeof location !== "undefined") {
1604
+ const isSSL = "https:" === location.protocol;
1605
+ let port = location.port;
1606
+ if (!port) {
1607
+ port = isSSL ? "443" : "80";
1608
+ }
1609
+ this.xd = typeof location !== "undefined" && opts.hostname !== location.hostname || port !== opts.port;
1610
+ }
1611
+ }
1612
+ /**
1613
+ * Sends data.
1614
+ *
1615
+ * @param {String} data - data to send.
1616
+ * @param {Function} fn - called upon flush.
1617
+ * @private
1618
+ */
1619
+ doWrite(data, fn) {
1620
+ const req = this.request({
1621
+ method: "POST",
1622
+ data
1623
+ });
1624
+ req.on("success", fn);
1625
+ req.on("error", (xhrStatus, context) => {
1626
+ this.onError("xhr post error", xhrStatus, context);
1627
+ });
1628
+ }
1629
+ /**
1630
+ * Starts a poll cycle.
1631
+ *
1632
+ * @private
1633
+ */
1634
+ doPoll() {
1635
+ const req = this.request();
1636
+ req.on("data", this.onData.bind(this));
1637
+ req.on("error", (xhrStatus, context) => {
1638
+ this.onError("xhr poll error", xhrStatus, context);
1639
+ });
1640
+ this.pollXhr = req;
1641
+ }
1642
+ };
1643
+ var Request = class _Request extends Emitter {
1644
+ /**
1645
+ * Request constructor
1646
+ *
1647
+ * @param {Object} options
1648
+ * @package
1649
+ */
1650
+ constructor(createRequest, uri, opts) {
1651
+ super();
1652
+ this.createRequest = createRequest;
1653
+ installTimerFunctions(this, opts);
1654
+ this._opts = opts;
1655
+ this._method = opts.method || "GET";
1656
+ this._uri = uri;
1657
+ this._data = void 0 !== opts.data ? opts.data : null;
1658
+ this._create();
1659
+ }
1660
+ /**
1661
+ * Creates the XHR object and sends the request.
1662
+ *
1663
+ * @private
1664
+ */
1665
+ _create() {
1666
+ var _a;
1667
+ const opts = pick(this._opts, "agent", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "autoUnref");
1668
+ opts.xdomain = !!this._opts.xd;
1669
+ const xhr = this._xhr = this.createRequest(opts);
1670
+ try {
1671
+ xhr.open(this._method, this._uri, true);
1672
+ try {
1673
+ if (this._opts.extraHeaders) {
1674
+ xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
1675
+ for (let i in this._opts.extraHeaders) {
1676
+ if (this._opts.extraHeaders.hasOwnProperty(i)) {
1677
+ xhr.setRequestHeader(i, this._opts.extraHeaders[i]);
1678
+ }
1679
+ }
1680
+ }
1681
+ } catch (e) {
1682
+ }
1683
+ if ("POST" === this._method) {
1684
+ try {
1685
+ xhr.setRequestHeader("Content-type", "text/plain;charset=UTF-8");
1686
+ } catch (e) {
1687
+ }
1688
+ }
1689
+ try {
1690
+ xhr.setRequestHeader("Accept", "*/*");
1691
+ } catch (e) {
1692
+ }
1693
+ (_a = this._opts.cookieJar) === null || _a === void 0 ? void 0 : _a.addCookies(xhr);
1694
+ if ("withCredentials" in xhr) {
1695
+ xhr.withCredentials = this._opts.withCredentials;
1696
+ }
1697
+ if (this._opts.requestTimeout) {
1698
+ xhr.timeout = this._opts.requestTimeout;
1699
+ }
1700
+ xhr.onreadystatechange = () => {
1701
+ var _a2;
1702
+ if (xhr.readyState === 3) {
1703
+ (_a2 = this._opts.cookieJar) === null || _a2 === void 0 ? void 0 : _a2.parseCookies(
1704
+ // @ts-ignore
1705
+ xhr.getResponseHeader("set-cookie")
1706
+ );
1707
+ }
1708
+ if (4 !== xhr.readyState)
1709
+ return;
1710
+ if (200 === xhr.status || 1223 === xhr.status) {
1711
+ this._onLoad();
1712
+ } else {
1713
+ this.setTimeoutFn(() => {
1714
+ this._onError(typeof xhr.status === "number" ? xhr.status : 0);
1715
+ }, 0);
1716
+ }
1717
+ };
1718
+ xhr.send(this._data);
1719
+ } catch (e) {
1720
+ this.setTimeoutFn(() => {
1721
+ this._onError(e);
1722
+ }, 0);
1723
+ return;
1724
+ }
1725
+ if (typeof document !== "undefined") {
1726
+ this._index = _Request.requestsCount++;
1727
+ _Request.requests[this._index] = this;
1728
+ }
1729
+ }
1730
+ /**
1731
+ * Called upon error.
1732
+ *
1733
+ * @private
1734
+ */
1735
+ _onError(err) {
1736
+ this.emitReserved("error", err, this._xhr);
1737
+ this._cleanup(true);
1738
+ }
1739
+ /**
1740
+ * Cleans up house.
1741
+ *
1742
+ * @private
1743
+ */
1744
+ _cleanup(fromError) {
1745
+ if ("undefined" === typeof this._xhr || null === this._xhr) {
1746
+ return;
1747
+ }
1748
+ this._xhr.onreadystatechange = empty;
1749
+ if (fromError) {
1750
+ try {
1751
+ this._xhr.abort();
1752
+ } catch (e) {
1753
+ }
1754
+ }
1755
+ if (typeof document !== "undefined") {
1756
+ delete _Request.requests[this._index];
1757
+ }
1758
+ this._xhr = null;
1759
+ }
1760
+ /**
1761
+ * Called upon load.
1762
+ *
1763
+ * @private
1764
+ */
1765
+ _onLoad() {
1766
+ const data = this._xhr.responseText;
1767
+ if (data !== null) {
1768
+ this.emitReserved("data", data);
1769
+ this.emitReserved("success");
1770
+ this._cleanup();
1771
+ }
1772
+ }
1773
+ /**
1774
+ * Aborts the request.
1775
+ *
1776
+ * @package
1777
+ */
1778
+ abort() {
1779
+ this._cleanup();
1780
+ }
1781
+ };
1782
+ Request.requestsCount = 0;
1783
+ Request.requests = {};
1784
+ if (typeof document !== "undefined") {
1785
+ if (typeof attachEvent === "function") {
1786
+ attachEvent("onunload", unloadHandler);
1787
+ } else if (typeof addEventListener === "function") {
1788
+ const terminationEvent = "onpagehide" in globalThisShim ? "pagehide" : "unload";
1789
+ addEventListener(terminationEvent, unloadHandler, false);
1790
+ }
1791
+ }
1792
+ function unloadHandler() {
1793
+ for (let i in Request.requests) {
1794
+ if (Request.requests.hasOwnProperty(i)) {
1795
+ Request.requests[i].abort();
1796
+ }
1797
+ }
1798
+ }
1799
+ var hasXHR2 = (function() {
1800
+ const xhr = newRequest({
1801
+ xdomain: false
1802
+ });
1803
+ return xhr && xhr.responseType !== null;
1804
+ })();
1805
+ var XHR = class extends BaseXHR {
1806
+ constructor(opts) {
1807
+ super(opts);
1808
+ const forceBase64 = opts && opts.forceBase64;
1809
+ this.supportsBinary = hasXHR2 && !forceBase64;
1810
+ }
1811
+ request(opts = {}) {
1812
+ Object.assign(opts, { xd: this.xd }, this.opts);
1813
+ return new Request(newRequest, this.uri(), opts);
1814
+ }
1815
+ };
1816
+ function newRequest(opts) {
1817
+ const xdomain = opts.xdomain;
1818
+ try {
1819
+ if ("undefined" !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
1820
+ return new XMLHttpRequest();
1821
+ }
1822
+ } catch (e) {
1823
+ }
1824
+ if (!xdomain) {
1825
+ try {
1826
+ return new globalThisShim[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP");
1827
+ } catch (e) {
1828
+ }
1829
+ }
1830
+ }
1831
+
1832
+ // ../../node_modules/engine.io-client/build/esm/transports/websocket.js
1833
+ var isReactNative = typeof navigator !== "undefined" && typeof navigator.product === "string" && navigator.product.toLowerCase() === "reactnative";
1834
+ var BaseWS = class extends Transport {
1835
+ get name() {
1836
+ return "websocket";
1837
+ }
1838
+ doOpen() {
1839
+ const uri = this.uri();
1840
+ const protocols = this.opts.protocols;
1841
+ const opts = isReactNative ? {} : pick(this.opts, "agent", "perMessageDeflate", "pfx", "key", "passphrase", "cert", "ca", "ciphers", "rejectUnauthorized", "localAddress", "protocolVersion", "origin", "maxPayload", "family", "checkServerIdentity");
1842
+ if (this.opts.extraHeaders) {
1843
+ opts.headers = this.opts.extraHeaders;
1844
+ }
1845
+ try {
1846
+ this.ws = this.createSocket(uri, protocols, opts);
1847
+ } catch (err) {
1848
+ return this.emitReserved("error", err);
1849
+ }
1850
+ this.ws.binaryType = this.socket.binaryType;
1851
+ this.addEventListeners();
1852
+ }
1853
+ /**
1854
+ * Adds event listeners to the socket
1855
+ *
1856
+ * @private
1857
+ */
1858
+ addEventListeners() {
1859
+ this.ws.onopen = () => {
1860
+ if (this.opts.autoUnref) {
1861
+ this.ws._socket.unref();
1862
+ }
1863
+ this.onOpen();
1864
+ };
1865
+ this.ws.onclose = (closeEvent) => this.onClose({
1866
+ description: "websocket connection closed",
1867
+ context: closeEvent
1868
+ });
1869
+ this.ws.onmessage = (ev) => this.onData(ev.data);
1870
+ this.ws.onerror = (e) => this.onError("websocket error", e);
1871
+ }
1872
+ write(packets) {
1873
+ this.writable = false;
1874
+ for (let i = 0; i < packets.length; i++) {
1875
+ const packet = packets[i];
1876
+ const lastPacket = i === packets.length - 1;
1877
+ encodePacket(packet, this.supportsBinary, (data) => {
1878
+ try {
1879
+ this.doWrite(packet, data);
1880
+ } catch (e) {
1881
+ }
1882
+ if (lastPacket) {
1883
+ nextTick(() => {
1884
+ this.writable = true;
1885
+ this.emitReserved("drain");
1886
+ }, this.setTimeoutFn);
1887
+ }
1888
+ });
1889
+ }
1890
+ }
1891
+ doClose() {
1892
+ if (typeof this.ws !== "undefined") {
1893
+ this.ws.onerror = () => {
1894
+ };
1895
+ this.ws.close();
1896
+ this.ws = null;
1897
+ }
1898
+ }
1899
+ /**
1900
+ * Generates uri for connection.
1901
+ *
1902
+ * @private
1903
+ */
1904
+ uri() {
1905
+ const schema = this.opts.secure ? "wss" : "ws";
1906
+ const query = this.query || {};
1907
+ if (this.opts.timestampRequests) {
1908
+ query[this.opts.timestampParam] = randomString();
1909
+ }
1910
+ if (!this.supportsBinary) {
1911
+ query.b64 = 1;
1912
+ }
1913
+ return this.createUri(schema, query);
1914
+ }
1915
+ };
1916
+ var WebSocketCtor = globalThisShim.WebSocket || globalThisShim.MozWebSocket;
1917
+ var WS = class extends BaseWS {
1918
+ createSocket(uri, protocols, opts) {
1919
+ return !isReactNative ? protocols ? new WebSocketCtor(uri, protocols) : new WebSocketCtor(uri) : new WebSocketCtor(uri, protocols, opts);
1920
+ }
1921
+ doWrite(_packet, data) {
1922
+ this.ws.send(data);
1923
+ }
1924
+ };
1925
+
1926
+ // ../../node_modules/engine.io-client/build/esm/transports/webtransport.js
1927
+ var WT = class extends Transport {
1928
+ get name() {
1929
+ return "webtransport";
1930
+ }
1931
+ doOpen() {
1932
+ try {
1933
+ this._transport = new WebTransport(this.createUri("https"), this.opts.transportOptions[this.name]);
1934
+ } catch (err) {
1935
+ return this.emitReserved("error", err);
1936
+ }
1937
+ this._transport.closed.then(() => {
1938
+ this.onClose();
1939
+ }).catch((err) => {
1940
+ this.onError("webtransport error", err);
1941
+ });
1942
+ this._transport.ready.then(() => {
1943
+ this._transport.createBidirectionalStream().then((stream) => {
1944
+ const decoderStream = createPacketDecoderStream(Number.MAX_SAFE_INTEGER, this.socket.binaryType);
1945
+ const reader = stream.readable.pipeThrough(decoderStream).getReader();
1946
+ const encoderStream = createPacketEncoderStream();
1947
+ encoderStream.readable.pipeTo(stream.writable);
1948
+ this._writer = encoderStream.writable.getWriter();
1949
+ const read = () => {
1950
+ reader.read().then(({ done, value: value2 }) => {
1951
+ if (done) {
1952
+ return;
1953
+ }
1954
+ this.onPacket(value2);
1955
+ read();
1956
+ }).catch((err) => {
1957
+ });
1958
+ };
1959
+ read();
1960
+ const packet = { type: "open" };
1961
+ if (this.query.sid) {
1962
+ packet.data = `{"sid":"${this.query.sid}"}`;
1963
+ }
1964
+ this._writer.write(packet).then(() => this.onOpen());
1965
+ });
1966
+ });
1967
+ }
1968
+ write(packets) {
1969
+ this.writable = false;
1970
+ for (let i = 0; i < packets.length; i++) {
1971
+ const packet = packets[i];
1972
+ const lastPacket = i === packets.length - 1;
1973
+ this._writer.write(packet).then(() => {
1974
+ if (lastPacket) {
1975
+ nextTick(() => {
1976
+ this.writable = true;
1977
+ this.emitReserved("drain");
1978
+ }, this.setTimeoutFn);
1979
+ }
1980
+ });
1981
+ }
1982
+ }
1983
+ doClose() {
1984
+ var _a;
1985
+ (_a = this._transport) === null || _a === void 0 ? void 0 : _a.close();
1986
+ }
1987
+ };
1988
+
1989
+ // ../../node_modules/engine.io-client/build/esm/transports/index.js
1990
+ var transports = {
1991
+ websocket: WS,
1992
+ webtransport: WT,
1993
+ polling: XHR
1994
+ };
1995
+
1996
+ // ../../node_modules/engine.io-client/build/esm/contrib/parseuri.js
1997
+ var re = /^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
1998
+ var parts = [
1999
+ "source",
2000
+ "protocol",
2001
+ "authority",
2002
+ "userInfo",
2003
+ "user",
2004
+ "password",
2005
+ "host",
2006
+ "port",
2007
+ "relative",
2008
+ "path",
2009
+ "directory",
2010
+ "file",
2011
+ "query",
2012
+ "anchor"
2013
+ ];
2014
+ function parse(str) {
2015
+ if (str.length > 8e3) {
2016
+ throw "URI too long";
2017
+ }
2018
+ const src = str, b = str.indexOf("["), e = str.indexOf("]");
2019
+ if (b != -1 && e != -1) {
2020
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ";") + str.substring(e, str.length);
2021
+ }
2022
+ let m = re.exec(str || ""), uri = {}, i = 14;
2023
+ while (i--) {
2024
+ uri[parts[i]] = m[i] || "";
2025
+ }
2026
+ if (b != -1 && e != -1) {
2027
+ uri.source = src;
2028
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ":");
2029
+ uri.authority = uri.authority.replace("[", "").replace("]", "").replace(/;/g, ":");
2030
+ uri.ipv6uri = true;
2031
+ }
2032
+ uri.pathNames = pathNames(uri, uri["path"]);
2033
+ uri.queryKey = queryKey(uri, uri["query"]);
2034
+ return uri;
2035
+ }
2036
+ function pathNames(obj, path) {
2037
+ const regx = /\/{2,9}/g, names = path.replace(regx, "/").split("/");
2038
+ if (path.slice(0, 1) == "/" || path.length === 0) {
2039
+ names.splice(0, 1);
2040
+ }
2041
+ if (path.slice(-1) == "/") {
2042
+ names.splice(names.length - 1, 1);
2043
+ }
2044
+ return names;
2045
+ }
2046
+ function queryKey(uri, query) {
2047
+ const data = {};
2048
+ query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function($0, $1, $2) {
2049
+ if ($1) {
2050
+ data[$1] = $2;
2051
+ }
2052
+ });
2053
+ return data;
2054
+ }
2055
+
2056
+ // ../../node_modules/engine.io-client/build/esm/socket.js
2057
+ var withEventListeners = typeof addEventListener === "function" && typeof removeEventListener === "function";
2058
+ var OFFLINE_EVENT_LISTENERS = [];
2059
+ if (withEventListeners) {
2060
+ addEventListener("offline", () => {
2061
+ OFFLINE_EVENT_LISTENERS.forEach((listener) => listener());
2062
+ }, false);
2063
+ }
2064
+ var SocketWithoutUpgrade = class _SocketWithoutUpgrade extends Emitter {
2065
+ /**
2066
+ * Socket constructor.
2067
+ *
2068
+ * @param {String|Object} uri - uri or options
2069
+ * @param {Object} opts - options
2070
+ */
2071
+ constructor(uri, opts) {
2072
+ super();
2073
+ this.binaryType = defaultBinaryType;
2074
+ this.writeBuffer = [];
2075
+ this._prevBufferLen = 0;
2076
+ this._pingInterval = -1;
2077
+ this._pingTimeout = -1;
2078
+ this._maxPayload = -1;
2079
+ this._pingTimeoutTime = Infinity;
2080
+ if (uri && "object" === typeof uri) {
2081
+ opts = uri;
2082
+ uri = null;
2083
+ }
2084
+ if (uri) {
2085
+ const parsedUri = parse(uri);
2086
+ opts.hostname = parsedUri.host;
2087
+ opts.secure = parsedUri.protocol === "https" || parsedUri.protocol === "wss";
2088
+ opts.port = parsedUri.port;
2089
+ if (parsedUri.query)
2090
+ opts.query = parsedUri.query;
2091
+ } else if (opts.host) {
2092
+ opts.hostname = parse(opts.host).host;
2093
+ }
2094
+ installTimerFunctions(this, opts);
2095
+ this.secure = null != opts.secure ? opts.secure : typeof location !== "undefined" && "https:" === location.protocol;
2096
+ if (opts.hostname && !opts.port) {
2097
+ opts.port = this.secure ? "443" : "80";
2098
+ }
2099
+ this.hostname = opts.hostname || (typeof location !== "undefined" ? location.hostname : "localhost");
2100
+ this.port = opts.port || (typeof location !== "undefined" && location.port ? location.port : this.secure ? "443" : "80");
2101
+ this.transports = [];
2102
+ this._transportsByName = {};
2103
+ opts.transports.forEach((t) => {
2104
+ const transportName = t.prototype.name;
2105
+ this.transports.push(transportName);
2106
+ this._transportsByName[transportName] = t;
2107
+ });
2108
+ this.opts = Object.assign({
2109
+ path: "/engine.io",
2110
+ agent: false,
2111
+ withCredentials: false,
2112
+ upgrade: true,
2113
+ timestampParam: "t",
2114
+ rememberUpgrade: false,
2115
+ addTrailingSlash: true,
2116
+ rejectUnauthorized: true,
2117
+ perMessageDeflate: {
2118
+ threshold: 1024
2119
+ },
2120
+ transportOptions: {},
2121
+ closeOnBeforeunload: false
2122
+ }, opts);
2123
+ this.opts.path = this.opts.path.replace(/\/$/, "") + (this.opts.addTrailingSlash ? "/" : "");
2124
+ if (typeof this.opts.query === "string") {
2125
+ this.opts.query = decode2(this.opts.query);
2126
+ }
2127
+ if (withEventListeners) {
2128
+ if (this.opts.closeOnBeforeunload) {
2129
+ this._beforeunloadEventListener = () => {
2130
+ if (this.transport) {
2131
+ this.transport.removeAllListeners();
2132
+ this.transport.close();
2133
+ }
2134
+ };
2135
+ addEventListener("beforeunload", this._beforeunloadEventListener, false);
2136
+ }
2137
+ if (this.hostname !== "localhost") {
2138
+ this._offlineEventListener = () => {
2139
+ this._onClose("transport close", {
2140
+ description: "network connection lost"
2141
+ });
2142
+ };
2143
+ OFFLINE_EVENT_LISTENERS.push(this._offlineEventListener);
2144
+ }
2145
+ }
2146
+ if (this.opts.withCredentials) {
2147
+ this._cookieJar = createCookieJar();
2148
+ }
2149
+ this._open();
2150
+ }
2151
+ /**
2152
+ * Creates transport of the given type.
2153
+ *
2154
+ * @param {String} name - transport name
2155
+ * @return {Transport}
2156
+ * @private
2157
+ */
2158
+ createTransport(name) {
2159
+ const query = Object.assign({}, this.opts.query);
2160
+ query.EIO = protocol;
2161
+ query.transport = name;
2162
+ if (this.id)
2163
+ query.sid = this.id;
2164
+ const opts = Object.assign({}, this.opts, {
2165
+ query,
2166
+ socket: this,
2167
+ hostname: this.hostname,
2168
+ secure: this.secure,
2169
+ port: this.port
2170
+ }, this.opts.transportOptions[name]);
2171
+ return new this._transportsByName[name](opts);
2172
+ }
2173
+ /**
2174
+ * Initializes transport to use and starts probe.
2175
+ *
2176
+ * @private
2177
+ */
2178
+ _open() {
2179
+ if (this.transports.length === 0) {
2180
+ this.setTimeoutFn(() => {
2181
+ this.emitReserved("error", "No transports available");
2182
+ }, 0);
2183
+ return;
2184
+ }
2185
+ const transportName = this.opts.rememberUpgrade && _SocketWithoutUpgrade.priorWebsocketSuccess && this.transports.indexOf("websocket") !== -1 ? "websocket" : this.transports[0];
2186
+ this.readyState = "opening";
2187
+ const transport = this.createTransport(transportName);
2188
+ transport.open();
2189
+ this.setTransport(transport);
2190
+ }
2191
+ /**
2192
+ * Sets the current transport. Disables the existing one (if any).
2193
+ *
2194
+ * @private
2195
+ */
2196
+ setTransport(transport) {
2197
+ if (this.transport) {
2198
+ this.transport.removeAllListeners();
2199
+ }
2200
+ this.transport = transport;
2201
+ transport.on("drain", this._onDrain.bind(this)).on("packet", this._onPacket.bind(this)).on("error", this._onError.bind(this)).on("close", (reason) => this._onClose("transport close", reason));
2202
+ }
2203
+ /**
2204
+ * Called when connection is deemed open.
2205
+ *
2206
+ * @private
2207
+ */
2208
+ onOpen() {
2209
+ this.readyState = "open";
2210
+ _SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === this.transport.name;
2211
+ this.emitReserved("open");
2212
+ this.flush();
2213
+ }
2214
+ /**
2215
+ * Handles a packet.
2216
+ *
2217
+ * @private
2218
+ */
2219
+ _onPacket(packet) {
2220
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
2221
+ this.emitReserved("packet", packet);
2222
+ this.emitReserved("heartbeat");
2223
+ switch (packet.type) {
2224
+ case "open":
2225
+ this.onHandshake(JSON.parse(packet.data));
2226
+ break;
2227
+ case "ping":
2228
+ this._sendPacket("pong");
2229
+ this.emitReserved("ping");
2230
+ this.emitReserved("pong");
2231
+ this._resetPingTimeout();
2232
+ break;
2233
+ case "error":
2234
+ const err = new Error("server error");
2235
+ err.code = packet.data;
2236
+ this._onError(err);
2237
+ break;
2238
+ case "message":
2239
+ this.emitReserved("data", packet.data);
2240
+ this.emitReserved("message", packet.data);
2241
+ break;
2242
+ }
2243
+ } else {
2244
+ }
2245
+ }
2246
+ /**
2247
+ * Called upon handshake completion.
2248
+ *
2249
+ * @param {Object} data - handshake obj
2250
+ * @private
2251
+ */
2252
+ onHandshake(data) {
2253
+ this.emitReserved("handshake", data);
2254
+ this.id = data.sid;
2255
+ this.transport.query.sid = data.sid;
2256
+ this._pingInterval = data.pingInterval;
2257
+ this._pingTimeout = data.pingTimeout;
2258
+ this._maxPayload = data.maxPayload;
2259
+ this.onOpen();
2260
+ if ("closed" === this.readyState)
2261
+ return;
2262
+ this._resetPingTimeout();
2263
+ }
2264
+ /**
2265
+ * Sets and resets ping timeout timer based on server pings.
2266
+ *
2267
+ * @private
2268
+ */
2269
+ _resetPingTimeout() {
2270
+ this.clearTimeoutFn(this._pingTimeoutTimer);
2271
+ const delay = this._pingInterval + this._pingTimeout;
2272
+ this._pingTimeoutTime = Date.now() + delay;
2273
+ this._pingTimeoutTimer = this.setTimeoutFn(() => {
2274
+ this._onClose("ping timeout");
2275
+ }, delay);
2276
+ if (this.opts.autoUnref) {
2277
+ this._pingTimeoutTimer.unref();
2278
+ }
2279
+ }
2280
+ /**
2281
+ * Called on `drain` event
2282
+ *
2283
+ * @private
2284
+ */
2285
+ _onDrain() {
2286
+ this.writeBuffer.splice(0, this._prevBufferLen);
2287
+ this._prevBufferLen = 0;
2288
+ if (0 === this.writeBuffer.length) {
2289
+ this.emitReserved("drain");
2290
+ } else {
2291
+ this.flush();
2292
+ }
2293
+ }
2294
+ /**
2295
+ * Flush write buffers.
2296
+ *
2297
+ * @private
2298
+ */
2299
+ flush() {
2300
+ if ("closed" !== this.readyState && this.transport.writable && !this.upgrading && this.writeBuffer.length) {
2301
+ const packets = this._getWritablePackets();
2302
+ this.transport.send(packets);
2303
+ this._prevBufferLen = packets.length;
2304
+ this.emitReserved("flush");
2305
+ }
2306
+ }
2307
+ /**
2308
+ * Ensure the encoded size of the writeBuffer is below the maxPayload value sent by the server (only for HTTP
2309
+ * long-polling)
2310
+ *
2311
+ * @private
2312
+ */
2313
+ _getWritablePackets() {
2314
+ const shouldCheckPayloadSize = this._maxPayload && this.transport.name === "polling" && this.writeBuffer.length > 1;
2315
+ if (!shouldCheckPayloadSize) {
2316
+ return this.writeBuffer;
2317
+ }
2318
+ let payloadSize = 1;
2319
+ for (let i = 0; i < this.writeBuffer.length; i++) {
2320
+ const data = this.writeBuffer[i].data;
2321
+ if (data) {
2322
+ payloadSize += byteLength(data);
2323
+ }
2324
+ if (i > 0 && payloadSize > this._maxPayload) {
2325
+ return this.writeBuffer.slice(0, i);
2326
+ }
2327
+ payloadSize += 2;
2328
+ }
2329
+ return this.writeBuffer;
2330
+ }
2331
+ /**
2332
+ * Checks whether the heartbeat timer has expired but the socket has not yet been notified.
2333
+ *
2334
+ * Note: this method is private for now because it does not really fit the WebSocket API, but if we put it in the
2335
+ * `write()` method then the message would not be buffered by the Socket.IO client.
2336
+ *
2337
+ * @return {boolean}
2338
+ * @private
2339
+ */
2340
+ /* private */
2341
+ _hasPingExpired() {
2342
+ if (!this._pingTimeoutTime)
2343
+ return true;
2344
+ const hasExpired = Date.now() > this._pingTimeoutTime;
2345
+ if (hasExpired) {
2346
+ this._pingTimeoutTime = 0;
2347
+ nextTick(() => {
2348
+ this._onClose("ping timeout");
2349
+ }, this.setTimeoutFn);
2350
+ }
2351
+ return hasExpired;
2352
+ }
2353
+ /**
2354
+ * Sends a message.
2355
+ *
2356
+ * @param {String} msg - message.
2357
+ * @param {Object} options.
2358
+ * @param {Function} fn - callback function.
2359
+ * @return {Socket} for chaining.
2360
+ */
2361
+ write(msg, options, fn) {
2362
+ this._sendPacket("message", msg, options, fn);
2363
+ return this;
2364
+ }
2365
+ /**
2366
+ * Sends a message. Alias of {@link Socket#write}.
2367
+ *
2368
+ * @param {String} msg - message.
2369
+ * @param {Object} options.
2370
+ * @param {Function} fn - callback function.
2371
+ * @return {Socket} for chaining.
2372
+ */
2373
+ send(msg, options, fn) {
2374
+ this._sendPacket("message", msg, options, fn);
2375
+ return this;
2376
+ }
2377
+ /**
2378
+ * Sends a packet.
2379
+ *
2380
+ * @param {String} type - packet type.
2381
+ * @param {String} data.
2382
+ * @param {Object} options.
2383
+ * @param {Function} fn - callback function.
2384
+ * @private
2385
+ */
2386
+ _sendPacket(type, data, options, fn) {
2387
+ if ("function" === typeof data) {
2388
+ fn = data;
2389
+ data = void 0;
2390
+ }
2391
+ if ("function" === typeof options) {
2392
+ fn = options;
2393
+ options = null;
2394
+ }
2395
+ if ("closing" === this.readyState || "closed" === this.readyState) {
2396
+ return;
2397
+ }
2398
+ options = options || {};
2399
+ options.compress = false !== options.compress;
2400
+ const packet = {
2401
+ type,
2402
+ data,
2403
+ options
2404
+ };
2405
+ this.emitReserved("packetCreate", packet);
2406
+ this.writeBuffer.push(packet);
2407
+ if (fn)
2408
+ this.once("flush", fn);
2409
+ this.flush();
2410
+ }
2411
+ /**
2412
+ * Closes the connection.
2413
+ */
2414
+ close() {
2415
+ const close = () => {
2416
+ this._onClose("forced close");
2417
+ this.transport.close();
2418
+ };
2419
+ const cleanupAndClose = () => {
2420
+ this.off("upgrade", cleanupAndClose);
2421
+ this.off("upgradeError", cleanupAndClose);
2422
+ close();
2423
+ };
2424
+ const waitForUpgrade = () => {
2425
+ this.once("upgrade", cleanupAndClose);
2426
+ this.once("upgradeError", cleanupAndClose);
2427
+ };
2428
+ if ("opening" === this.readyState || "open" === this.readyState) {
2429
+ this.readyState = "closing";
2430
+ if (this.writeBuffer.length) {
2431
+ this.once("drain", () => {
2432
+ if (this.upgrading) {
2433
+ waitForUpgrade();
2434
+ } else {
2435
+ close();
2436
+ }
2437
+ });
2438
+ } else if (this.upgrading) {
2439
+ waitForUpgrade();
2440
+ } else {
2441
+ close();
2442
+ }
2443
+ }
2444
+ return this;
2445
+ }
2446
+ /**
2447
+ * Called upon transport error
2448
+ *
2449
+ * @private
2450
+ */
2451
+ _onError(err) {
2452
+ _SocketWithoutUpgrade.priorWebsocketSuccess = false;
2453
+ if (this.opts.tryAllTransports && this.transports.length > 1 && this.readyState === "opening") {
2454
+ this.transports.shift();
2455
+ return this._open();
2456
+ }
2457
+ this.emitReserved("error", err);
2458
+ this._onClose("transport error", err);
2459
+ }
2460
+ /**
2461
+ * Called upon transport close.
2462
+ *
2463
+ * @private
2464
+ */
2465
+ _onClose(reason, description) {
2466
+ if ("opening" === this.readyState || "open" === this.readyState || "closing" === this.readyState) {
2467
+ this.clearTimeoutFn(this._pingTimeoutTimer);
2468
+ this.transport.removeAllListeners("close");
2469
+ this.transport.close();
2470
+ this.transport.removeAllListeners();
2471
+ if (withEventListeners) {
2472
+ if (this._beforeunloadEventListener) {
2473
+ removeEventListener("beforeunload", this._beforeunloadEventListener, false);
2474
+ }
2475
+ if (this._offlineEventListener) {
2476
+ const i = OFFLINE_EVENT_LISTENERS.indexOf(this._offlineEventListener);
2477
+ if (i !== -1) {
2478
+ OFFLINE_EVENT_LISTENERS.splice(i, 1);
2479
+ }
2480
+ }
2481
+ }
2482
+ this.readyState = "closed";
2483
+ this.id = null;
2484
+ this.emitReserved("close", reason, description);
2485
+ this.writeBuffer = [];
2486
+ this._prevBufferLen = 0;
2487
+ }
2488
+ }
2489
+ };
2490
+ SocketWithoutUpgrade.protocol = protocol;
2491
+ var SocketWithUpgrade = class extends SocketWithoutUpgrade {
2492
+ constructor() {
2493
+ super(...arguments);
2494
+ this._upgrades = [];
2495
+ }
2496
+ onOpen() {
2497
+ super.onOpen();
2498
+ if ("open" === this.readyState && this.opts.upgrade) {
2499
+ for (let i = 0; i < this._upgrades.length; i++) {
2500
+ this._probe(this._upgrades[i]);
2501
+ }
2502
+ }
2503
+ }
2504
+ /**
2505
+ * Probes a transport.
2506
+ *
2507
+ * @param {String} name - transport name
2508
+ * @private
2509
+ */
2510
+ _probe(name) {
2511
+ let transport = this.createTransport(name);
2512
+ let failed = false;
2513
+ SocketWithoutUpgrade.priorWebsocketSuccess = false;
2514
+ const onTransportOpen = () => {
2515
+ if (failed)
2516
+ return;
2517
+ transport.send([{ type: "ping", data: "probe" }]);
2518
+ transport.once("packet", (msg) => {
2519
+ if (failed)
2520
+ return;
2521
+ if ("pong" === msg.type && "probe" === msg.data) {
2522
+ this.upgrading = true;
2523
+ this.emitReserved("upgrading", transport);
2524
+ if (!transport)
2525
+ return;
2526
+ SocketWithoutUpgrade.priorWebsocketSuccess = "websocket" === transport.name;
2527
+ this.transport.pause(() => {
2528
+ if (failed)
2529
+ return;
2530
+ if ("closed" === this.readyState)
2531
+ return;
2532
+ cleanup();
2533
+ this.setTransport(transport);
2534
+ transport.send([{ type: "upgrade" }]);
2535
+ this.emitReserved("upgrade", transport);
2536
+ transport = null;
2537
+ this.upgrading = false;
2538
+ this.flush();
2539
+ });
2540
+ } else {
2541
+ const err = new Error("probe error");
2542
+ err.transport = transport.name;
2543
+ this.emitReserved("upgradeError", err);
2544
+ }
2545
+ });
2546
+ };
2547
+ function freezeTransport() {
2548
+ if (failed)
2549
+ return;
2550
+ failed = true;
2551
+ cleanup();
2552
+ transport.close();
2553
+ transport = null;
2554
+ }
2555
+ const onerror = (err) => {
2556
+ const error = new Error("probe error: " + err);
2557
+ error.transport = transport.name;
2558
+ freezeTransport();
2559
+ this.emitReserved("upgradeError", error);
2560
+ };
2561
+ function onTransportClose() {
2562
+ onerror("transport closed");
2563
+ }
2564
+ function onclose() {
2565
+ onerror("socket closed");
2566
+ }
2567
+ function onupgrade(to) {
2568
+ if (transport && to.name !== transport.name) {
2569
+ freezeTransport();
2570
+ }
2571
+ }
2572
+ const cleanup = () => {
2573
+ transport.removeListener("open", onTransportOpen);
2574
+ transport.removeListener("error", onerror);
2575
+ transport.removeListener("close", onTransportClose);
2576
+ this.off("close", onclose);
2577
+ this.off("upgrading", onupgrade);
2578
+ };
2579
+ transport.once("open", onTransportOpen);
2580
+ transport.once("error", onerror);
2581
+ transport.once("close", onTransportClose);
2582
+ this.once("close", onclose);
2583
+ this.once("upgrading", onupgrade);
2584
+ if (this._upgrades.indexOf("webtransport") !== -1 && name !== "webtransport") {
2585
+ this.setTimeoutFn(() => {
2586
+ if (!failed) {
2587
+ transport.open();
2588
+ }
2589
+ }, 200);
2590
+ } else {
2591
+ transport.open();
2592
+ }
2593
+ }
2594
+ onHandshake(data) {
2595
+ this._upgrades = this._filterUpgrades(data.upgrades);
2596
+ super.onHandshake(data);
2597
+ }
2598
+ /**
2599
+ * Filters upgrades, returning only those matching client transports.
2600
+ *
2601
+ * @param {Array} upgrades - server upgrades
2602
+ * @private
2603
+ */
2604
+ _filterUpgrades(upgrades) {
2605
+ const filteredUpgrades = [];
2606
+ for (let i = 0; i < upgrades.length; i++) {
2607
+ if (~this.transports.indexOf(upgrades[i]))
2608
+ filteredUpgrades.push(upgrades[i]);
2609
+ }
2610
+ return filteredUpgrades;
2611
+ }
2612
+ };
2613
+ var Socket = class extends SocketWithUpgrade {
2614
+ constructor(uri, opts = {}) {
2615
+ const isOptionsOnly = typeof uri === "object";
2616
+ const o = isOptionsOnly ? { ...uri } : { ...opts };
2617
+ if (!o.transports || o.transports && typeof o.transports[0] === "string") {
2618
+ o.transports = (o.transports || ["polling", "websocket", "webtransport"]).map((transportName) => transports[transportName]).filter((t) => !!t);
2619
+ }
2620
+ super(isOptionsOnly ? o : uri, o);
2621
+ }
2622
+ };
2623
+
2624
+ // ../../node_modules/engine.io-client/build/esm/index.js
2625
+ var protocol2 = Socket.protocol;
2626
+
2627
+ // ../../node_modules/socket.io-client/build/esm/url.js
2628
+ function url(uri, path = "", loc) {
2629
+ let obj = uri;
2630
+ loc = loc || typeof location !== "undefined" && location;
2631
+ if (null == uri)
2632
+ uri = loc.protocol + "//" + loc.host;
2633
+ if (typeof uri === "string") {
2634
+ if ("/" === uri.charAt(0)) {
2635
+ if ("/" === uri.charAt(1)) {
2636
+ uri = loc.protocol + uri;
2637
+ } else {
2638
+ uri = loc.host + uri;
2639
+ }
2640
+ }
2641
+ if (!/^(https?|wss?):\/\//.test(uri)) {
2642
+ if ("undefined" !== typeof loc) {
2643
+ uri = loc.protocol + "//" + uri;
2644
+ } else {
2645
+ uri = "https://" + uri;
2646
+ }
2647
+ }
2648
+ obj = parse(uri);
2649
+ }
2650
+ if (!obj.port) {
2651
+ if (/^(http|ws)$/.test(obj.protocol)) {
2652
+ obj.port = "80";
2653
+ } else if (/^(http|ws)s$/.test(obj.protocol)) {
2654
+ obj.port = "443";
2655
+ }
2656
+ }
2657
+ obj.path = obj.path || "/";
2658
+ const ipv6 = obj.host.indexOf(":") !== -1;
2659
+ const host = ipv6 ? "[" + obj.host + "]" : obj.host;
2660
+ obj.id = obj.protocol + "://" + host + ":" + obj.port + path;
2661
+ obj.href = obj.protocol + "://" + host + (loc && loc.port === obj.port ? "" : ":" + obj.port);
2662
+ return obj;
2663
+ }
2664
+
2665
+ // ../../node_modules/socket.io-parser/build/esm/index.js
2666
+ var esm_exports = {};
2667
+ __export(esm_exports, {
2668
+ Decoder: () => Decoder,
2669
+ Encoder: () => Encoder,
2670
+ PacketType: () => PacketType,
2671
+ isPacketValid: () => isPacketValid,
2672
+ protocol: () => protocol3
2673
+ });
2674
+
2675
+ // ../../node_modules/socket.io-parser/build/esm/is-binary.js
2676
+ var withNativeArrayBuffer3 = typeof ArrayBuffer === "function";
2677
+ var isView2 = (obj) => {
2678
+ return typeof ArrayBuffer.isView === "function" ? ArrayBuffer.isView(obj) : obj.buffer instanceof ArrayBuffer;
2679
+ };
2680
+ var toString = Object.prototype.toString;
2681
+ var withNativeBlob2 = typeof Blob === "function" || typeof Blob !== "undefined" && toString.call(Blob) === "[object BlobConstructor]";
2682
+ var withNativeFile = typeof File === "function" || typeof File !== "undefined" && toString.call(File) === "[object FileConstructor]";
2683
+ function isBinary(obj) {
2684
+ return withNativeArrayBuffer3 && (obj instanceof ArrayBuffer || isView2(obj)) || withNativeBlob2 && obj instanceof Blob || withNativeFile && obj instanceof File;
2685
+ }
2686
+ function hasBinary(obj, toJSON) {
2687
+ if (!obj || typeof obj !== "object") {
2688
+ return false;
2689
+ }
2690
+ if (Array.isArray(obj)) {
2691
+ for (let i = 0, l = obj.length; i < l; i++) {
2692
+ if (hasBinary(obj[i])) {
2693
+ return true;
2694
+ }
2695
+ }
2696
+ return false;
2697
+ }
2698
+ if (isBinary(obj)) {
2699
+ return true;
2700
+ }
2701
+ if (obj.toJSON && typeof obj.toJSON === "function" && arguments.length === 1) {
2702
+ return hasBinary(obj.toJSON(), true);
2703
+ }
2704
+ for (const key in obj) {
2705
+ if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
2706
+ return true;
2707
+ }
2708
+ }
2709
+ return false;
2710
+ }
2711
+
2712
+ // ../../node_modules/socket.io-parser/build/esm/binary.js
2713
+ function deconstructPacket(packet) {
2714
+ const buffers = [];
2715
+ const packetData = packet.data;
2716
+ const pack = packet;
2717
+ pack.data = _deconstructPacket(packetData, buffers);
2718
+ pack.attachments = buffers.length;
2719
+ return { packet: pack, buffers };
2720
+ }
2721
+ function _deconstructPacket(data, buffers, toJSON) {
2722
+ if (!data)
2723
+ return data;
2724
+ if (isBinary(data)) {
2725
+ const placeholder = { _placeholder: true, num: buffers.length };
2726
+ buffers.push(data);
2727
+ return placeholder;
2728
+ } else if (Array.isArray(data)) {
2729
+ const newData = new Array(data.length);
2730
+ for (let i = 0; i < data.length; i++) {
2731
+ newData[i] = _deconstructPacket(data[i], buffers);
2732
+ }
2733
+ return newData;
2734
+ } else if (typeof data === "object" && !(data instanceof Date)) {
2735
+ if (data.toJSON && typeof data.toJSON === "function" && !toJSON) {
2736
+ return _deconstructPacket(data.toJSON(), buffers, true);
2737
+ }
2738
+ const newData = {};
2739
+ for (const key in data) {
2740
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
2741
+ newData[key] = _deconstructPacket(data[key], buffers);
2742
+ }
2743
+ }
2744
+ return newData;
2745
+ }
2746
+ return data;
2747
+ }
2748
+ function reconstructPacket(packet, buffers) {
2749
+ packet.data = _reconstructPacket(packet.data, buffers);
2750
+ delete packet.attachments;
2751
+ return packet;
2752
+ }
2753
+ function _reconstructPacket(data, buffers) {
2754
+ if (!data)
2755
+ return data;
2756
+ if (data && data._placeholder === true) {
2757
+ const isIndexValid = typeof data.num === "number" && data.num >= 0 && data.num < buffers.length;
2758
+ if (isIndexValid) {
2759
+ return buffers[data.num];
2760
+ } else {
2761
+ throw new Error("illegal attachments");
2762
+ }
2763
+ } else if (Array.isArray(data)) {
2764
+ for (let i = 0; i < data.length; i++) {
2765
+ data[i] = _reconstructPacket(data[i], buffers);
2766
+ }
2767
+ } else if (typeof data === "object") {
2768
+ for (const key in data) {
2769
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
2770
+ data[key] = _reconstructPacket(data[key], buffers);
2771
+ }
2772
+ }
2773
+ }
2774
+ return data;
2775
+ }
2776
+
2777
+ // ../../node_modules/socket.io-parser/build/esm/index.js
2778
+ var RESERVED_EVENTS = [
2779
+ "connect",
2780
+ // used on the client side
2781
+ "connect_error",
2782
+ // used on the client side
2783
+ "disconnect",
2784
+ // used on both sides
2785
+ "disconnecting",
2786
+ // used on the server side
2787
+ "newListener",
2788
+ // used by the Node.js EventEmitter
2789
+ "removeListener"
2790
+ // used by the Node.js EventEmitter
2791
+ ];
2792
+ var protocol3 = 5;
2793
+ var PacketType;
2794
+ (function(PacketType2) {
2795
+ PacketType2[PacketType2["CONNECT"] = 0] = "CONNECT";
2796
+ PacketType2[PacketType2["DISCONNECT"] = 1] = "DISCONNECT";
2797
+ PacketType2[PacketType2["EVENT"] = 2] = "EVENT";
2798
+ PacketType2[PacketType2["ACK"] = 3] = "ACK";
2799
+ PacketType2[PacketType2["CONNECT_ERROR"] = 4] = "CONNECT_ERROR";
2800
+ PacketType2[PacketType2["BINARY_EVENT"] = 5] = "BINARY_EVENT";
2801
+ PacketType2[PacketType2["BINARY_ACK"] = 6] = "BINARY_ACK";
2802
+ })(PacketType || (PacketType = {}));
2803
+ var Encoder = class {
2804
+ /**
2805
+ * Encoder constructor
2806
+ *
2807
+ * @param {function} replacer - custom replacer to pass down to JSON.parse
2808
+ */
2809
+ constructor(replacer) {
2810
+ this.replacer = replacer;
2811
+ }
2812
+ /**
2813
+ * Encode a packet as a single string if non-binary, or as a
2814
+ * buffer sequence, depending on packet type.
2815
+ *
2816
+ * @param {Object} obj - packet object
2817
+ */
2818
+ encode(obj) {
2819
+ if (obj.type === PacketType.EVENT || obj.type === PacketType.ACK) {
2820
+ if (hasBinary(obj)) {
2821
+ return this.encodeAsBinary({
2822
+ type: obj.type === PacketType.EVENT ? PacketType.BINARY_EVENT : PacketType.BINARY_ACK,
2823
+ nsp: obj.nsp,
2824
+ data: obj.data,
2825
+ id: obj.id
2826
+ });
2827
+ }
2828
+ }
2829
+ return [this.encodeAsString(obj)];
2830
+ }
2831
+ /**
2832
+ * Encode packet as string.
2833
+ */
2834
+ encodeAsString(obj) {
2835
+ let str = "" + obj.type;
2836
+ if (obj.type === PacketType.BINARY_EVENT || obj.type === PacketType.BINARY_ACK) {
2837
+ str += obj.attachments + "-";
2838
+ }
2839
+ if (obj.nsp && "/" !== obj.nsp) {
2840
+ str += obj.nsp + ",";
2841
+ }
2842
+ if (null != obj.id) {
2843
+ str += obj.id;
2844
+ }
2845
+ if (null != obj.data) {
2846
+ str += JSON.stringify(obj.data, this.replacer);
2847
+ }
2848
+ return str;
2849
+ }
2850
+ /**
2851
+ * Encode packet as 'buffer sequence' by removing blobs, and
2852
+ * deconstructing packet into object with placeholders and
2853
+ * a list of buffers.
2854
+ */
2855
+ encodeAsBinary(obj) {
2856
+ const deconstruction = deconstructPacket(obj);
2857
+ const pack = this.encodeAsString(deconstruction.packet);
2858
+ const buffers = deconstruction.buffers;
2859
+ buffers.unshift(pack);
2860
+ return buffers;
2861
+ }
2862
+ };
2863
+ var Decoder = class _Decoder extends Emitter {
2864
+ /**
2865
+ * Decoder constructor
2866
+ */
2867
+ constructor(opts) {
2868
+ super();
2869
+ this.opts = Object.assign({
2870
+ reviver: void 0,
2871
+ maxAttachments: 10
2872
+ }, typeof opts === "function" ? { reviver: opts } : opts);
2873
+ }
2874
+ /**
2875
+ * Decodes an encoded packet string into packet JSON.
2876
+ *
2877
+ * @param {String} obj - encoded packet
2878
+ */
2879
+ add(obj) {
2880
+ let packet;
2881
+ if (typeof obj === "string") {
2882
+ if (this.reconstructor) {
2883
+ throw new Error("got plaintext data when reconstructing a packet");
2884
+ }
2885
+ packet = this.decodeString(obj);
2886
+ const isBinaryEvent = packet.type === PacketType.BINARY_EVENT;
2887
+ if (isBinaryEvent || packet.type === PacketType.BINARY_ACK) {
2888
+ packet.type = isBinaryEvent ? PacketType.EVENT : PacketType.ACK;
2889
+ this.reconstructor = new BinaryReconstructor(packet);
2890
+ } else {
2891
+ super.emitReserved("decoded", packet);
2892
+ }
2893
+ } else if (isBinary(obj) || obj.base64) {
2894
+ if (!this.reconstructor) {
2895
+ throw new Error("got binary data when not reconstructing a packet");
2896
+ } else {
2897
+ packet = this.reconstructor.takeBinaryData(obj);
2898
+ if (packet) {
2899
+ this.reconstructor = null;
2900
+ super.emitReserved("decoded", packet);
2901
+ }
2902
+ }
2903
+ } else {
2904
+ throw new Error("Unknown type: " + obj);
2905
+ }
2906
+ }
2907
+ /**
2908
+ * Decode a packet String (JSON data)
2909
+ *
2910
+ * @param {String} str
2911
+ * @return {Object} packet
2912
+ */
2913
+ decodeString(str) {
2914
+ let i = 0;
2915
+ const p = {
2916
+ type: Number(str.charAt(0))
2917
+ };
2918
+ if (PacketType[p.type] === void 0) {
2919
+ throw new Error("unknown packet type " + p.type);
2920
+ }
2921
+ if (p.type === PacketType.BINARY_EVENT || p.type === PacketType.BINARY_ACK) {
2922
+ const start = i + 1;
2923
+ while (str.charAt(++i) !== "-" && i != str.length) {
2924
+ }
2925
+ const buf = str.substring(start, i);
2926
+ if (buf != Number(buf) || str.charAt(i) !== "-") {
2927
+ throw new Error("Illegal attachments");
2928
+ }
2929
+ const n = Number(buf);
2930
+ if (!isInteger(n) || n < 1) {
2931
+ throw new Error("Illegal attachments");
2932
+ } else if (n > this.opts.maxAttachments) {
2933
+ throw new Error("too many attachments");
2934
+ }
2935
+ p.attachments = n;
2936
+ }
2937
+ if ("/" === str.charAt(i + 1)) {
2938
+ const start = i + 1;
2939
+ while (++i) {
2940
+ const c = str.charAt(i);
2941
+ if ("," === c)
2942
+ break;
2943
+ if (i === str.length)
2944
+ break;
2945
+ }
2946
+ p.nsp = str.substring(start, i);
2947
+ } else {
2948
+ p.nsp = "/";
2949
+ }
2950
+ const next = str.charAt(i + 1);
2951
+ if ("" !== next && Number(next) == next) {
2952
+ const start = i + 1;
2953
+ while (++i) {
2954
+ const c = str.charAt(i);
2955
+ if (null == c || Number(c) != c) {
2956
+ --i;
2957
+ break;
2958
+ }
2959
+ if (i === str.length)
2960
+ break;
2961
+ }
2962
+ p.id = Number(str.substring(start, i + 1));
2963
+ }
2964
+ if (str.charAt(++i)) {
2965
+ const payload = this.tryParse(str.substr(i));
2966
+ if (_Decoder.isPayloadValid(p.type, payload)) {
2967
+ p.data = payload;
2968
+ } else {
2969
+ throw new Error("invalid payload");
2970
+ }
2971
+ }
2972
+ return p;
2973
+ }
2974
+ tryParse(str) {
2975
+ try {
2976
+ return JSON.parse(str, this.opts.reviver);
2977
+ } catch (e) {
2978
+ return false;
2979
+ }
2980
+ }
2981
+ static isPayloadValid(type, payload) {
2982
+ switch (type) {
2983
+ case PacketType.CONNECT:
2984
+ return isObject(payload);
2985
+ case PacketType.DISCONNECT:
2986
+ return payload === void 0;
2987
+ case PacketType.CONNECT_ERROR:
2988
+ return typeof payload === "string" || isObject(payload);
2989
+ case PacketType.EVENT:
2990
+ case PacketType.BINARY_EVENT:
2991
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
2992
+ case PacketType.ACK:
2993
+ case PacketType.BINARY_ACK:
2994
+ return Array.isArray(payload);
2995
+ }
2996
+ }
2997
+ /**
2998
+ * Deallocates a parser's resources
2999
+ */
3000
+ destroy() {
3001
+ if (this.reconstructor) {
3002
+ this.reconstructor.finishedReconstruction();
3003
+ this.reconstructor = null;
3004
+ }
3005
+ }
3006
+ };
3007
+ var BinaryReconstructor = class {
3008
+ constructor(packet) {
3009
+ this.packet = packet;
3010
+ this.buffers = [];
3011
+ this.reconPack = packet;
3012
+ }
3013
+ /**
3014
+ * Method to be called when binary data received from connection
3015
+ * after a BINARY_EVENT packet.
3016
+ *
3017
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
3018
+ * @return {null | Object} returns null if more binary data is expected or
3019
+ * a reconstructed packet object if all buffers have been received.
3020
+ */
3021
+ takeBinaryData(binData) {
3022
+ this.buffers.push(binData);
3023
+ if (this.buffers.length === this.reconPack.attachments) {
3024
+ const packet = reconstructPacket(this.reconPack, this.buffers);
3025
+ this.finishedReconstruction();
3026
+ return packet;
3027
+ }
3028
+ return null;
3029
+ }
3030
+ /**
3031
+ * Cleans up binary packet reconstruction variables.
3032
+ */
3033
+ finishedReconstruction() {
3034
+ this.reconPack = null;
3035
+ this.buffers = [];
3036
+ }
3037
+ };
3038
+ function isNamespaceValid(nsp) {
3039
+ return typeof nsp === "string";
3040
+ }
3041
+ var isInteger = Number.isInteger || function(value2) {
3042
+ return typeof value2 === "number" && isFinite(value2) && Math.floor(value2) === value2;
3043
+ };
3044
+ function isAckIdValid(id) {
3045
+ return id === void 0 || isInteger(id);
3046
+ }
3047
+ function isObject(value2) {
3048
+ return Object.prototype.toString.call(value2) === "[object Object]";
3049
+ }
3050
+ function isDataValid(type, payload) {
3051
+ switch (type) {
3052
+ case PacketType.CONNECT:
3053
+ return payload === void 0 || isObject(payload);
3054
+ case PacketType.DISCONNECT:
3055
+ return payload === void 0;
3056
+ case PacketType.EVENT:
3057
+ return Array.isArray(payload) && (typeof payload[0] === "number" || typeof payload[0] === "string" && RESERVED_EVENTS.indexOf(payload[0]) === -1);
3058
+ case PacketType.ACK:
3059
+ return Array.isArray(payload);
3060
+ case PacketType.CONNECT_ERROR:
3061
+ return typeof payload === "string" || isObject(payload);
3062
+ default:
3063
+ return false;
3064
+ }
3065
+ }
3066
+ function isPacketValid(packet) {
3067
+ return isNamespaceValid(packet.nsp) && isAckIdValid(packet.id) && isDataValid(packet.type, packet.data);
3068
+ }
3069
+
3070
+ // ../../node_modules/socket.io-client/build/esm/on.js
3071
+ function on(obj, ev, fn) {
3072
+ obj.on(ev, fn);
3073
+ return function subDestroy() {
3074
+ obj.off(ev, fn);
3075
+ };
3076
+ }
3077
+
3078
+ // ../../node_modules/socket.io-client/build/esm/socket.js
3079
+ var RESERVED_EVENTS2 = Object.freeze({
3080
+ connect: 1,
3081
+ connect_error: 1,
3082
+ disconnect: 1,
3083
+ disconnecting: 1,
3084
+ // EventEmitter reserved events: https://nodejs.org/api/events.html#events_event_newlistener
3085
+ newListener: 1,
3086
+ removeListener: 1
3087
+ });
3088
+ var Socket2 = class extends Emitter {
3089
+ /**
3090
+ * `Socket` constructor.
3091
+ */
3092
+ constructor(io, nsp, opts) {
3093
+ super();
3094
+ this.connected = false;
3095
+ this.recovered = false;
3096
+ this.receiveBuffer = [];
3097
+ this.sendBuffer = [];
3098
+ this._queue = [];
3099
+ this._queueSeq = 0;
3100
+ this.ids = 0;
3101
+ this.acks = {};
3102
+ this.flags = {};
3103
+ this.io = io;
3104
+ this.nsp = nsp;
3105
+ if (opts && opts.auth) {
3106
+ this.auth = opts.auth;
3107
+ }
3108
+ this._opts = Object.assign({}, opts);
3109
+ if (this.io._autoConnect)
3110
+ this.open();
3111
+ }
3112
+ /**
3113
+ * Whether the socket is currently disconnected
3114
+ *
3115
+ * @example
3116
+ * const socket = io();
3117
+ *
3118
+ * socket.on("connect", () => {
3119
+ * console.log(socket.disconnected); // false
3120
+ * });
3121
+ *
3122
+ * socket.on("disconnect", () => {
3123
+ * console.log(socket.disconnected); // true
3124
+ * });
3125
+ */
3126
+ get disconnected() {
3127
+ return !this.connected;
3128
+ }
3129
+ /**
3130
+ * Subscribe to open, close and packet events
3131
+ *
3132
+ * @private
3133
+ */
3134
+ subEvents() {
3135
+ if (this.subs)
3136
+ return;
3137
+ const io = this.io;
3138
+ this.subs = [
3139
+ on(io, "open", this.onopen.bind(this)),
3140
+ on(io, "packet", this.onpacket.bind(this)),
3141
+ on(io, "error", this.onerror.bind(this)),
3142
+ on(io, "close", this.onclose.bind(this))
3143
+ ];
3144
+ }
3145
+ /**
3146
+ * Whether the Socket will try to reconnect when its Manager connects or reconnects.
3147
+ *
3148
+ * @example
3149
+ * const socket = io();
3150
+ *
3151
+ * console.log(socket.active); // true
3152
+ *
3153
+ * socket.on("disconnect", (reason) => {
3154
+ * if (reason === "io server disconnect") {
3155
+ * // the disconnection was initiated by the server, you need to manually reconnect
3156
+ * console.log(socket.active); // false
3157
+ * }
3158
+ * // else the socket will automatically try to reconnect
3159
+ * console.log(socket.active); // true
3160
+ * });
3161
+ */
3162
+ get active() {
3163
+ return !!this.subs;
3164
+ }
3165
+ /**
3166
+ * "Opens" the socket.
3167
+ *
3168
+ * @example
3169
+ * const socket = io({
3170
+ * autoConnect: false
3171
+ * });
3172
+ *
3173
+ * socket.connect();
3174
+ */
3175
+ connect() {
3176
+ if (this.connected)
3177
+ return this;
3178
+ this.subEvents();
3179
+ if (!this.io["_reconnecting"])
3180
+ this.io.open();
3181
+ if ("open" === this.io._readyState)
3182
+ this.onopen();
3183
+ return this;
3184
+ }
3185
+ /**
3186
+ * Alias for {@link connect()}.
3187
+ */
3188
+ open() {
3189
+ return this.connect();
3190
+ }
3191
+ /**
3192
+ * Sends a `message` event.
3193
+ *
3194
+ * This method mimics the WebSocket.send() method.
3195
+ *
3196
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/send
3197
+ *
3198
+ * @example
3199
+ * socket.send("hello");
3200
+ *
3201
+ * // this is equivalent to
3202
+ * socket.emit("message", "hello");
3203
+ *
3204
+ * @return self
3205
+ */
3206
+ send(...args) {
3207
+ args.unshift("message");
3208
+ this.emit.apply(this, args);
3209
+ return this;
3210
+ }
3211
+ /**
3212
+ * Override `emit`.
3213
+ * If the event is in `events`, it's emitted normally.
3214
+ *
3215
+ * @example
3216
+ * socket.emit("hello", "world");
3217
+ *
3218
+ * // all serializable datastructures are supported (no need to call JSON.stringify)
3219
+ * socket.emit("hello", 1, "2", { 3: ["4"], 5: Uint8Array.from([6]) });
3220
+ *
3221
+ * // with an acknowledgement from the server
3222
+ * socket.emit("hello", "world", (val) => {
3223
+ * // ...
3224
+ * });
3225
+ *
3226
+ * @return self
3227
+ */
3228
+ emit(ev, ...args) {
3229
+ var _a, _b, _c;
3230
+ if (RESERVED_EVENTS2.hasOwnProperty(ev)) {
3231
+ throw new Error('"' + ev.toString() + '" is a reserved event name');
3232
+ }
3233
+ args.unshift(ev);
3234
+ if (this._opts.retries && !this.flags.fromQueue && !this.flags.volatile) {
3235
+ this._addToQueue(args);
3236
+ return this;
3237
+ }
3238
+ const packet = {
3239
+ type: PacketType.EVENT,
3240
+ data: args
3241
+ };
3242
+ packet.options = {};
3243
+ packet.options.compress = this.flags.compress !== false;
3244
+ if ("function" === typeof args[args.length - 1]) {
3245
+ const id = this.ids++;
3246
+ const ack = args.pop();
3247
+ this._registerAckCallback(id, ack);
3248
+ packet.id = id;
3249
+ }
3250
+ const isTransportWritable = (_b = (_a = this.io.engine) === null || _a === void 0 ? void 0 : _a.transport) === null || _b === void 0 ? void 0 : _b.writable;
3251
+ const isConnected = this.connected && !((_c = this.io.engine) === null || _c === void 0 ? void 0 : _c._hasPingExpired());
3252
+ const discardPacket = this.flags.volatile && !isTransportWritable;
3253
+ if (discardPacket) {
3254
+ } else if (isConnected) {
3255
+ this.notifyOutgoingListeners(packet);
3256
+ this.packet(packet);
3257
+ } else {
3258
+ this.sendBuffer.push(packet);
3259
+ }
3260
+ this.flags = {};
3261
+ return this;
3262
+ }
3263
+ /**
3264
+ * @private
3265
+ */
3266
+ _registerAckCallback(id, ack) {
3267
+ var _a;
3268
+ const timeout = (_a = this.flags.timeout) !== null && _a !== void 0 ? _a : this._opts.ackTimeout;
3269
+ if (timeout === void 0) {
3270
+ this.acks[id] = ack;
3271
+ return;
3272
+ }
3273
+ const timer = this.io.setTimeoutFn(() => {
3274
+ delete this.acks[id];
3275
+ for (let i = 0; i < this.sendBuffer.length; i++) {
3276
+ if (this.sendBuffer[i].id === id) {
3277
+ this.sendBuffer.splice(i, 1);
3278
+ }
3279
+ }
3280
+ ack.call(this, new Error("operation has timed out"));
3281
+ }, timeout);
3282
+ const fn = (...args) => {
3283
+ this.io.clearTimeoutFn(timer);
3284
+ ack.apply(this, args);
3285
+ };
3286
+ fn.withError = true;
3287
+ this.acks[id] = fn;
3288
+ }
3289
+ /**
3290
+ * Emits an event and waits for an acknowledgement
3291
+ *
3292
+ * @example
3293
+ * // without timeout
3294
+ * const response = await socket.emitWithAck("hello", "world");
3295
+ *
3296
+ * // with a specific timeout
3297
+ * try {
3298
+ * const response = await socket.timeout(1000).emitWithAck("hello", "world");
3299
+ * } catch (err) {
3300
+ * // the server did not acknowledge the event in the given delay
3301
+ * }
3302
+ *
3303
+ * @return a Promise that will be fulfilled when the server acknowledges the event
3304
+ */
3305
+ emitWithAck(ev, ...args) {
3306
+ return new Promise((resolve, reject) => {
3307
+ const fn = (arg1, arg2) => {
3308
+ return arg1 ? reject(arg1) : resolve(arg2);
3309
+ };
3310
+ fn.withError = true;
3311
+ args.push(fn);
3312
+ this.emit(ev, ...args);
3313
+ });
3314
+ }
3315
+ /**
3316
+ * Add the packet to the queue.
3317
+ * @param args
3318
+ * @private
3319
+ */
3320
+ _addToQueue(args) {
3321
+ let ack;
3322
+ if (typeof args[args.length - 1] === "function") {
3323
+ ack = args.pop();
3324
+ }
3325
+ const packet = {
3326
+ id: this._queueSeq++,
3327
+ tryCount: 0,
3328
+ pending: false,
3329
+ args,
3330
+ flags: Object.assign({ fromQueue: true }, this.flags)
3331
+ };
3332
+ args.push((err, ...responseArgs) => {
3333
+ if (packet !== this._queue[0]) {
3334
+ }
3335
+ const hasError = err !== null;
3336
+ if (hasError) {
3337
+ if (packet.tryCount > this._opts.retries) {
3338
+ this._queue.shift();
3339
+ if (ack) {
3340
+ ack(err);
3341
+ }
3342
+ }
3343
+ } else {
3344
+ this._queue.shift();
3345
+ if (ack) {
3346
+ ack(null, ...responseArgs);
3347
+ }
3348
+ }
3349
+ packet.pending = false;
3350
+ return this._drainQueue();
3351
+ });
3352
+ this._queue.push(packet);
3353
+ this._drainQueue();
3354
+ }
3355
+ /**
3356
+ * Send the first packet of the queue, and wait for an acknowledgement from the server.
3357
+ * @param force - whether to resend a packet that has not been acknowledged yet
3358
+ *
3359
+ * @private
3360
+ */
3361
+ _drainQueue(force = false) {
3362
+ if (!this.connected || this._queue.length === 0) {
3363
+ return;
3364
+ }
3365
+ const packet = this._queue[0];
3366
+ if (packet.pending && !force) {
3367
+ return;
3368
+ }
3369
+ packet.pending = true;
3370
+ packet.tryCount++;
3371
+ this.flags = packet.flags;
3372
+ this.emit.apply(this, packet.args);
3373
+ }
3374
+ /**
3375
+ * Sends a packet.
3376
+ *
3377
+ * @param packet
3378
+ * @private
3379
+ */
3380
+ packet(packet) {
3381
+ packet.nsp = this.nsp;
3382
+ this.io._packet(packet);
3383
+ }
3384
+ /**
3385
+ * Called upon engine `open`.
3386
+ *
3387
+ * @private
3388
+ */
3389
+ onopen() {
3390
+ if (typeof this.auth == "function") {
3391
+ this.auth((data) => {
3392
+ this._sendConnectPacket(data);
3393
+ });
3394
+ } else {
3395
+ this._sendConnectPacket(this.auth);
3396
+ }
3397
+ }
3398
+ /**
3399
+ * Sends a CONNECT packet to initiate the Socket.IO session.
3400
+ *
3401
+ * @param data
3402
+ * @private
3403
+ */
3404
+ _sendConnectPacket(data) {
3405
+ this.packet({
3406
+ type: PacketType.CONNECT,
3407
+ data: this._pid ? Object.assign({ pid: this._pid, offset: this._lastOffset }, data) : data
3408
+ });
3409
+ }
3410
+ /**
3411
+ * Called upon engine or manager `error`.
3412
+ *
3413
+ * @param err
3414
+ * @private
3415
+ */
3416
+ onerror(err) {
3417
+ if (!this.connected) {
3418
+ this.emitReserved("connect_error", err);
3419
+ }
3420
+ }
3421
+ /**
3422
+ * Called upon engine `close`.
3423
+ *
3424
+ * @param reason
3425
+ * @param description
3426
+ * @private
3427
+ */
3428
+ onclose(reason, description) {
3429
+ this.connected = false;
3430
+ delete this.id;
3431
+ this.emitReserved("disconnect", reason, description);
3432
+ this._clearAcks();
3433
+ }
3434
+ /**
3435
+ * Clears the acknowledgement handlers upon disconnection, since the client will never receive an acknowledgement from
3436
+ * the server.
3437
+ *
3438
+ * @private
3439
+ */
3440
+ _clearAcks() {
3441
+ Object.keys(this.acks).forEach((id) => {
3442
+ const isBuffered = this.sendBuffer.some((packet) => String(packet.id) === id);
3443
+ if (!isBuffered) {
3444
+ const ack = this.acks[id];
3445
+ delete this.acks[id];
3446
+ if (ack.withError) {
3447
+ ack.call(this, new Error("socket has been disconnected"));
3448
+ }
3449
+ }
3450
+ });
3451
+ }
3452
+ /**
3453
+ * Called with socket packet.
3454
+ *
3455
+ * @param packet
3456
+ * @private
3457
+ */
3458
+ onpacket(packet) {
3459
+ const sameNamespace = packet.nsp === this.nsp;
3460
+ if (!sameNamespace)
3461
+ return;
3462
+ switch (packet.type) {
3463
+ case PacketType.CONNECT:
3464
+ if (packet.data && packet.data.sid) {
3465
+ this.onconnect(packet.data.sid, packet.data.pid);
3466
+ } else {
3467
+ this.emitReserved("connect_error", new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));
3468
+ }
3469
+ break;
3470
+ case PacketType.EVENT:
3471
+ case PacketType.BINARY_EVENT:
3472
+ this.onevent(packet);
3473
+ break;
3474
+ case PacketType.ACK:
3475
+ case PacketType.BINARY_ACK:
3476
+ this.onack(packet);
3477
+ break;
3478
+ case PacketType.DISCONNECT:
3479
+ this.ondisconnect();
3480
+ break;
3481
+ case PacketType.CONNECT_ERROR:
3482
+ this.destroy();
3483
+ const err = new Error(packet.data.message);
3484
+ err.data = packet.data.data;
3485
+ this.emitReserved("connect_error", err);
3486
+ break;
3487
+ }
3488
+ }
3489
+ /**
3490
+ * Called upon a server event.
3491
+ *
3492
+ * @param packet
3493
+ * @private
3494
+ */
3495
+ onevent(packet) {
3496
+ const args = packet.data || [];
3497
+ if (null != packet.id) {
3498
+ args.push(this.ack(packet.id));
3499
+ }
3500
+ if (this.connected) {
3501
+ this.emitEvent(args);
3502
+ } else {
3503
+ this.receiveBuffer.push(Object.freeze(args));
3504
+ }
3505
+ }
3506
+ emitEvent(args) {
3507
+ if (this._anyListeners && this._anyListeners.length) {
3508
+ const listeners = this._anyListeners.slice();
3509
+ for (const listener of listeners) {
3510
+ listener.apply(this, args);
3511
+ }
3512
+ }
3513
+ super.emit.apply(this, args);
3514
+ if (this._pid && args.length && typeof args[args.length - 1] === "string") {
3515
+ this._lastOffset = args[args.length - 1];
3516
+ }
3517
+ }
3518
+ /**
3519
+ * Produces an ack callback to emit with an event.
3520
+ *
3521
+ * @private
3522
+ */
3523
+ ack(id) {
3524
+ const self2 = this;
3525
+ let sent = false;
3526
+ return function(...args) {
3527
+ if (sent)
3528
+ return;
3529
+ sent = true;
3530
+ self2.packet({
3531
+ type: PacketType.ACK,
3532
+ id,
3533
+ data: args
3534
+ });
3535
+ };
3536
+ }
3537
+ /**
3538
+ * Called upon a server acknowledgement.
3539
+ *
3540
+ * @param packet
3541
+ * @private
3542
+ */
3543
+ onack(packet) {
3544
+ const ack = this.acks[packet.id];
3545
+ if (typeof ack !== "function") {
3546
+ return;
3547
+ }
3548
+ delete this.acks[packet.id];
3549
+ if (ack.withError) {
3550
+ packet.data.unshift(null);
3551
+ }
3552
+ ack.apply(this, packet.data);
3553
+ }
3554
+ /**
3555
+ * Called upon server connect.
3556
+ *
3557
+ * @private
3558
+ */
3559
+ onconnect(id, pid) {
3560
+ this.id = id;
3561
+ this.recovered = pid && this._pid === pid;
3562
+ this._pid = pid;
3563
+ this.connected = true;
3564
+ this.emitBuffered();
3565
+ this._drainQueue(true);
3566
+ this.emitReserved("connect");
3567
+ }
3568
+ /**
3569
+ * Emit buffered events (received and emitted).
3570
+ *
3571
+ * @private
3572
+ */
3573
+ emitBuffered() {
3574
+ this.receiveBuffer.forEach((args) => this.emitEvent(args));
3575
+ this.receiveBuffer = [];
3576
+ this.sendBuffer.forEach((packet) => {
3577
+ this.notifyOutgoingListeners(packet);
3578
+ this.packet(packet);
3579
+ });
3580
+ this.sendBuffer = [];
3581
+ }
3582
+ /**
3583
+ * Called upon server disconnect.
3584
+ *
3585
+ * @private
3586
+ */
3587
+ ondisconnect() {
3588
+ this.destroy();
3589
+ this.onclose("io server disconnect");
3590
+ }
3591
+ /**
3592
+ * Called upon forced client/server side disconnections,
3593
+ * this method ensures the manager stops tracking us and
3594
+ * that reconnections don't get triggered for this.
3595
+ *
3596
+ * @private
3597
+ */
3598
+ destroy() {
3599
+ if (this.subs) {
3600
+ this.subs.forEach((subDestroy) => subDestroy());
3601
+ this.subs = void 0;
3602
+ }
3603
+ this.io["_destroy"](this);
3604
+ }
3605
+ /**
3606
+ * Disconnects the socket manually. In that case, the socket will not try to reconnect.
3607
+ *
3608
+ * If this is the last active Socket instance of the {@link Manager}, the low-level connection will be closed.
3609
+ *
3610
+ * @example
3611
+ * const socket = io();
3612
+ *
3613
+ * socket.on("disconnect", (reason) => {
3614
+ * // console.log(reason); prints "io client disconnect"
3615
+ * });
3616
+ *
3617
+ * socket.disconnect();
3618
+ *
3619
+ * @return self
3620
+ */
3621
+ disconnect() {
3622
+ if (this.connected) {
3623
+ this.packet({ type: PacketType.DISCONNECT });
3624
+ }
3625
+ this.destroy();
3626
+ if (this.connected) {
3627
+ this.onclose("io client disconnect");
3628
+ }
3629
+ return this;
3630
+ }
3631
+ /**
3632
+ * Alias for {@link disconnect()}.
3633
+ *
3634
+ * @return self
3635
+ */
3636
+ close() {
3637
+ return this.disconnect();
3638
+ }
3639
+ /**
3640
+ * Sets the compress flag.
3641
+ *
3642
+ * @example
3643
+ * socket.compress(false).emit("hello");
3644
+ *
3645
+ * @param compress - if `true`, compresses the sending data
3646
+ * @return self
3647
+ */
3648
+ compress(compress) {
3649
+ this.flags.compress = compress;
3650
+ return this;
3651
+ }
3652
+ /**
3653
+ * Sets a modifier for a subsequent event emission that the event message will be dropped when this socket is not
3654
+ * ready to send messages.
3655
+ *
3656
+ * @example
3657
+ * socket.volatile.emit("hello"); // the server may or may not receive it
3658
+ *
3659
+ * @returns self
3660
+ */
3661
+ get volatile() {
3662
+ this.flags.volatile = true;
3663
+ return this;
3664
+ }
3665
+ /**
3666
+ * Sets a modifier for a subsequent event emission that the callback will be called with an error when the
3667
+ * given number of milliseconds have elapsed without an acknowledgement from the server:
3668
+ *
3669
+ * @example
3670
+ * socket.timeout(5000).emit("my-event", (err) => {
3671
+ * if (err) {
3672
+ * // the server did not acknowledge the event in the given delay
3673
+ * }
3674
+ * });
3675
+ *
3676
+ * @returns self
3677
+ */
3678
+ timeout(timeout) {
3679
+ this.flags.timeout = timeout;
3680
+ return this;
3681
+ }
3682
+ /**
3683
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3684
+ * callback.
3685
+ *
3686
+ * @example
3687
+ * socket.onAny((event, ...args) => {
3688
+ * console.log(`got ${event}`);
3689
+ * });
3690
+ *
3691
+ * @param listener
3692
+ */
3693
+ onAny(listener) {
3694
+ this._anyListeners = this._anyListeners || [];
3695
+ this._anyListeners.push(listener);
3696
+ return this;
3697
+ }
3698
+ /**
3699
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3700
+ * callback. The listener is added to the beginning of the listeners array.
3701
+ *
3702
+ * @example
3703
+ * socket.prependAny((event, ...args) => {
3704
+ * console.log(`got event ${event}`);
3705
+ * });
3706
+ *
3707
+ * @param listener
3708
+ */
3709
+ prependAny(listener) {
3710
+ this._anyListeners = this._anyListeners || [];
3711
+ this._anyListeners.unshift(listener);
3712
+ return this;
3713
+ }
3714
+ /**
3715
+ * Removes the listener that will be fired when any event is emitted.
3716
+ *
3717
+ * @example
3718
+ * const catchAllListener = (event, ...args) => {
3719
+ * console.log(`got event ${event}`);
3720
+ * }
3721
+ *
3722
+ * socket.onAny(catchAllListener);
3723
+ *
3724
+ * // remove a specific listener
3725
+ * socket.offAny(catchAllListener);
3726
+ *
3727
+ * // or remove all listeners
3728
+ * socket.offAny();
3729
+ *
3730
+ * @param listener
3731
+ */
3732
+ offAny(listener) {
3733
+ if (!this._anyListeners) {
3734
+ return this;
3735
+ }
3736
+ if (listener) {
3737
+ const listeners = this._anyListeners;
3738
+ for (let i = 0; i < listeners.length; i++) {
3739
+ if (listener === listeners[i]) {
3740
+ listeners.splice(i, 1);
3741
+ return this;
3742
+ }
3743
+ }
3744
+ } else {
3745
+ this._anyListeners = [];
3746
+ }
3747
+ return this;
3748
+ }
3749
+ /**
3750
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3751
+ * e.g. to remove listeners.
3752
+ */
3753
+ listenersAny() {
3754
+ return this._anyListeners || [];
3755
+ }
3756
+ /**
3757
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3758
+ * callback.
3759
+ *
3760
+ * Note: acknowledgements sent to the server are not included.
3761
+ *
3762
+ * @example
3763
+ * socket.onAnyOutgoing((event, ...args) => {
3764
+ * console.log(`sent event ${event}`);
3765
+ * });
3766
+ *
3767
+ * @param listener
3768
+ */
3769
+ onAnyOutgoing(listener) {
3770
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3771
+ this._anyOutgoingListeners.push(listener);
3772
+ return this;
3773
+ }
3774
+ /**
3775
+ * Adds a listener that will be fired when any event is emitted. The event name is passed as the first argument to the
3776
+ * callback. The listener is added to the beginning of the listeners array.
3777
+ *
3778
+ * Note: acknowledgements sent to the server are not included.
3779
+ *
3780
+ * @example
3781
+ * socket.prependAnyOutgoing((event, ...args) => {
3782
+ * console.log(`sent event ${event}`);
3783
+ * });
3784
+ *
3785
+ * @param listener
3786
+ */
3787
+ prependAnyOutgoing(listener) {
3788
+ this._anyOutgoingListeners = this._anyOutgoingListeners || [];
3789
+ this._anyOutgoingListeners.unshift(listener);
3790
+ return this;
3791
+ }
3792
+ /**
3793
+ * Removes the listener that will be fired when any event is emitted.
3794
+ *
3795
+ * @example
3796
+ * const catchAllListener = (event, ...args) => {
3797
+ * console.log(`sent event ${event}`);
3798
+ * }
3799
+ *
3800
+ * socket.onAnyOutgoing(catchAllListener);
3801
+ *
3802
+ * // remove a specific listener
3803
+ * socket.offAnyOutgoing(catchAllListener);
3804
+ *
3805
+ * // or remove all listeners
3806
+ * socket.offAnyOutgoing();
3807
+ *
3808
+ * @param [listener] - the catch-all listener (optional)
3809
+ */
3810
+ offAnyOutgoing(listener) {
3811
+ if (!this._anyOutgoingListeners) {
3812
+ return this;
3813
+ }
3814
+ if (listener) {
3815
+ const listeners = this._anyOutgoingListeners;
3816
+ for (let i = 0; i < listeners.length; i++) {
3817
+ if (listener === listeners[i]) {
3818
+ listeners.splice(i, 1);
3819
+ return this;
3820
+ }
3821
+ }
3822
+ } else {
3823
+ this._anyOutgoingListeners = [];
3824
+ }
3825
+ return this;
3826
+ }
3827
+ /**
3828
+ * Returns an array of listeners that are listening for any event that is specified. This array can be manipulated,
3829
+ * e.g. to remove listeners.
3830
+ */
3831
+ listenersAnyOutgoing() {
3832
+ return this._anyOutgoingListeners || [];
3833
+ }
3834
+ /**
3835
+ * Notify the listeners for each packet sent
3836
+ *
3837
+ * @param packet
3838
+ *
3839
+ * @private
3840
+ */
3841
+ notifyOutgoingListeners(packet) {
3842
+ if (this._anyOutgoingListeners && this._anyOutgoingListeners.length) {
3843
+ const listeners = this._anyOutgoingListeners.slice();
3844
+ for (const listener of listeners) {
3845
+ listener.apply(this, packet.data);
3846
+ }
3847
+ }
3848
+ }
3849
+ };
3850
+
3851
+ // ../../node_modules/socket.io-client/build/esm/contrib/backo2.js
3852
+ function Backoff(opts) {
3853
+ opts = opts || {};
3854
+ this.ms = opts.min || 100;
3855
+ this.max = opts.max || 1e4;
3856
+ this.factor = opts.factor || 2;
3857
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
3858
+ this.attempts = 0;
3859
+ }
3860
+ Backoff.prototype.duration = function() {
3861
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
3862
+ if (this.jitter) {
3863
+ var rand = Math.random();
3864
+ var deviation = Math.floor(rand * this.jitter * ms);
3865
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
3866
+ }
3867
+ return Math.min(ms, this.max) | 0;
3868
+ };
3869
+ Backoff.prototype.reset = function() {
3870
+ this.attempts = 0;
3871
+ };
3872
+ Backoff.prototype.setMin = function(min) {
3873
+ this.ms = min;
3874
+ };
3875
+ Backoff.prototype.setMax = function(max) {
3876
+ this.max = max;
3877
+ };
3878
+ Backoff.prototype.setJitter = function(jitter) {
3879
+ this.jitter = jitter;
3880
+ };
3881
+
3882
+ // ../../node_modules/socket.io-client/build/esm/manager.js
3883
+ var Manager = class extends Emitter {
3884
+ constructor(uri, opts) {
3885
+ var _a;
3886
+ super();
3887
+ this.nsps = {};
3888
+ this.subs = [];
3889
+ if (uri && "object" === typeof uri) {
3890
+ opts = uri;
3891
+ uri = void 0;
3892
+ }
3893
+ opts = opts || {};
3894
+ opts.path = opts.path || "/socket.io";
3895
+ this.opts = opts;
3896
+ installTimerFunctions(this, opts);
3897
+ this.reconnection(opts.reconnection !== false);
3898
+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
3899
+ this.reconnectionDelay(opts.reconnectionDelay || 1e3);
3900
+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5e3);
3901
+ this.randomizationFactor((_a = opts.randomizationFactor) !== null && _a !== void 0 ? _a : 0.5);
3902
+ this.backoff = new Backoff({
3903
+ min: this.reconnectionDelay(),
3904
+ max: this.reconnectionDelayMax(),
3905
+ jitter: this.randomizationFactor()
3906
+ });
3907
+ this.timeout(null == opts.timeout ? 2e4 : opts.timeout);
3908
+ this._readyState = "closed";
3909
+ this.uri = uri;
3910
+ const _parser = opts.parser || esm_exports;
3911
+ this.encoder = new _parser.Encoder();
3912
+ this.decoder = new _parser.Decoder();
3913
+ this._autoConnect = opts.autoConnect !== false;
3914
+ if (this._autoConnect)
3915
+ this.open();
3916
+ }
3917
+ reconnection(v) {
3918
+ if (!arguments.length)
3919
+ return this._reconnection;
3920
+ this._reconnection = !!v;
3921
+ if (!v) {
3922
+ this.skipReconnect = true;
3923
+ }
3924
+ return this;
3925
+ }
3926
+ reconnectionAttempts(v) {
3927
+ if (v === void 0)
3928
+ return this._reconnectionAttempts;
3929
+ this._reconnectionAttempts = v;
3930
+ return this;
3931
+ }
3932
+ reconnectionDelay(v) {
3933
+ var _a;
3934
+ if (v === void 0)
3935
+ return this._reconnectionDelay;
3936
+ this._reconnectionDelay = v;
3937
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMin(v);
3938
+ return this;
3939
+ }
3940
+ randomizationFactor(v) {
3941
+ var _a;
3942
+ if (v === void 0)
3943
+ return this._randomizationFactor;
3944
+ this._randomizationFactor = v;
3945
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setJitter(v);
3946
+ return this;
3947
+ }
3948
+ reconnectionDelayMax(v) {
3949
+ var _a;
3950
+ if (v === void 0)
3951
+ return this._reconnectionDelayMax;
3952
+ this._reconnectionDelayMax = v;
3953
+ (_a = this.backoff) === null || _a === void 0 ? void 0 : _a.setMax(v);
3954
+ return this;
3955
+ }
3956
+ timeout(v) {
3957
+ if (!arguments.length)
3958
+ return this._timeout;
3959
+ this._timeout = v;
3960
+ return this;
3961
+ }
3962
+ /**
3963
+ * Starts trying to reconnect if reconnection is enabled and we have not
3964
+ * started reconnecting yet
3965
+ *
3966
+ * @private
3967
+ */
3968
+ maybeReconnectOnOpen() {
3969
+ if (!this._reconnecting && this._reconnection && this.backoff.attempts === 0) {
3970
+ this.reconnect();
3971
+ }
3972
+ }
3973
+ /**
3974
+ * Sets the current transport `socket`.
3975
+ *
3976
+ * @param {Function} fn - optional, callback
3977
+ * @return self
3978
+ * @public
3979
+ */
3980
+ open(fn) {
3981
+ if (~this._readyState.indexOf("open"))
3982
+ return this;
3983
+ this.engine = new Socket(this.uri, this.opts);
3984
+ const socket = this.engine;
3985
+ const self2 = this;
3986
+ this._readyState = "opening";
3987
+ this.skipReconnect = false;
3988
+ const openSubDestroy = on(socket, "open", function() {
3989
+ self2.onopen();
3990
+ fn && fn();
3991
+ });
3992
+ const onError = (err) => {
3993
+ this.cleanup();
3994
+ this._readyState = "closed";
3995
+ this.emitReserved("error", err);
3996
+ if (fn) {
3997
+ fn(err);
3998
+ } else {
3999
+ this.maybeReconnectOnOpen();
4000
+ }
4001
+ };
4002
+ const errorSub = on(socket, "error", onError);
4003
+ if (false !== this._timeout) {
4004
+ const timeout = this._timeout;
4005
+ const timer = this.setTimeoutFn(() => {
4006
+ openSubDestroy();
4007
+ onError(new Error("timeout"));
4008
+ socket.close();
4009
+ }, timeout);
4010
+ if (this.opts.autoUnref) {
4011
+ timer.unref();
4012
+ }
4013
+ this.subs.push(() => {
4014
+ this.clearTimeoutFn(timer);
4015
+ });
4016
+ }
4017
+ this.subs.push(openSubDestroy);
4018
+ this.subs.push(errorSub);
4019
+ return this;
4020
+ }
4021
+ /**
4022
+ * Alias for open()
4023
+ *
4024
+ * @return self
4025
+ * @public
4026
+ */
4027
+ connect(fn) {
4028
+ return this.open(fn);
4029
+ }
4030
+ /**
4031
+ * Called upon transport open.
4032
+ *
4033
+ * @private
4034
+ */
4035
+ onopen() {
4036
+ this.cleanup();
4037
+ this._readyState = "open";
4038
+ this.emitReserved("open");
4039
+ const socket = this.engine;
4040
+ this.subs.push(
4041
+ on(socket, "ping", this.onping.bind(this)),
4042
+ on(socket, "data", this.ondata.bind(this)),
4043
+ on(socket, "error", this.onerror.bind(this)),
4044
+ on(socket, "close", this.onclose.bind(this)),
4045
+ // @ts-ignore
4046
+ on(this.decoder, "decoded", this.ondecoded.bind(this))
4047
+ );
4048
+ }
4049
+ /**
4050
+ * Called upon a ping.
4051
+ *
4052
+ * @private
4053
+ */
4054
+ onping() {
4055
+ this.emitReserved("ping");
4056
+ }
4057
+ /**
4058
+ * Called with data.
4059
+ *
4060
+ * @private
4061
+ */
4062
+ ondata(data) {
4063
+ try {
4064
+ this.decoder.add(data);
4065
+ } catch (e) {
4066
+ this.onclose("parse error", e);
4067
+ }
4068
+ }
4069
+ /**
4070
+ * Called when parser fully decodes a packet.
4071
+ *
4072
+ * @private
4073
+ */
4074
+ ondecoded(packet) {
4075
+ nextTick(() => {
4076
+ this.emitReserved("packet", packet);
4077
+ }, this.setTimeoutFn);
4078
+ }
4079
+ /**
4080
+ * Called upon socket error.
4081
+ *
4082
+ * @private
4083
+ */
4084
+ onerror(err) {
4085
+ this.emitReserved("error", err);
4086
+ }
4087
+ /**
4088
+ * Creates a new socket for the given `nsp`.
4089
+ *
4090
+ * @return {Socket}
4091
+ * @public
4092
+ */
4093
+ socket(nsp, opts) {
4094
+ let socket = this.nsps[nsp];
4095
+ if (!socket) {
4096
+ socket = new Socket2(this, nsp, opts);
4097
+ this.nsps[nsp] = socket;
4098
+ } else if (this._autoConnect && !socket.active) {
4099
+ socket.connect();
4100
+ }
4101
+ return socket;
4102
+ }
4103
+ /**
4104
+ * Called upon a socket close.
4105
+ *
4106
+ * @param socket
4107
+ * @private
4108
+ */
4109
+ _destroy(socket) {
4110
+ const nsps = Object.keys(this.nsps);
4111
+ for (const nsp of nsps) {
4112
+ const socket2 = this.nsps[nsp];
4113
+ if (socket2.active) {
4114
+ return;
4115
+ }
4116
+ }
4117
+ this._close();
4118
+ }
4119
+ /**
4120
+ * Writes a packet.
4121
+ *
4122
+ * @param packet
4123
+ * @private
4124
+ */
4125
+ _packet(packet) {
4126
+ const encodedPackets = this.encoder.encode(packet);
4127
+ for (let i = 0; i < encodedPackets.length; i++) {
4128
+ this.engine.write(encodedPackets[i], packet.options);
4129
+ }
4130
+ }
4131
+ /**
4132
+ * Clean up transport subscriptions and packet buffer.
4133
+ *
4134
+ * @private
4135
+ */
4136
+ cleanup() {
4137
+ this.subs.forEach((subDestroy) => subDestroy());
4138
+ this.subs.length = 0;
4139
+ this.decoder.destroy();
4140
+ }
4141
+ /**
4142
+ * Close the current socket.
4143
+ *
4144
+ * @private
4145
+ */
4146
+ _close() {
4147
+ this.skipReconnect = true;
4148
+ this._reconnecting = false;
4149
+ this.onclose("forced close");
4150
+ }
4151
+ /**
4152
+ * Alias for close()
4153
+ *
4154
+ * @private
4155
+ */
4156
+ disconnect() {
4157
+ return this._close();
4158
+ }
4159
+ /**
4160
+ * Called when:
4161
+ *
4162
+ * - the low-level engine is closed
4163
+ * - the parser encountered a badly formatted packet
4164
+ * - all sockets are disconnected
4165
+ *
4166
+ * @private
4167
+ */
4168
+ onclose(reason, description) {
4169
+ var _a;
4170
+ this.cleanup();
4171
+ (_a = this.engine) === null || _a === void 0 ? void 0 : _a.close();
4172
+ this.backoff.reset();
4173
+ this._readyState = "closed";
4174
+ this.emitReserved("close", reason, description);
4175
+ if (this._reconnection && !this.skipReconnect) {
4176
+ this.reconnect();
4177
+ }
4178
+ }
4179
+ /**
4180
+ * Attempt a reconnection.
4181
+ *
4182
+ * @private
4183
+ */
4184
+ reconnect() {
4185
+ if (this._reconnecting || this.skipReconnect)
4186
+ return this;
4187
+ const self2 = this;
4188
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
4189
+ this.backoff.reset();
4190
+ this.emitReserved("reconnect_failed");
4191
+ this._reconnecting = false;
4192
+ } else {
4193
+ const delay = this.backoff.duration();
4194
+ this._reconnecting = true;
4195
+ const timer = this.setTimeoutFn(() => {
4196
+ if (self2.skipReconnect)
4197
+ return;
4198
+ this.emitReserved("reconnect_attempt", self2.backoff.attempts);
4199
+ if (self2.skipReconnect)
4200
+ return;
4201
+ self2.open((err) => {
4202
+ if (err) {
4203
+ self2._reconnecting = false;
4204
+ self2.reconnect();
4205
+ this.emitReserved("reconnect_error", err);
4206
+ } else {
4207
+ self2.onreconnect();
4208
+ }
4209
+ });
4210
+ }, delay);
4211
+ if (this.opts.autoUnref) {
4212
+ timer.unref();
4213
+ }
4214
+ this.subs.push(() => {
4215
+ this.clearTimeoutFn(timer);
4216
+ });
4217
+ }
4218
+ }
4219
+ /**
4220
+ * Called upon successful reconnect.
4221
+ *
4222
+ * @private
4223
+ */
4224
+ onreconnect() {
4225
+ const attempt = this.backoff.attempts;
4226
+ this._reconnecting = false;
4227
+ this.backoff.reset();
4228
+ this.emitReserved("reconnect", attempt);
4229
+ }
4230
+ };
4231
+
4232
+ // ../../node_modules/socket.io-client/build/esm/index.js
4233
+ var cache = {};
4234
+ function lookup2(uri, opts) {
4235
+ if (typeof uri === "object") {
4236
+ opts = uri;
4237
+ uri = void 0;
4238
+ }
4239
+ opts = opts || {};
4240
+ const parsed = url(uri, opts.path || "/socket.io");
4241
+ const source = parsed.source;
4242
+ const id = parsed.id;
4243
+ const path = parsed.path;
4244
+ const sameNamespace = cache[id] && path in cache[id]["nsps"];
4245
+ const newConnection = opts.forceNew || opts["force new connection"] || false === opts.multiplex || sameNamespace;
4246
+ let io;
4247
+ if (newConnection) {
4248
+ io = new Manager(source, opts);
4249
+ } else {
4250
+ if (!cache[id]) {
4251
+ cache[id] = new Manager(source, opts);
4252
+ }
4253
+ io = cache[id];
4254
+ }
4255
+ if (parsed.query && !opts.query) {
4256
+ opts.query = parsed.queryKey;
4257
+ }
4258
+ return io.socket(parsed.path, opts);
4259
+ }
4260
+ Object.assign(lookup2, {
4261
+ Manager,
4262
+ Socket: Socket2,
4263
+ io: lookup2,
4264
+ connect: lookup2
4265
+ });
4266
+
4267
+ // src/payment-socket.ts
4268
+ function idsMatch(eventId, expectedId) {
4269
+ if (!expectedId) return true;
4270
+ if (!eventId) return false;
4271
+ return String(eventId) === String(expectedId);
4272
+ }
4273
+ function isConfirmedStatus(status) {
4274
+ return ["COMPLETED", "CONFIRMED", "PAID", "SUCCESS", "OVERPAID"].includes(
4275
+ String(status || "").toUpperCase()
4276
+ );
4277
+ }
4278
+ function watchPaymentSocket(params) {
4279
+ const {
4280
+ apiBaseUrl,
4281
+ shoppingCartReference,
4282
+ purchaseId,
4283
+ signal,
4284
+ timeoutMs = 45 * 60 * 1e3
4285
+ } = params;
4286
+ let socket = null;
4287
+ let settled = false;
4288
+ let connected = false;
4289
+ let timer = null;
4290
+ let resolveFn = null;
4291
+ let rejectFn = null;
4292
+ const dispose = () => {
4293
+ if (timer) {
4294
+ clearTimeout(timer);
4295
+ timer = null;
4296
+ }
4297
+ signal?.removeEventListener("abort", onAbort);
4298
+ if (socket) {
4299
+ socket.removeAllListeners();
4300
+ socket.disconnect();
4301
+ socket = null;
4302
+ }
4303
+ };
4304
+ const settleResolve = (value2) => {
4305
+ if (settled) return;
4306
+ settled = true;
4307
+ dispose();
4308
+ resolveFn?.(value2);
4309
+ };
4310
+ const settleReject = (reason) => {
4311
+ if (settled) return;
4312
+ settled = true;
4313
+ dispose();
4314
+ rejectFn?.(reason);
4315
+ };
4316
+ const onAbort = () => {
4317
+ settleReject(new Error("checkout_aborted"));
4318
+ };
4319
+ const handleSnapshot = (payload) => {
4320
+ const eventPurchaseId = payload?.purchaseId || payload?.orderId;
4321
+ if (!idsMatch(eventPurchaseId ? String(eventPurchaseId) : void 0, purchaseId)) {
4322
+ return;
4323
+ }
4324
+ if (isConfirmedStatus(payload?.status)) {
4325
+ settleResolve({
4326
+ ...payload,
4327
+ status: String(payload.status || "SUCCESS").toUpperCase()
4328
+ });
4329
+ }
4330
+ };
4331
+ const promise = new Promise((resolve, reject) => {
4332
+ resolveFn = resolve;
4333
+ rejectFn = reject;
4334
+ if (signal?.aborted) {
4335
+ settleReject(new Error("checkout_aborted"));
4336
+ return;
4337
+ }
4338
+ signal?.addEventListener("abort", onAbort, { once: true });
4339
+ timer = setTimeout(() => {
4340
+ settleReject(new Error("checkout_payment_timeout"));
4341
+ }, timeoutMs);
4342
+ try {
4343
+ socket = lookup2(apiBaseUrl.replace(/\/+$/, ""), {
4344
+ withCredentials: true,
4345
+ reconnection: true,
4346
+ reconnectionAttempts: Infinity,
4347
+ reconnectionDelay: 1e3,
4348
+ reconnectionDelayMax: 1e4,
4349
+ timeout: 2e4,
4350
+ transports: ["websocket", "polling"]
4351
+ });
4352
+ } catch (err) {
4353
+ settleReject(err);
4354
+ return;
4355
+ }
4356
+ const joinRoom = () => {
4357
+ if (!socket?.connected) return;
4358
+ connected = true;
4359
+ socket.emit("payment:process", { shoppingCartReference });
4360
+ };
4361
+ socket.on("connect", joinRoom);
4362
+ socket.on("reconnect", joinRoom);
4363
+ socket.on("payment:confirmed", (payload) => {
4364
+ handleSnapshot({
4365
+ ...payload,
4366
+ status: payload?.status || "SUCCESS"
4367
+ });
4368
+ });
4369
+ socket.on("payment:status", (payload) => {
4370
+ handleSnapshot(payload);
4371
+ });
4372
+ socket.on("payment:processing", () => {
4373
+ });
4374
+ socket.on("payment:underpaid", () => {
4375
+ });
4376
+ socket.on("connect_error", () => {
4377
+ connected = false;
4378
+ });
4379
+ socket.on("disconnect", () => {
4380
+ connected = false;
4381
+ });
4382
+ if (socket.connected) joinRoom();
4383
+ });
4384
+ return {
4385
+ promise,
4386
+ dispose: () => {
4387
+ if (!settled) {
4388
+ settled = true;
4389
+ dispose();
4390
+ return;
4391
+ }
4392
+ dispose();
4393
+ },
4394
+ get connected() {
4395
+ return connected;
4396
+ }
4397
+ };
4398
+ }
4399
+
4400
+ // src/navigate.ts
4401
+ function navigateTopLevel(url2) {
4402
+ if (typeof window === "undefined" || !url2) return;
4403
+ try {
4404
+ const topWin = window.top;
4405
+ if (topWin && topWin !== window) {
4406
+ topWin.location.assign(url2);
4407
+ return;
4408
+ }
4409
+ } catch {
4410
+ }
4411
+ window.location.assign(url2);
4412
+ }
4413
+ function resolveRedirectUrl(params) {
4414
+ if (params.nextAction?.type === "redirect" && params.nextAction.url) {
4415
+ return params.nextAction.url;
4416
+ }
4417
+ return params.redirectUrl || params.initPoint || null;
4418
+ }
4419
+
4420
+ // src/controller.ts
4421
+ function generateIdempotencyKey() {
4422
+ if (typeof crypto !== "undefined" && "randomUUID" in crypto) {
4423
+ return crypto.randomUUID();
4424
+ }
4425
+ return `idem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
4426
+ }
4427
+ function toTickeanError(err) {
4428
+ if (err instanceof TickeanError) return err;
4429
+ const anyErr = err;
4430
+ return new TickeanError(
4431
+ {
4432
+ code: anyErr?.code || "checkout_unknown_error",
4433
+ message: anyErr?.message || "Unexpected checkout error",
4434
+ details: anyErr?.details
4435
+ },
4436
+ anyErr?.status
4437
+ );
4438
+ }
4439
+ function resolveShowIdFromCart(event, cart) {
4440
+ const optionId = cart.find((item) => item.showOptionId)?.showOptionId;
4441
+ if (!optionId || !event?.shows?.length) return null;
4442
+ for (const show of event.shows) {
4443
+ if ((show.showOptions || []).some((opt) => opt.id === optionId)) {
4444
+ return show.id;
4445
+ }
4446
+ }
4447
+ return null;
4448
+ }
4449
+ function createCheckoutController(options) {
4450
+ const client = createTickean(options);
4451
+ const telemetry = options.telemetry || createNoopTelemetry();
4452
+ const persistenceKey = options.persistenceKey || `tickean.checkout.${options.eventSlug}.${options.publishableKey || "demo"}`;
4453
+ const persistence = options.persistence === false ? null : options.persistence || (typeof sessionStorage !== "undefined" ? createSessionStoragePersistence() : createMemoryPersistence());
4454
+ let state = createInitialState();
4455
+ const listeners = /* @__PURE__ */ new Set();
4456
+ let quoteTimer = null;
4457
+ let activeSocketWatch = null;
4458
+ let watchAbort = null;
4459
+ let quoteGeneration = 0;
4460
+ const quoteDebounceMs = options.quoteDebounceMs ?? 300;
4461
+ let disposed = false;
4462
+ const emit = (name, properties) => {
4463
+ telemetry.track({ name, timestamp: Date.now(), properties });
4464
+ };
4465
+ const notify = () => {
4466
+ const snapshot = getSnapshot();
4467
+ for (const listener of listeners) {
4468
+ try {
4469
+ listener(snapshot);
4470
+ } catch {
4471
+ }
4472
+ }
4473
+ };
4474
+ const dispatch = (action) => {
4475
+ state = checkoutReducer(state, action);
4476
+ persist();
4477
+ notify();
4478
+ };
4479
+ const persist = () => {
4480
+ if (!persistence) return;
4481
+ persistence.set(persistenceKey, {
4482
+ sessionToken: state.session?.sessionToken,
4483
+ eventSlug: options.eventSlug,
4484
+ cart: state.cart,
4485
+ discountCode: state.discountCode,
4486
+ phase: state.phase,
4487
+ buyerVerified: state.buyerVerified,
4488
+ purchaseId: state.purchase?.id ?? null
4489
+ });
4490
+ };
4491
+ const getSnapshot = () => state;
4492
+ const subscribe = (listener) => {
4493
+ listeners.add(listener);
4494
+ return () => {
4495
+ listeners.delete(listener);
4496
+ };
4497
+ };
4498
+ const scheduleQuote = () => {
4499
+ if (quoteTimer) clearTimeout(quoteTimer);
4500
+ if (!state.session || state.cart.length === 0) {
4501
+ dispatch({
4502
+ type: "QUOTE_SUCCESS",
4503
+ quote: {
4504
+ valid: true,
4505
+ totalPrice: 0,
4506
+ pricingBreakdown: { subtotal: 0 }
4507
+ }
4508
+ });
4509
+ return;
4510
+ }
4511
+ const gen = ++quoteGeneration;
4512
+ quoteTimer = setTimeout(async () => {
4513
+ dispatch({ type: "QUOTE_START" });
4514
+ emit("checkout.quote.start", { items: state.cart.length });
4515
+ try {
4516
+ const quote = await client.quote({
4517
+ items: state.cart,
4518
+ discountCode: state.discountCode || void 0
4519
+ });
4520
+ if (disposed || gen !== quoteGeneration) return;
4521
+ dispatch({ type: "QUOTE_SUCCESS", quote });
4522
+ emit("checkout.quote.success", { totalPrice: quote.totalPrice });
4523
+ if ((quote.unlockedShowOptions || []).length > 0) {
4524
+ dispatch({
4525
+ type: "MERGE_UNLOCKED_OPTIONS",
4526
+ options: quote.unlockedShowOptions || []
4527
+ });
4528
+ }
4529
+ } catch (err) {
4530
+ if (disposed || gen !== quoteGeneration) return;
4531
+ const error = toTickeanError(err);
4532
+ dispatch({ type: "QUOTE_FAILURE", error });
4533
+ emit("checkout.quote.error", { code: error.code });
4534
+ }
4535
+ }, quoteDebounceMs);
4536
+ };
4537
+ const setCartItem = (showOptionId, amount) => {
4538
+ const next = state.cart.filter((item) => item.showOptionId !== showOptionId);
4539
+ if (amount > 0) next.push({ showOptionId, amount });
4540
+ dispatch({ type: "SET_CART", cart: next });
4541
+ emit("checkout.cart.change", { showOptionId, amount });
4542
+ scheduleQuote();
4543
+ };
4544
+ const setCart = (cart) => {
4545
+ dispatch({
4546
+ type: "SET_CART",
4547
+ cart: cart.filter((item) => item.amount > 0)
4548
+ });
4549
+ emit("checkout.cart.change", { count: cart.length });
4550
+ scheduleQuote();
4551
+ };
4552
+ const applyDiscountCode = async (code) => {
4553
+ const normalized = code.trim().toUpperCase();
4554
+ dispatch({ type: "SET_DISCOUNT", discountCode: normalized || null });
4555
+ if (!state.session) {
4556
+ throw new TickeanError({
4557
+ code: "checkout_session_required",
4558
+ message: "Session required"
4559
+ });
4560
+ }
4561
+ dispatch({ type: "QUOTE_START" });
4562
+ try {
4563
+ const quote = await client.quote({
4564
+ items: state.cart,
4565
+ discountCode: normalized || void 0
4566
+ });
4567
+ const unlocked = quote.unlockedShowOptions || [];
4568
+ const unlockedIds = quote.unlockedShowOptionIds || [];
4569
+ const unlockedAnything = unlocked.length > 0 || unlockedIds.length > 0;
4570
+ if (quote.valid === false && !unlockedAnything) {
4571
+ dispatch({ type: "SET_DISCOUNT", discountCode: null });
4572
+ const error = new TickeanError({
4573
+ code: "discount_invalid",
4574
+ message: quote.message || "Invalid discount code"
4575
+ });
4576
+ dispatch({ type: "QUOTE_FAILURE", error });
4577
+ throw error;
4578
+ }
4579
+ dispatch({ type: "QUOTE_SUCCESS", quote });
4580
+ emit("checkout.discount.applied", { code: normalized || null });
4581
+ if (unlocked.length > 0) {
4582
+ dispatch({
4583
+ type: "MERGE_UNLOCKED_OPTIONS",
4584
+ options: unlocked
4585
+ });
4586
+ }
4587
+ return quote;
4588
+ } catch (err) {
4589
+ const error = toTickeanError(err);
4590
+ if (error.code !== "discount_invalid") {
4591
+ dispatch({ type: "QUOTE_FAILURE", error });
4592
+ }
4593
+ throw error;
4594
+ }
4595
+ };
4596
+ const lookupBuyer = async (phone) => {
4597
+ const result = await client.lookupBuyer({ phone });
4598
+ emit("checkout.buyer.lookup", { exists: result.exists });
4599
+ return result;
4600
+ };
4601
+ const sendOtp = async (phone, channel) => {
4602
+ await client.sendOtp({ phone, channel });
4603
+ dispatch({ type: "OTP_SENT" });
4604
+ emit("checkout.otp.sent");
4605
+ };
4606
+ const verifyOtp = async (params) => {
4607
+ const result = await client.verifyOtp(params);
4608
+ const buyer = result.buyer || {
4609
+ id: "buyer",
4610
+ phone: params.phone,
4611
+ name: params.name,
4612
+ email: params.email
4613
+ };
4614
+ dispatch({ type: "OTP_VERIFIED", buyer });
4615
+ emit("checkout.otp.verified");
4616
+ };
4617
+ const stopPaymentWatchers = () => {
4618
+ watchAbort?.abort();
4619
+ watchAbort = null;
4620
+ activeSocketWatch?.dispose();
4621
+ activeSocketWatch = null;
4622
+ };
4623
+ const changePaymentMethod = () => {
4624
+ stopPaymentWatchers();
4625
+ dispatch({ type: "RESET_PAYMENT_FLOW" });
4626
+ emit("checkout.payment.method_change");
4627
+ };
4628
+ const purchaseAndPay = async (params) => {
4629
+ stopPaymentWatchers();
4630
+ dispatch({ type: "PURCHASE_START" });
4631
+ const idempotencyKey = params.idempotencyKey || generateIdempotencyKey();
4632
+ emit("checkout.purchase.start", { paymentMethod: params.paymentMethod });
4633
+ try {
4634
+ const showId = params.showId || resolveShowIdFromCart(state.event, state.cart) || void 0;
4635
+ const purchase = await client.createPurchase({
4636
+ items: state.cart,
4637
+ paymentMethod: params.paymentMethod,
4638
+ currency: params.currency,
4639
+ discountCode: params.discountCode ?? state.discountCode ?? void 0,
4640
+ expectedTotal: state.quote?.totalPrice,
4641
+ showId,
4642
+ idempotencyKey,
4643
+ attendees: params.attendees
4644
+ });
4645
+ const payment = await client.createPayment({
4646
+ orderId: purchase.purchase.id,
4647
+ paymentMethod: params.paymentMethod,
4648
+ currency: params.currency,
4649
+ amount: purchase.purchase.totalPrice,
4650
+ idempotencyKey: `${idempotencyKey}:payment`
4651
+ });
4652
+ const redirectUrl = resolveRedirectUrl({
4653
+ nextAction: payment.nextAction,
4654
+ redirectUrl: payment.redirectUrl,
4655
+ initPoint: payment.initPoint
4656
+ });
4657
+ const nextAction = payment.nextAction || (payment.paymentInstructions ? {
4658
+ type: "display_instructions",
4659
+ paymentInstructions: payment.paymentInstructions
4660
+ } : redirectUrl ? { type: "redirect", url: redirectUrl } : { type: "none" });
4661
+ dispatch({
4662
+ type: "PURCHASE_SUCCESS",
4663
+ purchase: purchase.purchase,
4664
+ payment,
4665
+ nextAction
4666
+ });
4667
+ emit("checkout.purchase.success", {
4668
+ purchaseId: purchase.purchase.id,
4669
+ nextActionType: nextAction.type
4670
+ });
4671
+ if (nextAction.type === "display_instructions") {
4672
+ void watchPayment({
4673
+ intervalMs: 1e4,
4674
+ timeoutMs: 45 * 60 * 1e3
4675
+ }).catch(() => {
4676
+ });
4677
+ }
4678
+ if (nextAction.type === "redirect" && nextAction.url) {
4679
+ navigateTopLevel(nextAction.url);
4680
+ }
4681
+ return { purchaseId: purchase.purchase.id, payment, nextAction };
4682
+ } catch (err) {
4683
+ const error = toTickeanError(err);
4684
+ dispatch({ type: "PURCHASE_FAILURE", error });
4685
+ emit("checkout.purchase.error", { code: error.code });
4686
+ throw error;
4687
+ }
4688
+ };
4689
+ const confirmPayment = async (params) => {
4690
+ const payment = await client.confirmPayment({
4691
+ ...params,
4692
+ idempotencyKey: params?.idempotencyKey || generateIdempotencyKey()
4693
+ });
4694
+ const nextAction = payment.nextAction || { type: "none" };
4695
+ dispatch({ type: "SET_NEXT_ACTION", nextAction, payment });
4696
+ emit("checkout.payment.confirmed", { nextActionType: nextAction.type });
4697
+ return payment;
4698
+ };
4699
+ const watchPayment = async (watchOptions) => {
4700
+ dispatch({ type: "PROCESSING" });
4701
+ emit("checkout.payment.watch.start");
4702
+ watchAbort?.abort();
4703
+ activeSocketWatch?.dispose();
4704
+ watchAbort = new AbortController();
4705
+ const localAbort = watchAbort;
4706
+ const onOuterAbort = () => localAbort.abort();
4707
+ watchOptions?.signal?.addEventListener("abort", onOuterAbort);
4708
+ const timeoutMs = watchOptions?.timeoutMs ?? 45 * 60 * 1e3;
4709
+ const cartRef = state.purchase?.shoppingCartReference;
4710
+ const purchaseId = state.purchase?.id;
4711
+ const apiBaseUrl = options.apiBaseUrl || "https://api.tickean.com";
4712
+ try {
4713
+ const status = await new Promise((resolve, reject) => {
4714
+ let settled = false;
4715
+ const finish = (fn) => {
4716
+ if (settled) return;
4717
+ settled = true;
4718
+ localAbort.abort();
4719
+ activeSocketWatch?.dispose();
4720
+ activeSocketWatch = null;
4721
+ fn();
4722
+ };
4723
+ if (!options.demo && cartRef) {
4724
+ activeSocketWatch = watchPaymentSocket({
4725
+ apiBaseUrl,
4726
+ shoppingCartReference: cartRef,
4727
+ purchaseId,
4728
+ signal: localAbort.signal,
4729
+ timeoutMs
4730
+ });
4731
+ emit("checkout.payment.socket.start", {
4732
+ shoppingCartReference: cartRef
4733
+ });
4734
+ void activeSocketWatch.promise.then(async (snap) => {
4735
+ emit("checkout.payment.socket.confirmed", {
4736
+ status: snap.status,
4737
+ purchaseId: snap.purchaseId || purchaseId
4738
+ });
4739
+ try {
4740
+ return await client.getPaymentStatus();
4741
+ } catch {
4742
+ return {
4743
+ status: snap.status || "SUCCESS",
4744
+ purchase: state.purchase ? { ...state.purchase, status: "COMPLETED" } : null,
4745
+ payment: state.payment,
4746
+ nextAction: { type: "none" },
4747
+ requiresAction: false
4748
+ };
4749
+ }
4750
+ }).then((result) => finish(() => resolve(result))).catch(() => {
4751
+ });
4752
+ }
4753
+ void client.watchPayment({
4754
+ intervalMs: watchOptions?.intervalMs ?? (cartRef ? 1e4 : 3e3),
4755
+ timeoutMs,
4756
+ signal: localAbort.signal
4757
+ }).then((result) => finish(() => resolve(result))).catch((err) => {
4758
+ if (!settled) finish(() => reject(err));
4759
+ });
4760
+ });
4761
+ if (["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
4762
+ String(status.status || "").toUpperCase()
4763
+ ) || ["COMPLETED", "CONFIRMED", "PAID", "SUCCESS"].includes(
4764
+ String(status.purchase?.status || "").toUpperCase()
4765
+ )) {
4766
+ dispatch({ type: "COMPLETED", purchase: status.purchase });
4767
+ emit("checkout.completed");
4768
+ } else if (status.nextAction && status.nextAction.type !== "none") {
4769
+ dispatch({
4770
+ type: "SET_NEXT_ACTION",
4771
+ nextAction: status.nextAction,
4772
+ payment: status.payment
4773
+ });
4774
+ }
4775
+ return status;
4776
+ } catch (err) {
4777
+ const error = toTickeanError(err);
4778
+ if (error.code !== "checkout_payment_timeout") {
4779
+ dispatch({ type: "FAILED", error });
4780
+ }
4781
+ emit("checkout.payment.watch.error", { code: error.code });
4782
+ throw error;
4783
+ } finally {
4784
+ watchOptions?.signal?.removeEventListener("abort", onOuterAbort);
4785
+ activeSocketWatch?.dispose();
4786
+ activeSocketWatch = null;
4787
+ if (watchAbort === localAbort) watchAbort = null;
4788
+ }
4789
+ };
4790
+ const refreshCatalog = async () => {
4791
+ const catalog = await client.getCatalog();
4792
+ dispatch({ type: "SET_EVENT", event: catalog });
4793
+ return catalog;
4794
+ };
4795
+ const initialize = async () => {
4796
+ dispatch({ type: "INIT_START" });
4797
+ emit("checkout.init.start", { eventSlug: options.eventSlug });
4798
+ try {
4799
+ const resumeCode = options.resumeCode?.trim();
4800
+ if (resumeCode) {
4801
+ const recovered = await client.exchangeRecovery({ code: resumeCode });
4802
+ const session2 = {
4803
+ sessionId: recovered.sessionId,
4804
+ sessionToken: recovered.sessionToken,
4805
+ expiresAt: recovered.expiresAt,
4806
+ event: recovered.event,
4807
+ capabilities: recovered.capabilities || {},
4808
+ shoppingCartReference: recovered.shoppingCartReference,
4809
+ nextAction: recovered.nextAction,
4810
+ phase: recovered.phase
4811
+ };
4812
+ dispatch({
4813
+ type: "INIT_SUCCESS",
4814
+ session: session2,
4815
+ event: recovered.event
4816
+ });
4817
+ dispatch({
4818
+ type: "REHYDRATE",
4819
+ partial: {
4820
+ cart: recovered.cart || [],
4821
+ discountCode: recovered.discountCode || null,
4822
+ buyer: recovered.buyer || null,
4823
+ buyerVerified: Boolean(recovered.buyerVerified || recovered.buyer),
4824
+ otpSent: Boolean(recovered.buyerVerified || recovered.buyer),
4825
+ purchase: recovered.purchase || null,
4826
+ payment: recovered.payment || null,
4827
+ nextAction: recovered.nextAction || { type: "none" },
4828
+ phase: recovered.phase === "completed" ? "completed" : recovered.phase === "processing" || recovered.suggestedStep === "PAYMENT_PENDING" ? "processing" : recovered.buyer ? "ready_to_purchase" : "browsing",
4829
+ loading: false,
4830
+ error: null
4831
+ }
4832
+ });
4833
+ if ((recovered.nextAction?.type === "display_instructions" || recovered.suggestedStep === "PAYMENT_PENDING") && recovered.purchase) {
4834
+ void watchPayment({
4835
+ intervalMs: 1e4,
4836
+ timeoutMs: 45 * 60 * 1e3
4837
+ }).catch(() => void 0);
4838
+ }
4839
+ persist();
4840
+ emit("checkout.init.success", {
4841
+ sessionId: session2.sessionId,
4842
+ resumed: true
4843
+ });
4844
+ return;
4845
+ }
4846
+ const stored = persistence?.get(persistenceKey);
4847
+ let session = null;
4848
+ if (stored?.sessionToken) {
4849
+ try {
4850
+ client.session = {
4851
+ sessionId: "",
4852
+ sessionToken: stored.sessionToken,
4853
+ expiresAt: "",
4854
+ event: {
4855
+ id: "",
4856
+ slug: options.eventSlug,
4857
+ title: "",
4858
+ shows: []
4859
+ },
4860
+ capabilities: {}
4861
+ };
4862
+ const resumed = await client.getSession();
4863
+ session = {
4864
+ ...resumed,
4865
+ sessionToken: stored.sessionToken,
4866
+ event: resumed.event
4867
+ };
4868
+ } catch {
4869
+ client.session = null;
4870
+ persistence?.remove(persistenceKey);
4871
+ }
4872
+ }
4873
+ if (!session) {
4874
+ session = await client.createSession({
4875
+ eventSlug: options.eventSlug,
4876
+ returnUrl: options.returnUrl
4877
+ });
4878
+ }
4879
+ dispatch({
4880
+ type: "INIT_SUCCESS",
4881
+ session,
4882
+ event: session.event
4883
+ });
4884
+ if (session.otpVerified || stored?.buyerVerified) {
4885
+ dispatch({
4886
+ type: "REHYDRATE",
4887
+ partial: {
4888
+ buyerVerified: true,
4889
+ otpSent: true,
4890
+ buyer: session.buyerId ? {
4891
+ id: String(session.buyerId),
4892
+ phone: ""
4893
+ } : void 0
4894
+ }
4895
+ });
4896
+ }
4897
+ if (stored?.cart?.length) {
4898
+ dispatch({ type: "SET_CART", cart: stored.cart });
4899
+ if (stored.discountCode) {
4900
+ dispatch({ type: "SET_DISCOUNT", discountCode: stored.discountCode });
4901
+ }
4902
+ scheduleQuote();
4903
+ }
4904
+ emit("checkout.init.success", { sessionId: session.sessionId });
4905
+ } catch (err) {
4906
+ const error = toTickeanError(err);
4907
+ dispatch({ type: "INIT_FAILURE", error });
4908
+ emit("checkout.init.error", { code: error.code });
4909
+ throw error;
4910
+ }
4911
+ };
4912
+ const dispose = () => {
4913
+ disposed = true;
4914
+ if (quoteTimer) clearTimeout(quoteTimer);
4915
+ watchAbort?.abort();
4916
+ activeSocketWatch?.dispose();
4917
+ activeSocketWatch = null;
4918
+ listeners.clear();
4919
+ };
4920
+ const ready = initialize().catch(() => {
4921
+ });
4922
+ return {
4923
+ client,
4924
+ ready,
4925
+ getSnapshot,
4926
+ subscribe,
4927
+ setCartItem,
4928
+ setCart,
4929
+ applyDiscountCode,
4930
+ lookupBuyer,
4931
+ sendOtp,
4932
+ verifyOtp,
4933
+ purchaseAndPay,
4934
+ changePaymentMethod,
4935
+ confirmPayment,
4936
+ watchPayment,
4937
+ refreshCatalog,
4938
+ dispose,
4939
+ /** @internal test helper */
4940
+ _dispatch: dispatch
4941
+ };
4942
+ }