@callimacus/thamyr-liquid 4.31.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.core.md CHANGED
@@ -3,6 +3,24 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ ## [5.0.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.31.1...thamyr-core-v5.0.0) (2026-11-13)
7
+
8
+
9
+ ### ⚠ BREAKING CHANGES
10
+
11
+ * analytics refactor ([#892](https://github.com/callimacus/thamyr-sdk/issues/892))
12
+
13
+ ### Features
14
+
15
+ * analytics refactor ([#892](https://github.com/callimacus/thamyr-sdk/issues/892)) ([ac36d45](https://github.com/callimacus/thamyr-sdk/commit/ac36d452124a6f2511c18325b916d8e6445b08f0))
16
+
17
+ ## [4.31.1](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.31.0...thamyr-core-v4.31.1) (2026-11-12)
18
+
19
+
20
+ ### Bug Fixes
21
+
22
+ * **core:** transformImageUrl writes base64 the CDN reads, in every browser (CAL-1826, CAL-1804) ([#922](https://github.com/callimacus/thamyr-sdk/issues/922)) ([945c74c](https://github.com/callimacus/thamyr-sdk/commit/945c74ce1e8b151edd2379875cdbc6b7ec18d879))
23
+
6
24
  ## [4.31.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.30.2...thamyr-core-v4.31.0) (2026-11-12)
7
25
 
8
26
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## [5.0.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.31.1...thamyr-liquid-v5.0.0) (2026-11-13)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * analytics refactor ([#892](https://github.com/callimacus/thamyr-sdk/issues/892))
9
+
10
+ ### Features
11
+
12
+ * analytics refactor ([#892](https://github.com/callimacus/thamyr-sdk/issues/892)) ([ac36d45](https://github.com/callimacus/thamyr-sdk/commit/ac36d452124a6f2511c18325b916d8e6445b08f0))
13
+
14
+
15
+ ### Dependencies
16
+
17
+ * The following workspace dependencies were updated
18
+ * dependencies
19
+ * @callimacus/thamyr-core bumped from ^4.31.1 to ^5.0.0
20
+
21
+ ## [4.31.1](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.31.0...thamyr-liquid-v4.31.1) (2026-11-12)
22
+
23
+
24
+ ### Miscellaneous Chores
25
+
26
+ * **thamyr-liquid:** Synchronize thamyr versions
27
+
28
+
29
+ ### Dependencies
30
+
31
+ * The following workspace dependencies were updated
32
+ * dependencies
33
+ * @callimacus/thamyr-core bumped from ^4.31.0 to ^4.31.1
34
+
3
35
  ## [4.31.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-liquid-v4.30.2...thamyr-liquid-v4.31.0) (2026-11-12)
4
36
 
5
37
 
package/MIGRATION.md CHANGED
@@ -2,11 +2,11 @@
2
2
 
3
3
  This file ships inside every `@solomei-ai/thamyr*` package; the same guide is published at [docs.callimacus.ai/thamyr-sdk/8-migration](https://docs.callimacus.ai/thamyr-sdk/8-migration) (Callimacus account required). It covers every break since 1.x; release-by-release detail is in `CHANGELOG.md` (this package) and, in the framework packages, `CHANGELOG.core.md` (the contract and types — in `@solomei-ai/thamyr-core` that is `CHANGELOG.md` itself).
4
4
 
5
- **The wire protocol has not changed since v1.** Any major talks to the same server, so upgrading is an exercise you can schedule: bump, run your type checker, work through the errors. Every signature change is compile-time; three things are not — error handling, retries, and since 4.0.2 the constructor rejecting an empty or relative `endpoint` — so read [Error handling](#error-handling) and [`endpoint` must be an absolute URL](#endpoint-must-be-an-absolute-url-402) before you start.
5
+ **The wire protocol has not changed since v1;** v5 only adds to it: it sends events of its own and three optional fields — see [Migrating to v5](#migrating-to-v5). Any major talks to the same server, so upgrading is an exercise you can schedule: bump, run your type checker, work through the errors. Every signature change is compile-time; three things are not — error handling, retries, and since 4.0.2 the constructor rejecting an empty or relative `endpoint` — so read [Error handling](#error-handling) and [`endpoint` must be an absolute URL](#endpoint-must-be-an-absolute-url-402) before you start.
6
6
 
7
7
  ## Coming from v1
8
8
 
9
- Sites still on 1.x (the last 1.x release is 1.8.2) cross three majors at once. Work through the errors in this order:
9
+ Sites still on 1.x (the last 1.x release is 1.8.2) cross four majors at once. Work through the errors in this order:
10
10
 
11
11
  1. **`@solomei-ai/common` imports.** The package left the dependency tree in v2.0.0; every wire type and enum a client needs is exported by `@solomei-ai/thamyr`. One rewrite — see [`@solomei-ai/common` is no longer a dependency](#solomei-aicommon-is-no-longer-a-dependency). Imports from `@solomei-ai/thamyr-core` keep working (`@solomei-ai/thamyr` re-exports all of it), but declare the package or import from `@solomei-ai/thamyr` instead of relying on hoisting.
12
12
  2. **`accessToken` → `clientId`** on the constructor / `useInitThamyr` — see [Initialization](#initialization-accesstoken--clientid).
@@ -16,14 +16,15 @@ Sites still on 1.x (the last 1.x release is 1.8.2) cross three majors at once. W
16
16
  6. **Protocol enums are `as const` objects.** Runtime values are unchanged; `Enum.member` in a type position becomes `typeof Enum.member` — see [Protocol enums](#protocol-enums-are-as-const-objects).
17
17
  7. **Salesforce `c_*` attributes and media extras are `unknown`** on `Basket`, on each `ProductItem` and on `Image.properties.cloudinary` — declare your shapes once, see [Custom attributes](#custom-attributes-are-unknown).
18
18
  8. **v4:** `skesis.*` takes a parameters object and resolves the envelope; `products.*` is deprecated but stays; `endpoint` must be an absolute URL; `Basket.basketId` is required — see [Migrating to v4](#migrating-to-v4).
19
- 9. **Ride-along:** `@solomei-ai/intent` moves to 2.1.2 or later — see [Intent SDK 2.1.2 rides along](#intent-sdk-212-rides-along).
20
- 10. **Deploy:** if your build copies `VITE_*` variables into `.env`, delete those lines — see [`endpoint` must be an absolute URL](#endpoint-must-be-an-absolute-url-402).
19
+ 9. **v5:** nothing to change in your code; the SDK now records page views, opens of the items in the assistant's answers, adds to cart and the custom events your markup names on its own, see [Migrating to v5](#migrating-to-v5).
20
+ 10. **Ride-along:** `@solomei-ai/intent` moves to 2.1.2 or later — see [Intent SDK 2.1.2 rides along](#intent-sdk-212-rides-along).
21
+ 11. **Deploy:** if your build copies `VITE_*` variables into `.env`, delete those lines — see [`endpoint` must be an absolute URL](#endpoint-must-be-an-absolute-url-402).
21
22
 
22
23
  Dependencies your build scripts only had transitively through `@solomei-ai/common` (a `zod` import in a script, for instance) disappear too — declare them yourself.
23
24
 
24
- The call sites a storefront on 1.x most often has, v1 → v4 in one hop:
25
+ The call sites a storefront on 1.x most often has, v1 → v5 in one hop:
25
26
 
26
- | v1 | v4 |
27
+ | v1 | v5 |
27
28
  | --- | --- |
28
29
  | `const basket = await thamyr.cart.getCart()` | `const {data: basket, error, response} = await thamyr.cart.getCart()` |
29
30
  | `thamyr.cart.addItemToCart(id)` | `thamyr.cart.addItemToCart({productId: id})` — same envelope; `removeItemFromCart` and `updateProductQuantity({productId, quantity})` alike |
@@ -31,10 +32,40 @@ The call sites a storefront on 1.x most often has, v1 → v4 in one hop:
31
32
  | `thamyr.products.getSimilarProducts(sku, 50)` | `const {data} = await thamyr.products.getSimilar({productId: sku, topK: 50})` — deprecated in v4 but kept, see [below](#products-is-deprecated--and-stays-through-4x) |
32
33
  | `thamyr.products.getRecommendations(sku)` | `const {data} = await thamyr.products.getRecommendations({productId: sku})` |
33
34
  | `thamyr.getWhisper(storyId)` | `const {data, response} = await thamyr.whisper.getLast({storyId})` → `data?.whisper`; `response?.status === 404` means none yet |
34
- | `thamyr.analytics.trackEvent(storyId, name, content, payload)` | `void thamyr.analytics.trackEvent({storyId, eventName: name, content, payload})` — `content` is a `string` |
35
+ | `thamyr.analytics.trackEvent(storyId, name, content, payload)` | `void thamyr.analytics.trackEvent({storyId, eventName: name, content, payload})` — `content` is a `string`; kept within the [custom events' limits](#custom-events) |
35
36
 
36
37
  Prefer keeping v1's "resolve the payload, reject on failure" contract at your call sites? Pass `{throwOnError: true}` to the call: `const {data: basket} = await thamyr.cart.getCart({throwOnError: true})` is a `Basket` or a rejection, and from 4.1.0 the rejection is a `ThamyrHttpError` carrying `status` — see [Error handling](#error-handling). Under that option a 404 (the whisper row's "none yet") rejects with `status === 404`, and a fire-and-forget `void trackEvent(...)` needs a `.catch`.
37
38
 
39
+ # Migrating to v5
40
+
41
+ **Breaking in:** v5.0.0, for all six packages together. No call is removed and no signature changes: moving to v5 is a version bump. What changes is what your site sends at run time, since v5 records events on its own: see [v5 records events on its own](#v5-records-events-on-its-own).
42
+
43
+ - **`trackEvent` stays.** `thamyr.analytics.trackEvent(...)` (vanilla) and `api.analytics.trackEvent(...)` (react, from `useApi()`) send a custom event, as on 4.x. Callimacus keeps it when its name and fields fit the [custom events' limits](#custom-events), and refuses and counts it when not; the call resolves the same either way.
44
+ - **The chat's adds to cart go through the collector.** After an add from the chat, v5 records an `added_to_cart` with its round instead of calling `trackEvent` with `shopify_cart_add` or `woocommerce_cart_add`. `useShopifyCartNotices()` and the notices' `outcome` are unchanged.
45
+ - **A new `events` namespace.** The contract's `POST /api/v3/events` operation is generated like every other: `thamyr.events.collect({eventBatch})` (vanilla) and `api.events.collect({eventBatch})` (react, from `useApi()`). It is the door the SDK's own collector posts to; you have no need to call it.
46
+ - **Three optional wire fields.** The socket's handshake says `recordsPageViews: true` while the SDK records the page's views (or the Shopify loader recorded the load's), so Callimacus records none of its own for that socket. A round's `context.pageViewId` names the page view it was asked on, so its facts join that page's visit. A round's `inputEvent.data` may carry `trigger`: `suggested` for a question the visitor clicked (offered by the assistant or by the site), `site` for a round the page sent on its own. Only the analytics reads it. The SDK sets both; a round you build yourself may set `trigger` too, as a starter chip would: `sendEvent('create-round', {inputEvent: {type: 'question', data: {value, trigger: 'suggested'}}})`.
47
+ - **A site still on 4.x keeps working.** Its `trackEvent` calls are kept as custom events within the limits, and its chat's adds to cart are counted.
48
+
49
+ ## v5 records events on its own
50
+
51
+ With no call from your code, v5 records page views, opens of the items the assistant's answers showed, and adds to cart, each naming the round it came from, and the custom events your markup names:
52
+
53
+ - **React** (from `useInitThamyr`): a page view for the load and one for each route change, an open for a `link` action that names a product and its round, an add to cart for a `cart` action or a chat cart command that went through, and the custom events of the page's markup. To see route changes it wraps `history.pushState` and `history.replaceState` and listens to `popstate`, so a client-side router is seen with no setup. Events wait three seconds for others and go in one batch, so a route change costs about one request.
54
+ - **React Native**: adds to cart only; there are no pages.
55
+ - **Liquid**: an add to cart made from a round's renderer, and the custom events of the page's markup. The round a section opens with on its own (`data-interaction`, `data-prompt`) is marked as the site's; `data-landing` needs no mark, since Callimacus counts every landing as the site's.
56
+ - **The Shopify app embed**: page views, opens from its cards, adds from its cards and from the chat, and the custom events of the theme's markup.
57
+ - **Vanilla** (`@callimacus/thamyr`): nothing on its own.
58
+
59
+ React, React Native and Liquid declare adds to cart with the first one, so a site with no cart never shows cart numbers; the Shopify embed declares them on every page, since every store has a cart. Custom events are declared with the first one. A question from an `ask` action is marked `suggested`.
60
+
61
+ React, React Native and Liquid send to `POST {endpoint}/api/v3/events`, with the client id in the header and `credentials: 'include'`, so the browser sends the cookies it holds for the API's domain (a Callimacus Studio session cookie marks the traffic as internal). As the page hides, what is left goes by `navigator.sendBeacon` (a keepalive fetch where there is none), with the client id inside a `text/plain` body. The Shopify app embed sends to the store's App Proxy (`<proxy path>/events`), on the store's own origin. Recording writes no cookie and nothing to storage. A failed batch is tried three more times; after a 429 the next try waits for the response's `Retry-After`, else a minute.
62
+
63
+ ## Custom events
64
+
65
+ - **From markup** (React, Liquid, the Shopify embed): `<button data-callimacus-event="newsletter_signup" data-callimacus-event-plan="pro">` sends `newsletter_signup` with `{plan: 'pro'}` when it is clicked. Each field is an attribute's name after `data-callimacus-event-`, as written: `data-callimacus-event-item_id="sku-123"` is `item_id`, which ties the event to an item an answer showed. HTML lowercases attribute names, so a markup field always arrives in lower case (`data-callimacus-event-itemId` is `itemid`). Values are sent as text, and an attribute with no value is no field. The event names the round of a non-empty `data-callimacus-round` on the element or an ancestor, else the round shown around it (a Shopify chapter, a Liquid section), else the newest round of the runtime that owns that part of the page. Several runtimes on one page (the Shopify embed and a Liquid section) send each event once, through the runtime whose part of the page it is in.
66
+ - **From code**: `trackEvent({storyId, eventName, content?, payload?})`. `content` is the field `content`; numbers and booleans in `payload` stay numbers and booleans.
67
+ - **The limits.** A name of at most 40 letters, digits or `_`, starting with a letter, in any case (`productClick` and `newsletter_signup` both pass), never a built-in event's name in any case. A name keeps at most 10 fields over its whole life, named the same way; `item_id` is the field that ties an event to an item an answer showed. Each value a finite number, a boolean, or a code of at most 128 letters, digits, `_`, `-`, `.`, `:` or `/`, which holds an item's id as answers show it (`shopify:product:gid://shopify/Product/1`): no spaces and no `@`, so no sentence or email address fits. A field's type is fixed when that field first arrives, and a project has at most 100 names. Free text and anything else outside the limits is refused and counted: the SDK drops a markup event before it is sent and counts it as dropped; Callimacus refuses a `trackEvent` call and counts it, and still answers it with 204, so the call resolves the same either way.
68
+
38
69
  # Migrating to v4
39
70
 
40
71
  v4.0.0 (2026-09-02) re-vendors the current platform contract, with follow-ups in 4.0.1, 4.0.2 and 4.0.3 (2026-09-03). The wire protocol is unchanged — a v3 SDK and a v4 SDK speak to the same server identically; everything below is compile-time, with one exception: since 4.0.2 the constructor throws at startup on an empty or relative `endpoint` that earlier versions accepted (see below).
package/README.md CHANGED
@@ -13,10 +13,10 @@ Load the self-contained browser bundle — it auto-mounts every
13
13
  `[data-callimacus]` element and re-mounts on `shopify:section:load`:
14
14
 
15
15
  ```liquid
16
- <script src="https://cdn.jsdelivr.net/npm/@callimacus/thamyr-liquid@4/dist/browser/callimacus-runtime.min.js" defer></script>
16
+ <script src="https://cdn.jsdelivr.net/npm/@callimacus/thamyr-liquid@5/dist/browser/callimacus-runtime.min.js" defer></script>
17
17
  ```
18
18
 
19
- The floating `@4` picks up minor and patch releases automatically. If you prefer
19
+ The floating `@5` picks up minor and patch releases automatically. If you prefer
20
20
  integrity over auto-updates, pin an exact version and add
21
21
  [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)
22
22
  (`integrity="sha384-…" crossorigin="anonymous"`) — jsdelivr shows the hash on
@@ -74,6 +74,15 @@ A section opens with one round, declared in its markup:
74
74
  `data-interaction-payload`) sends a declared interaction; `data-landing` opens
75
75
  the custom landing (`data-landing="pdp"` sends `pdp` as its value); `data-prompt`
76
76
  asks a question. Name several and the first in that order wins, with a warning.
77
+ The round a section opens with this way is its own, not the visitor's, and the
78
+ analytics counts it so.
79
+
80
+ Any clickable element with `data-callimacus-event="event_name"` records the
81
+ theme's own event when clicked, with a field for each
82
+ `data-callimacus-event-<field>` attribute with a value (`data-callimacus-event-item_id`
83
+ is `item_id`; HTML lowercases attribute names, so fields arrive in lower case)
84
+ and the round its section shows, else the newest round a section rendered. The
85
+ limits are in MIGRATION.md, Custom events.
77
86
 
78
87
  ## Suggestions
79
88
 
@@ -10,7 +10,7 @@
10
10
  * Socket.IO v4.8.4
11
11
  * (c) 2014-2026 Guillermo Rauch
12
12
  * Released under the MIT License.
13
- */const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach(s=>{e[t[s]]=s});const s={type:"error",data:"parser error"},n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:s},o,c)=>n&&s instanceof Blob?o?c(s):a(s,c):i&&(s instanceof ArrayBuffer||r(s))?o?c(s):a(new Blob([s]),c):c(t[e]+(s||"")),a=(t,e)=>{const s=new FileReader;return s.onload=function(){const t=s.result.split(",")[1];e("b"+(t||""))},s.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let h;const u="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)u["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const d="function"==typeof ArrayBuffer,l=(t,n)=>{if("string"!=typeof t)return{type:"message",data:f(t,n)};const i=t.charAt(0);return"b"===i?{type:"message",data:p(t.substring(1),n)}:e[i]?t.length>1?{type:e[i],data:t.substring(1)}:{type:e[i]}:s},p=(t,e)=>{if(d){const s=(t=>{let e,s,n,i,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),d=new Uint8Array(h);for(e=0;e<a;e+=4)s=u[t.charCodeAt(e)],n=u[t.charCodeAt(e+1)],i=u[t.charCodeAt(e+2)],r=u[t.charCodeAt(e+3)],d[c++]=s<<2|n>>4,d[c++]=(15&n)<<4|i>>2,d[c++]=(3&i)<<6|63&r;return h})(t);return f(s,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,y=String.fromCharCode(30);function m(){return new TransformStream({transform(t,e){!function(t,e){n&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):i&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):o(t,!1,t=>{h||(h=new TextEncoder),e(h.encode(t))})}(t,s=>{const n=s.length;let i;if(n<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,n);else if(n<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,n)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(n))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(s)})}})}let g;function b(t){return t.reduce((t,e)=>t+e.length,0)}function v(t,e){if(t[0].length===e)return t.shift();const s=new Uint8Array(e);let n=0;for(let i=0;i<e;i++)s[i]=t[0][n++],n===t[0].length&&(t.shift(),n=0);return t.length&&n<t[0].length&&(t[0]=t[0].slice(n)),s}function w(t){if(t)return function(t){for(var e in w.prototype)t[e]=w.prototype[e];return t}(t)}w.prototype.on=w.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},w.prototype.once=function(t,e){function s(){this.off(t,s),e.apply(this,arguments)}return s.fn=e,this.on(t,s),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var s,n=this.t["$"+t];if(!n)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var i=0;i<n.length;i++)if((s=n[i])===e||s.fn===e){n.splice(i,1);break}return 0===n.length&&delete this.t["$"+t],this},w.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),s=this.t["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(s){n=0;for(var i=(s=s.slice(0)).length;n<i;++n)s[n].apply(this,e)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},w.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(t,...e){return e.reduce((e,s)=>(t.hasOwnProperty(s)&&(e[s]=t[s]),e),{})}const O=R.setTimeout,T=R.clearTimeout;function A(t,e){e.useNativeTimers?(t.setTimeoutFn=O.bind(R),t.clearTimeoutFn=T.bind(R)):(t.setTimeoutFn=R.setTimeout.bind(R),t.clearTimeoutFn=R.clearTimeout.bind(R))}function S(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}let C=class extends Error{constructor(t,e,s){super(t),this.description=e,this.context=s,this.type="TransportError"}};class N extends w{constructor(t){super(),this.writable=!1,A(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,s){return super.emitReserved("error",new C(t,e,s)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=l(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this.i()+this.o()+this.opts.path+this.h(e)}i(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}o(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}h(t){const e=function(t){let e="";for(let s in t)t.hasOwnProperty(s)&&(e.length&&(e+="&"),e+=encodeURIComponent(s)+"="+encodeURIComponent(t[s]));return e}(t);return e.length?"?"+e:""}}class B extends N{constructor(){super(...arguments),this.u=!1}get name(){return"polling"}doOpen(){this.l()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.u||!this.writable){let t=0;this.u&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}l(){this.u=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const s=t.split(y),n=[];for(let t=0;t<s.length;t++){const i=l(s[t],e);if(n.push(i),"error"===i.type)break}return n})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this.u=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.l())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const s=t.length,n=new Array(s);let i=0;t.forEach((t,r)=>{o(t,!1,t=>{n[r]=t,++i===s&&e(n.join(y))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=S()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let x=!1;try{x="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const I=x;function U(){}class L extends B{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let s=location.port;s||(s=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port}}doWrite(t,e){const s=this.request({method:"POST",data:t});s.on("success",e),s.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}let j=class t extends w{constructor(t,e,s){super(),this.createRequest=t,A(this,s),this.p=s,this.v=s.method||"GET",this.m=e,this.k=void 0!==s.data?s.data:null,this.A()}A(){var e;const s=E(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");s.xdomain=!!this.p.xd;const n=this.O=this.createRequest(s);try{n.open(this.v,this.m,!0);try{if(this.p.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this.p.extraHeaders[t])}}catch(e){}if("POST"===this.v)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}try{n.setRequestHeader("Accept","*/*")}catch(e){}null===(e=this.p.cookieJar)||void 0===e||e.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(n.timeout=this.p.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof n.status?n.status:0)},0))},n.send(this.k)}catch(e){return void this.setTimeoutFn(()=>{this.j(e)},0)}"undefined"!=typeof document&&(this.B=t.requestsCount++,t.requests[this.B]=this)}j(t){this.emitReserved("error",t,this.O),this.C(!0)}C(e){if(void 0!==this.O&&null!==this.O){if(this.O.onreadystatechange=U,e)try{this.O.abort()}catch(e){}"undefined"!=typeof document&&delete t.requests[this.B],this.O=null}}_(){const t=this.O.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.C())}abort(){this.C()}};function $(){for(let t in j.requests)j.requests.hasOwnProperty(t)&&j.requests[t].abort()}j.requestsCount=0,j.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",$):"function"==typeof addEventListener&&addEventListener("onpagehide"in R?"pagehide":"unload",$,!1));const _=function(){const t=D({xdomain:!1});return t&&null!==t.responseType}();function D(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||I))return new XMLHttpRequest}catch(t){}if(!e)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const q="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class M extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,s=q?{}:E(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(s.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,s)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws.T.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;o(s,this.supportsBinary,t=>{try{this.doWrite(s,t)}catch(t){}n&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=S()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}}const P=R.WebSocket||R.MozWebSocket;const V={websocket:class extends M{createSocket(t,e,s){return q?new P(t,e,s):e?new P(t,e):new P(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this.N=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this.N.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.N.ready.then(()=>{this.N.createBidirectionalStream().then(t=>{const e=function(t,e){g||(g=new TextDecoder);const n=[];let i=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(n.push(a);;){if(0===i){if(b(n)<1)break;const t=v(n,1);o=!(128&~t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(b(n)<2)break;const t=v(n,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(b(n)<8)break;const t=v(n,8),e=new DataView(t.buffer,t.byteOffset,t.length),o=e.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(s);break}r=o*Math.pow(2,32)+e.getUint32(4),i=3}else{if(b(n)<r)break;const t=v(n,r);c.enqueue(l(o?t:g.decode(t),e)),i=0}if(0===r||r>t){c.enqueue(s);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=t.readable.pipeThrough(e).getReader(),i=m();i.readable.pipeTo(t.writable),this.U=i.writable.getWriter();const r=()=>{n.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.U.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const s=t[e],n=e===t.length-1;this.U.write(s).then(()=>{n&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends L{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=_&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new j(D,this.uri(),t)}}},F=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,s=t.indexOf("["),n=t.indexOf("]");-1!=s&&-1!=n&&(t=t.substring(0,s)+t.substring(s,n).replace(/:/g,";")+t.substring(n,t.length));let i=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=i[o]||"";return-1!=s&&-1!=n&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const s=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||s.splice(0,1),"/"==e.slice(-1)&&s.splice(s.length-1,1),s}(0,r.path),r.queryKey=function(t,e){const s={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,n){e&&(s[e]=n)}),s}(0,r.query),r}const W="function"==typeof addEventListener&&"function"==typeof removeEventListener,z=[];W&&addEventListener("offline",()=>{z.forEach(t=>t())},!1);class Y extends w{constructor(t,e={}){var s,n;if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this.P=0,this.D=[],this.M=-1,this.S=-1,this.L=-1,this.R=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const s=K(t);e.hostname=s.host,e.secure="https"===s.protocol||"wss"===s.protocol,e.port=s.port,s.query&&(e.query=s.query)}else e.host&&(e.hostname=K(e.host).host);if(A(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),e.transportImplementations&&e.transports)throw new Error("specifying both 'transportImplementations' and 'transports' options is not supported");e.transportImplementations||(null===(s=e.transports)||void 0===s?void 0:s.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(n=e.transportImplementations)&&void 0!==n?n:e.transports).forEach(t=>{const e=t.prototype.name;this.transports.push(e),this.I[e]=t})):(this.transports=e.transports?[...e.transports]:["polling","websocket","webtransport"],this.I=V),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},s=t.split("&");for(let t=0,n=s.length;t<n;t++){let n=s[t].split("=");e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e}(this.opts.query)),W&&(this.opts.closeOnBeforeunload&&(this.F=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.F,!1)),"localhost"!==this.hostname&&(this.$=()=>{this.V("transport close",{description:"network connection lost"})},z.push(this.$))),this.opts.withCredentials&&(this.W=void 0),this.q()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const s=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this.I[t](s)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&Y.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.H.bind(this)).on("packet",this.X.bind(this)).on("error",this.j.bind(this)).on("close",t=>this.V("transport close",t))}J(t){let e=this.createTransport(t),s=!1;Y.priorWebsocketSuccess=!1;const n=()=>{s||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!s)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;Y.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{s||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){s||(s=!0,h(),e.close(),e=null)}const r=t=>{const s=new Error("probe error: "+t);s.transport=e.name,i(),this.emitReserved("upgradeError",s)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",n),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",n),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{s||e.open()},200):e.open()}onOpen(){if(this.readyState="open",Y.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this.D.length;t++)this.J(this.D[t])}X(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.G("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this.K();break;case"error":const e=new Error("server error");e.code=t.data,this.j(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.D=this.Y(t.upgrades),this.M=t.pingInterval,this.S=t.pingTimeout,this.L=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.K()}K(){this.clearTimeoutFn(this.Z);const t=this.M+this.S;this.R=Date.now()+t,this.Z=this.setTimeoutFn(()=>{this.V("ping timeout")},t),this.opts.autoUnref&&this.Z.unref()}H(){this.writeBuffer.splice(0,this.P),this.P=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.tt();this.transport.send(t),this.P=t.length,this.emitReserved("flush")}}tt(){if(!(this.L&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let s=0;s<this.writeBuffer.length;s++){const n=this.writeBuffer[s].data;if(n&&(t+="string"==typeof(e=n)?function(t){let e=0,s=0;for(let n=0,i=t.length;n<i;n++)e=t.charCodeAt(n),e<128?s+=1:e<2048?s+=2:e<55296||e>=57344?s+=3:(n++,s+=4);return s}(e):Math.ceil(1.33*(e.byteLength||e.size))),s>0&&t>this.L)return this.writeBuffer.slice(0,s);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,k(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,s){return this.G("message",t,e,s),this}send(t,e,s){return this.G("message",t,e,s),this}G(t,e,s,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof s&&(n=s,s=null),"closing"===this.readyState||"closed"===this.readyState)return;(s=s||{}).compress=!1!==s.compress;const i={type:t,data:e,options:s};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),n&&this.once("flush",n),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},s=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?s():t()}):this.upgrading?s():t()),this}j(t){if(Y.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this.q();this.emitReserved("error",t),this.V("transport error",t)}V(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this.Z),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),W&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=z.indexOf(this.$);-1!==t&&z.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.P=0}}Y(t){const e=[];for(let s=0;s<t.length;s++)~this.transports.indexOf(t[s])&&e.push(t[s]);return e}}Y.protocol=4;const J="function"==typeof ArrayBuffer,G=Object.prototype.toString,X="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===G.call(Blob),Z="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===G.call(File);function Q(t){return J&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||X&&t instanceof Blob||Z&&t instanceof File}function tt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,s=t.length;e<s;e++)if(tt(t[e]))return!0;return!1}if(Q(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return tt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&tt(t[e]))return!0;return!1}function et(t){const e=[],s=t.data,n=t;return n.data=st(s,e),n.attachments=e.length,{packet:n,buffers:e}}function st(t,e,s){if(!t)return t;if(Q(t)){const s={_placeholder:!0,num:e.length};return e.push(t),s}if(Array.isArray(t)){const s=new Array(t.length);for(let n=0;n<t.length;n++)s[n]=st(t[n],e);return s}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!s)return st(t.toJSON(),e,!0);const n={};for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=st(t[s],e));return n}return t}function nt(t,e){return t.data=it(t.data,e),delete t.attachments,t}function it(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]=it(t[s],e);else if("object"==typeof t)for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(t[s]=it(t[s],e));return t}const rt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ot;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(ot||(ot={}));class at extends w{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const s=e.type===ot.BINARY_EVENT;s||e.type===ot.BINARY_ACK?(e.type=s?ot.EVENT:ot.ACK,this.reconstructor=new ct(e)):super.emitReserved("decoded",e)}else{if(!Q(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const s={type:Number(t.charAt(0))};if(void 0===ot[s.type])throw new Error("unknown packet type "+s.type);if(s.type===ot.BINARY_EVENT||s.type===ot.BINARY_ACK){const n=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(n,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(i);if(!ht(r)||r<1)throw new Error("Illegal attachments");if(r>this.opts.maxAttachments)throw new Error("too many attachments");s.attachments=r}if("/"===t.charAt(e+1)){const n=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);s.nsp=t.substring(n,e)}else s.nsp="/";const n=t.charAt(e+1);if(""!==n&&Number(n)==n){const n=e+1;for(;++e;){const s=t.charAt(e);if(null==s||Number(s)!=s){--e;break}if(e===t.length)break}s.id=Number(t.substring(n,e+1))}if(t.charAt(++e)){const n=this.tryParse(t.substr(e));if(!at.isPayloadValid(s.type,n))throw new Error("invalid payload");s.data=n}return s}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ot.CONNECT:return ut(e);case ot.DISCONNECT:return void 0===e;case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);case ot.EVENT:case ot.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:case ot.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ct{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=nt(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ht=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function ut(t){return"[object Object]"===Object.prototype.toString.call(t)}var dt=Object.freeze({__proto__:null,protocol:5,get PacketType(){return ot},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ot.EVENT&&t.type!==ot.ACK||!tt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ot.EVENT?ot.BINARY_EVENT:ot.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ot.BINARY_EVENT&&t.type!==ot.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=et(t),s=this.encodeAsString(e.packet),n=e.buffers;return n.unshift(s),n}},Decoder:at,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||ht(e))&&function(t,e){switch(t){case ot.CONNECT:return void 0===e||ut(e);case ot.DISCONNECT:return void 0===e;case ot.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:return Array.isArray(e);case ot.CONNECT_ERROR:return"string"==typeof e||ut(e);default:return!1}}(t.type,t.data);var e}});function lt(t,e,s){return t.on(e,s),function(){t.off(e,s)}}const pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ft extends w{constructor(t,e,s){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this.et=[],this.nt=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,s&&s.auth&&(this.auth=s.auth),this.p=Object.assign({},s),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lt(t,"open",this.onopen.bind(this)),lt(t,"packet",this.onpacket.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io.ot||this.io.open(),"open"===this.io.ht&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var s,n,i;if(pt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this.p.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this.ct(e),this;const r={type:ot.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,s=e.pop();this.ut(t,s),r.id=t}const o=null===(n=null===(s=this.io.engine)||void 0===s?void 0:s.transport)||void 0===n?void 0:n.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i.st());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}ut(t,e){var s;const n=null!==(s=this.flags.timeout)&&void 0!==s?s:this.p.ackTimeout;if(void 0===n)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},n),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((s,n)=>{const i=(t,e)=>t?n(t):s(e);i.withError=!0,e.push(i),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const s={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...n)=>(this.et[0],null!==t?s.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...n)),s.pending=!1,this.ft())),this.et.push(s),this.ft()}ft(t=!1){if(!this.connected||0===this.et.length)return;const e=this.et[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io.lt(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this.dt(t)}):this.dt(this.auth)}dt(t){this.packet({type:ot.CONNECT,data:this.yt?Object.assign({pid:this.yt,offset:this.bt},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this.wt()}wt(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ot.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):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/)"));break;case ot.EVENT:case ot.BINARY_EVENT:this.onevent(t);break;case ot.ACK:case ot.BINARY_ACK:this.onack(t);break;case ot.DISCONNECT:this.ondisconnect();break;case ot.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this.gt&&this.gt.length){const e=this.gt.slice();for(const s of e)s.apply(this,t)}super.emit.apply(this,t),this.yt&&t.length&&"string"==typeof t[t.length-1]&&(this.bt=t[t.length-1])}ack(t){const e=this;let s=!1;return function(...n){s||(s=!0,e.packet({type:ot.ACK,id:t,data:n}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this.yt===e,this.yt=e,this.connected=!0,this.emitBuffered(),this.ft(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io.vt(this)}disconnect(){return this.connected&&this.packet({type:ot.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this.gt=this.gt||[],this.gt.push(t),this}prependAny(t){return this.gt=this.gt||[],this.gt.unshift(t),this}offAny(t){if(!this.gt)return this;if(t){const e=this.gt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.gt=[];return this}listenersAny(){return this.gt||[]}onAnyOutgoing(t){return this.kt=this.kt||[],this.kt.push(t),this}prependAnyOutgoing(t){return this.kt=this.kt||[],this.kt.unshift(t),this}offAnyOutgoing(t){if(!this.kt)return this;if(t){const e=this.kt;for(let s=0;s<e.length;s++)if(t===e[s])return e.splice(s,1),this}else this.kt=[];return this}listenersAnyOutgoing(){return this.kt||[]}notifyOutgoingListeners(t){if(this.kt&&this.kt.length){const e=this.kt.slice();for(const s of e)s.apply(this,t.data)}}}function yt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}yt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),s=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+s:t-s}return 0|Math.min(t,this.max)},yt.prototype.reset=function(){this.attempts=0},yt.prototype.setMin=function(t){this.ms=t},yt.prototype.setMax=function(t){this.max=t},yt.prototype.setJitter=function(t){this.jitter=t};class mt extends w{constructor(t,e){var s;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,A(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(s=e.randomizationFactor)&&void 0!==s?s:.5),this.backoff=new yt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const n=e.parser||dt;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this.rt=!1!==e.autoConnect,this.rt&&this.open()}reconnection(t){return arguments.length?(this.At=!!t,t||(this.skipReconnect=!0),this):this.At}reconnectionAttempts(t){return void 0===t?this.Et:(this.Et=t,this)}reconnectionDelay(t){var e;return void 0===t?this.Ot:(this.Ot=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._t:(this._t=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this.jt:(this.jt=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this.Bt=t,this):this.Bt}maybeReconnectOnOpen(){!this.ot&&this.At&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this.ht.indexOf("open"))return this;this.engine=new Y(this.uri,this.opts);const e=this.engine,s=this;this.ht="opening",this.skipReconnect=!1;const n=lt(e,"open",function(){s.onopen(),t&&t()}),i=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",i);if(!1!==this.Bt){const t=this.Bt,s=this.setTimeoutFn(()=>{n(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}return this.subs.push(n),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lt(t,"ping",this.onping.bind(this)),lt(t,"data",this.ondata.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this)),lt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let s=this.nsps[t];return s?this.rt&&!s.active&&s.connect():(s=new ft(this,t,e),this.nsps[t]=s),s}vt(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this.xt()}lt(t){const e=this.encoder.encode(t);for(let s=0;s<e.length;s++)this.engine.write(e[s],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}xt(){this.skipReconnect=!0,this.ot=!1,this.onclose("forced close")}disconnect(){return this.xt()}onclose(t,e){var s;this.cleanup(),null===(s=this.engine)||void 0===s||s.close(),this.backoff.reset(),this.ht="closed",this.emitReserved("close",t,e),this.At&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this.ot||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this.Et)this.backoff.reset(),this.emitReserved("reconnect_failed"),this.ot=!1;else{const e=this.backoff.duration();this.ot=!0;const s=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t.ot=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&s.unref(),this.subs.push(()=>{this.clearTimeoutFn(s)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gt={};function bt(t,e){"object"==typeof t&&(e=t,t=void 0);const s=function(t,e="",s){let n=t;s=s||"undefined"!=typeof location&&location,null==t&&(t=s.protocol+"//"+s.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?s.protocol+t:s.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==s?s.protocol+"//"+t:"https://"+t),n=K(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port+e,n.href=n.protocol+"://"+i+(s&&s.port===n.port?"":":"+n.port),n}(t,(e=e||{}).path||"/socket.io"),n=s.source,i=s.id,r=s.path,o=gt[i]&&r in gt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(n,e):(gt[i]||(gt[i]=new mt(n,e)),a=gt[i]),s.query&&!e.query&&(e.query=s.queryKey),a.socket(s.path,e)}Object.assign(bt,{Manager:mt,Socket:ft,io:bt,connect:bt});
13
+ */const t=Object.create(null);t.open="0",t.close="1",t.ping="2",t.pong="3",t.message="4",t.upgrade="5",t.noop="6";const e=Object.create(null);Object.keys(t).forEach(n=>{e[t[n]]=n});const n={type:"error",data:"parser error"},s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),i="function"==typeof ArrayBuffer,r=t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer instanceof ArrayBuffer,o=({type:e,data:n},o,c)=>s&&n instanceof Blob?o?c(n):a(n,c):i&&(n instanceof ArrayBuffer||r(n))?o?c(n):a(new Blob([n]),c):c(t[e]+(n||"")),a=(t,e)=>{const n=new FileReader;return n.onload=function(){const t=n.result.split(",")[1];e("b"+(t||""))},n.readAsDataURL(t)};function c(t){return t instanceof Uint8Array?t:t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}let h;const d="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let t=0;t<64;t++)d["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charCodeAt(t)]=t;const u="function"==typeof ArrayBuffer,l=(t,s)=>{if("string"!=typeof t)return{type:"message",data:f(t,s)};const i=t.charAt(0);return"b"===i?{type:"message",data:p(t.substring(1),s)}:e[i]?t.length>1?{type:e[i],data:t.substring(1)}:{type:e[i]}:n},p=(t,e)=>{if(u){const n=(t=>{let e,n,s,i,r,o=.75*t.length,a=t.length,c=0;"="===t[t.length-1]&&(o--,"="===t[t.length-2]&&o--);const h=new ArrayBuffer(o),u=new Uint8Array(h);for(e=0;e<a;e+=4)n=d[t.charCodeAt(e)],s=d[t.charCodeAt(e+1)],i=d[t.charCodeAt(e+2)],r=d[t.charCodeAt(e+3)],u[c++]=n<<2|s>>4,u[c++]=(15&s)<<4|i>>2,u[c++]=(3&i)<<6|63&r;return h})(t);return f(n,e)}return{base64:!0,data:t}},f=(t,e)=>"blob"===e?t instanceof Blob?t:new Blob([t]):t instanceof ArrayBuffer?t:t.buffer,y=String.fromCharCode(30);function m(){return new TransformStream({transform(t,e){!function(t,e){s&&t.data instanceof Blob?t.data.arrayBuffer().then(c).then(e):i&&(t.data instanceof ArrayBuffer||r(t.data))?e(c(t.data)):o(t,!1,t=>{h||(h=new TextEncoder),e(h.encode(t))})}(t,n=>{const s=n.length;let i;if(s<126)i=new Uint8Array(1),new DataView(i.buffer).setUint8(0,s);else if(s<65536){i=new Uint8Array(3);const t=new DataView(i.buffer);t.setUint8(0,126),t.setUint16(1,s)}else{i=new Uint8Array(9);const t=new DataView(i.buffer);t.setUint8(0,127),t.setBigUint64(1,BigInt(s))}t.data&&"string"!=typeof t.data&&(i[0]|=128),e.enqueue(i),e.enqueue(n)})}})}let g;function v(t){return t.reduce((t,e)=>t+e.length,0)}function b(t,e){if(t[0].length===e)return t.shift();const n=new Uint8Array(e);let s=0;for(let i=0;i<e;i++)n[i]=t[0][s++],s===t[0].length&&(t.shift(),s=0);return t.length&&s<t[0].length&&(t[0]=t[0].slice(s)),n}function w(t){if(t)return function(t){for(var e in w.prototype)t[e]=w.prototype[e];return t}(t)}w.prototype.on=w.prototype.addEventListener=function(t,e){return this.t=this.t||{},(this.t["$"+t]=this.t["$"+t]||[]).push(e),this},w.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},w.prototype.off=w.prototype.removeListener=w.prototype.removeAllListeners=w.prototype.removeEventListener=function(t,e){if(this.t=this.t||{},0==arguments.length)return this.t={},this;var n,s=this.t["$"+t];if(!s)return this;if(1==arguments.length)return delete this.t["$"+t],this;for(var i=0;i<s.length;i++)if((n=s[i])===e||n.fn===e){s.splice(i,1);break}return 0===s.length&&delete this.t["$"+t],this},w.prototype.emit=function(t){this.t=this.t||{};for(var e=new Array(arguments.length-1),n=this.t["$"+t],s=1;s<arguments.length;s++)e[s-1]=arguments[s];if(n){s=0;for(var i=(n=n.slice(0)).length;s<i;++s)n[s].apply(this,e)}return this},w.prototype.emitReserved=w.prototype.emit,w.prototype.listeners=function(t){return this.t=this.t||{},this.t["$"+t]||[]},w.prototype.hasListeners=function(t){return!!this.listeners(t).length};const k="function"==typeof Promise&&"function"==typeof Promise.resolve?t=>Promise.resolve().then(t):(t,e)=>e(t,0),R="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function E(t,...e){return e.reduce((e,n)=>(t.hasOwnProperty(n)&&(e[n]=t[n]),e),{})}const T=R.setTimeout,O=R.clearTimeout;function A(t,e){e.useNativeTimers?(t.setTimeoutFn=T.bind(R),t.clearTimeoutFn=O.bind(R)):(t.setTimeoutFn=R.setTimeout.bind(R),t.clearTimeoutFn=R.clearTimeout.bind(R))}function S(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class C extends Error{constructor(t,e,n){super(t),this.description=e,this.context=n,this.type="TransportError"}}class N extends w{constructor(t){super(),this.writable=!1,A(this,t),this.opts=t,this.query=t.query,this.socket=t.socket,this.supportsBinary=!t.forceBase64}onError(t,e,n){return super.emitReserved("error",new C(t,e,n)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(t){"open"===this.readyState&&this.write(t)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(t){const e=l(t,this.socket.binaryType);this.onPacket(e)}onPacket(t){super.emitReserved("packet",t)}onClose(t){this.readyState="closed",super.emitReserved("close",t)}pause(t){}createUri(t,e={}){return t+"://"+this.i()+this.o()+this.opts.path+this.h(e)}i(){const t=this.opts.hostname;return-1===t.indexOf(":")?t:"["+t+"]"}o(){return this.opts.port&&(this.opts.secure&&443!==Number(this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}h(t){const e=function(t){let e="";for(let n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e}(t);return e.length?"?"+e:""}}class I extends N{constructor(){super(...arguments),this.u=!1}get name(){return"polling"}doOpen(){this.l()}pause(t){this.readyState="pausing";const e=()=>{this.readyState="paused",t()};if(this.u||!this.writable){let t=0;this.u&&(t++,this.once("pollComplete",function(){--t||e()})),this.writable||(t++,this.once("drain",function(){--t||e()}))}else e()}l(){this.u=!0,this.doPoll(),this.emitReserved("poll")}onData(t){((t,e)=>{const n=t.split(y),s=[];for(let t=0;t<n.length;t++){const i=l(n[t],e);if(s.push(i),"error"===i.type)break}return s})(t,this.socket.binaryType).forEach(t=>{if("opening"===this.readyState&&"open"===t.type&&this.onOpen(),"close"===t.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(t)}),"closed"!==this.readyState&&(this.u=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this.l())}doClose(){const t=()=>{this.write([{type:"close"}])};"open"===this.readyState?t():this.once("open",t)}write(t){this.writable=!1,((t,e)=>{const n=t.length,s=new Array(n);let i=0;t.forEach((t,r)=>{o(t,!1,t=>{s[r]=t,++i===n&&e(s.join(y))})})})(t,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",e=this.query||{};return!1!==this.opts.timestampRequests&&(e[this.opts.timestampParam]=S()),this.supportsBinary||e.sid||(e.b64=1),this.createUri(t,e)}}let B=!1;try{B="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(t){}const x=B;function L(){}class U extends I{constructor(t){if(super(t),"undefined"!=typeof location){const e="https:"===location.protocol;let n=location.port;n||(n=e?"443":"80"),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port}}doWrite(t,e){const n=this.request({method:"POST",data:t});n.on("success",e),n.on("error",(t,e)=>{this.onError("xhr post error",t,e)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(t,e)=>{this.onError("xhr poll error",t,e)}),this.pollXhr=t}}class j extends w{constructor(t,e,n){super(),this.createRequest=t,A(this,n),this.p=n,this.v=n.method||"GET",this.m=e,this.k=void 0!==n.data?n.data:null,this.A()}A(){var t;const e=E(this.p,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");e.xdomain=!!this.p.xd;const n=this.O=this.createRequest(e);try{n.open(this.v,this.m,!0);try{if(this.p.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let t in this.p.extraHeaders)this.p.extraHeaders.hasOwnProperty(t)&&n.setRequestHeader(t,this.p.extraHeaders[t])}}catch(t){}if("POST"===this.v)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{n.setRequestHeader("Accept","*/*")}catch(t){}null===(t=this.p.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this.p.withCredentials),this.p.requestTimeout&&(n.timeout=this.p.requestTimeout),n.onreadystatechange=()=>{var t;3===n.readyState&&(null===(t=this.p.cookieJar)||void 0===t||t.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._():this.setTimeoutFn(()=>{this.j("number"==typeof n.status?n.status:0)},0))},n.send(this.k)}catch(t){return void this.setTimeoutFn(()=>{this.j(t)},0)}"undefined"!=typeof document&&(this.B=j.requestsCount++,j.requests[this.B]=this)}j(t){this.emitReserved("error",t,this.O),this.C(!0)}C(t){if(void 0!==this.O&&null!==this.O){if(this.O.onreadystatechange=L,t)try{this.O.abort()}catch(t){}"undefined"!=typeof document&&delete j.requests[this.B],this.O=null}}_(){const t=this.O.responseText;null!==t&&(this.emitReserved("data",t),this.emitReserved("success"),this.C())}abort(){this.C()}}function $(){for(let t in j.requests)j.requests.hasOwnProperty(t)&&j.requests[t].abort()}j.requestsCount=0,j.requests={},"undefined"!=typeof document&&("function"==typeof attachEvent?attachEvent("onunload",$):"function"==typeof addEventListener&&addEventListener("onpagehide"in R?"pagehide":"unload",$,!1));const _=function(){const t=M({xdomain:!1});return t&&null!==t.responseType}();function M(t){const e=t.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!e||x))return new XMLHttpRequest}catch(t){}if(!e)try{return new(R[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}const D="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();let q=class extends N{get name(){return"websocket"}doOpen(){const t=this.uri(),e=this.opts.protocols,n=D?{}:E(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(n.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(t,e,n)}catch(t){return this.emitReserved("error",t)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws.T.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;o(n,this.supportsBinary,t=>{try{this.doWrite(n,t)}catch(t){}s&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",e=this.query||{};return this.opts.timestampRequests&&(e[this.opts.timestampParam]=S()),this.supportsBinary||(e.b64=1),this.createUri(t,e)}};const V=R.WebSocket||R.MozWebSocket;const P={websocket:class extends q{createSocket(t,e,n){return D?new V(t,e,n):e?new V(t,e):new V(t)}doWrite(t,e){this.ws.send(e)}},webtransport:class extends N{get name(){return"webtransport"}doOpen(){try{this.N=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(t){return this.emitReserved("error",t)}this.N.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.N.ready.then(()=>{this.N.createBidirectionalStream().then(t=>{const e=function(t,e){g||(g=new TextDecoder);const s=[];let i=0,r=-1,o=!1;return new TransformStream({transform(a,c){for(s.push(a);;){if(0===i){if(v(s)<1)break;const t=b(s,1);o=!(128&~t[0]),r=127&t[0],i=r<126?3:126===r?1:2}else if(1===i){if(v(s)<2)break;const t=b(s,2);r=new DataView(t.buffer,t.byteOffset,t.length).getUint16(0),i=3}else if(2===i){if(v(s)<8)break;const t=b(s,8),e=new DataView(t.buffer,t.byteOffset,t.length),o=e.getUint32(0);if(o>Math.pow(2,21)-1){c.enqueue(n);break}r=o*Math.pow(2,32)+e.getUint32(4),i=3}else{if(v(s)<r)break;const t=b(s,r);c.enqueue(l(o?t:g.decode(t),e)),i=0}if(0===r||r>t){c.enqueue(n);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),s=t.readable.pipeThrough(e).getReader(),i=m();i.readable.pipeTo(t.writable),this.U=i.writable.getWriter();const r=()=>{s.read().then(({done:t,value:e})=>{t||(this.onPacket(e),r())}).catch(t=>{})};r();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this.U.write(o).then(()=>this.onOpen())})})}write(t){this.writable=!1;for(let e=0;e<t.length;e++){const n=t[e],s=e===t.length-1;this.U.write(n).then(()=>{s&&k(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;null===(t=this.N)||void 0===t||t.close()}},polling:class extends U{constructor(t){super(t);const e=t&&t.forceBase64;this.supportsBinary=_&&!e}request(t={}){return Object.assign(t,{xd:this.xd},this.opts),new j(M,this.uri(),t)}}},F=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,H=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function K(t){if(t.length>8e3)throw"URI too long";const e=t,n=t.indexOf("["),s=t.indexOf("]");-1!=n&&-1!=s&&(t=t.substring(0,n)+t.substring(n,s).replace(/:/g,";")+t.substring(s,t.length));let i=F.exec(t||""),r={},o=14;for(;o--;)r[H[o]]=i[o]||"";return-1!=n&&-1!=s&&(r.source=e,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(t,e){const n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.slice(0,1)&&0!==e.length||n.splice(0,1),"/"==e.slice(-1)&&n.splice(n.length-1,1),n}(0,r.path),r.queryKey=function(t,e){const n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,s){e&&(n[e]=s)}),n}(0,r.query),r}const W="function"==typeof addEventListener&&"function"==typeof removeEventListener,z=[];W&&addEventListener("offline",()=>{z.forEach(t=>t())},!1);class J extends w{constructor(t,e={}){var n,s;if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this.P=0,this.D=[],this.M=-1,this.S=-1,this.L=-1,this.R=1/0,t&&"object"==typeof t&&(e=t,t=null),t){const n=K(t);e.hostname=n.host,e.secure="https"===n.protocol||"wss"===n.protocol,e.port=n.port,n.query&&(e.query=n.query)}else e.host&&(e.hostname=K(e.host).host);if(A(this,e),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),e.transportImplementations&&e.transports)throw new Error("specifying both 'transportImplementations' and 'transports' options is not supported");e.transportImplementations||(null===(n=e.transports)||void 0===n?void 0:n.length)&&"function"==typeof e.transports[0]?(this.transports=[],this.I=Object.create(null),(null!==(s=e.transportImplementations)&&void 0!==s?s:e.transports).forEach(t=>{const e=t.prototype.name;this.transports.push(e),this.I[e]=t})):(this.transports=e.transports?[...e.transports]:["polling","websocket","webtransport"],this.I=P),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},e),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(t){let e={},n=t.split("&");for(let t=0,s=n.length;t<s;t++){let s=n[t].split("=");e[decodeURIComponent(s[0])]=decodeURIComponent(s[1])}return e}(this.opts.query)),W&&(this.opts.closeOnBeforeunload&&(this.F=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.F,!1)),"localhost"!==this.hostname&&(this.$=()=>{this.V("transport close",{description:"network connection lost"})},z.push(this.$))),this.opts.withCredentials&&(this.W=void 0),this.q()}createTransport(t){const e=Object.assign({},this.opts.query);e.EIO=4,e.transport=t,this.id&&(e.sid=this.id);const n=Object.assign({},this.opts,{query:e,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new this.I[t](n)}q(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const t=this.opts.rememberUpgrade&&J.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const e=this.createTransport(t);e.open(),this.setTransport(e)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.H.bind(this)).on("packet",this.X.bind(this)).on("error",this.j.bind(this)).on("close",t=>this.V("transport close",t))}J(t){let e=this.createTransport(t),n=!1;J.priorWebsocketSuccess=!1;const s=()=>{n||(e.send([{type:"ping",data:"probe"}]),e.once("packet",t=>{if(!n)if("pong"===t.type&&"probe"===t.data){if(this.upgrading=!0,this.emitReserved("upgrading",e),!e)return;J.priorWebsocketSuccess="websocket"===e.name,this.transport.pause(()=>{n||"closed"!==this.readyState&&(h(),this.setTransport(e),e.send([{type:"upgrade"}]),this.emitReserved("upgrade",e),e=null,this.upgrading=!1,this.flush())})}else{const t=new Error("probe error");t.transport=e.name,this.emitReserved("upgradeError",t)}}))};function i(){n||(n=!0,h(),e.close(),e=null)}const r=t=>{const n=new Error("probe error: "+t);n.transport=e.name,i(),this.emitReserved("upgradeError",n)};function o(){r("transport closed")}function a(){r("socket closed")}function c(t){e&&t.name!==e.name&&i()}const h=()=>{e.removeListener("open",s),e.removeListener("error",r),e.removeListener("close",o),this.off("close",a),this.off("upgrading",c)};e.once("open",s),e.once("error",r),e.once("close",o),this.once("close",a),this.once("upgrading",c),-1!==this.D.indexOf("webtransport")&&"webtransport"!==t?this.setTimeoutFn(()=>{n||e.open()},200):e.open()}onOpen(){if(this.readyState="open",J.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush(),"open"===this.readyState&&this.opts.upgrade)for(let t=0;t<this.D.length;t++)this.J(this.D[t])}X(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",t),this.emitReserved("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"ping":this.G("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this.K();break;case"error":const e=new Error("server error");e.code=t.data,this.j(e);break;case"message":this.emitReserved("data",t.data),this.emitReserved("message",t.data)}}onHandshake(t){this.emitReserved("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.D=this.Y(t.upgrades),this.M=t.pingInterval,this.S=t.pingTimeout,this.L=t.maxPayload,this.onOpen(),"closed"!==this.readyState&&this.K()}K(){this.clearTimeoutFn(this.Z);const t=this.M+this.S;this.R=Date.now()+t,this.Z=this.setTimeoutFn(()=>{this.V("ping timeout")},t),this.opts.autoUnref&&this.Z.unref()}H(){this.writeBuffer.splice(0,this.P),this.P=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.tt();this.transport.send(t),this.P=t.length,this.emitReserved("flush")}}tt(){if(!(this.L&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let n=0;n<this.writeBuffer.length;n++){const s=this.writeBuffer[n].data;if(s&&(t+="string"==typeof(e=s)?function(t){let e=0,n=0;for(let s=0,i=t.length;s<i;s++)e=t.charCodeAt(s),e<128?n+=1:e<2048?n+=2:e<55296||e>=57344?n+=3:(s++,n+=4);return n}(e):Math.ceil(1.33*(e.byteLength||e.size))),n>0&&t>this.L)return this.writeBuffer.slice(0,n);t+=2}var e;return this.writeBuffer}st(){if(!this.R)return!0;const t=Date.now()>this.R;return t&&(this.R=0,k(()=>{this.V("ping timeout")},this.setTimeoutFn)),t}write(t,e,n){return this.G("message",t,e,n),this}send(t,e,n){return this.G("message",t,e,n),this}G(t,e,n,s){if("function"==typeof e&&(s=e,e=void 0),"function"==typeof n&&(s=n,n=null),"closing"===this.readyState||"closed"===this.readyState)return;(n=n||{}).compress=!1!==n.compress;const i={type:t,data:e,options:n};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){const t=()=>{this.V("forced close"),this.transport.close()},e=()=>{this.off("upgrade",e),this.off("upgradeError",e),t()},n=()=>{this.once("upgrade",e),this.once("upgradeError",e)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?n():t()}):this.upgrading?n():t()),this}j(t){if(J.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this.q();this.emitReserved("error",t),this.V("transport error",t)}V(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this.Z),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),W&&(this.F&&removeEventListener("beforeunload",this.F,!1),this.$)){const t=z.indexOf(this.$);-1!==t&&z.splice(t,1)}this.readyState="closed",this.id=null,this.emitReserved("close",t,e),this.writeBuffer=[],this.P=0}}Y(t){const e=[];for(let n=0;n<t.length;n++)~this.transports.indexOf(t[n])&&e.push(t[n]);return e}}J.protocol=4;const Y="function"==typeof ArrayBuffer,G=Object.prototype.toString,X="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===G.call(Blob),Z="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===G.call(File);function Q(t){return Y&&(t instanceof ArrayBuffer||(t=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer)(t))||X&&t instanceof Blob||Z&&t instanceof File}function tt(t,e){if(!t||"object"!=typeof t)return!1;if(Array.isArray(t)){for(let e=0,n=t.length;e<n;e++)if(tt(t[e]))return!0;return!1}if(Q(t))return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return tt(t.toJSON(),!0);for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e)&&tt(t[e]))return!0;return!1}function et(t){const e=[],n=t.data,s=t;return s.data=nt(n,e),s.attachments=e.length,{packet:s,buffers:e}}function nt(t,e,n){if(!t)return t;if(Q(t)){const n={_placeholder:!0,num:e.length};return e.push(t),n}if(Array.isArray(t)){const n=new Array(t.length);for(let s=0;s<t.length;s++)n[s]=nt(t[s],e);return n}if("object"==typeof t&&!(t instanceof Date)){if(t.toJSON&&"function"==typeof t.toJSON&&!n)return nt(t.toJSON(),e,!0);const s={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(s[n]=nt(t[n],e));return s}return t}function st(t,e){return t.data=it(t.data,e),delete t.attachments,t}function it(t,e){if(!t)return t;if(t&&!0===t._placeholder){if("number"==typeof t.num&&t.num>=0&&t.num<e.length)return e[t.num];throw new Error("illegal attachments")}if(Array.isArray(t))for(let n=0;n<t.length;n++)t[n]=it(t[n],e);else if("object"==typeof t)for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(t[n]=it(t[n],e));return t}const rt=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var ot;!function(t){t[t.CONNECT=0]="CONNECT",t[t.DISCONNECT=1]="DISCONNECT",t[t.EVENT=2]="EVENT",t[t.ACK=3]="ACK",t[t.CONNECT_ERROR=4]="CONNECT_ERROR",t[t.BINARY_EVENT=5]="BINARY_EVENT",t[t.BINARY_ACK=6]="BINARY_ACK"}(ot||(ot={}));class at extends w{constructor(t){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},"function"==typeof t?{reviver:t}:t)}add(t){let e;if("string"==typeof t){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");e=this.decodeString(t);const n=e.type===ot.BINARY_EVENT;n||e.type===ot.BINARY_ACK?(e.type=n?ot.EVENT:ot.ACK,this.reconstructor=new ct(e)):super.emitReserved("decoded",e)}else{if(!Q(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");e=this.reconstructor.takeBinaryData(t),e&&(this.reconstructor=null,super.emitReserved("decoded",e))}}decodeString(t){let e=0;const n={type:Number(t.charAt(0))};if(void 0===ot[n.type])throw new Error("unknown packet type "+n.type);if(n.type===ot.BINARY_EVENT||n.type===ot.BINARY_ACK){const s=e+1;for(;"-"!==t.charAt(++e)&&e!=t.length;);const i=t.substring(s,e);if(i!=Number(i)||"-"!==t.charAt(e))throw new Error("Illegal attachments");const r=Number(i);if(!ht(r)||r<1)throw new Error("Illegal attachments");if(r>this.opts.maxAttachments)throw new Error("too many attachments");n.attachments=r}if("/"===t.charAt(e+1)){const s=e+1;for(;++e&&","!==t.charAt(e)&&e!==t.length;);n.nsp=t.substring(s,e)}else n.nsp="/";const s=t.charAt(e+1);if(""!==s&&Number(s)==s){const s=e+1;for(;++e;){const n=t.charAt(e);if(null==n||Number(n)!=n){--e;break}if(e===t.length)break}n.id=Number(t.substring(s,e+1))}if(t.charAt(++e)){const s=this.tryParse(t.substr(e));if(!at.isPayloadValid(n.type,s))throw new Error("invalid payload");n.data=s}return n}tryParse(t){try{return JSON.parse(t,this.opts.reviver)}catch(t){return!1}}static isPayloadValid(t,e){switch(t){case ot.CONNECT:return dt(e);case ot.DISCONNECT:return void 0===e;case ot.CONNECT_ERROR:return"string"==typeof e||dt(e);case ot.EVENT:case ot.BINARY_EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:case ot.BINARY_ACK:return Array.isArray(e)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ct{constructor(t){this.packet=t,this.buffers=[],this.reconPack=t}takeBinaryData(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){const t=st(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const ht=Number.isInteger||function(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t};function dt(t){return"[object Object]"===Object.prototype.toString.call(t)}var ut=Object.freeze({__proto__:null,protocol:5,get PacketType(){return ot},Encoder:class{constructor(t){this.replacer=t}encode(t){return t.type!==ot.EVENT&&t.type!==ot.ACK||!tt(t)?[this.encodeAsString(t)]:this.encodeAsBinary({type:t.type===ot.EVENT?ot.BINARY_EVENT:ot.BINARY_ACK,nsp:t.nsp,data:t.data,id:t.id})}encodeAsString(t){let e=""+t.type;return t.type!==ot.BINARY_EVENT&&t.type!==ot.BINARY_ACK||(e+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(e+=t.nsp+","),null!=t.id&&(e+=t.id),null!=t.data&&(e+=JSON.stringify(t.data,this.replacer)),e}encodeAsBinary(t){const e=et(t),n=this.encodeAsString(e.packet),s=e.buffers;return s.unshift(n),s}},Decoder:at,isPacketValid:function(t){return"string"==typeof t.nsp&&(void 0===(e=t.id)||ht(e))&&function(t,e){switch(t){case ot.CONNECT:return void 0===e||dt(e);case ot.DISCONNECT:return void 0===e;case ot.EVENT:return Array.isArray(e)&&("number"==typeof e[0]||"string"==typeof e[0]&&-1===rt.indexOf(e[0]));case ot.ACK:return Array.isArray(e);case ot.CONNECT_ERROR:return"string"==typeof e||dt(e);default:return!1}}(t.type,t.data);var e}});function lt(t,e,n){return t.on(e,n),function(){t.off(e,n)}}const pt=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ft extends w{constructor(t,e,n){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this.et=[],this.nt=0,this.ids=0,this.acks={},this.flags={},this.io=t,this.nsp=e,n&&n.auth&&(this.auth=n.auth),this.p=Object.assign({},n),this.io.rt&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const t=this.io;this.subs=[lt(t,"open",this.onopen.bind(this)),lt(t,"packet",this.onpacket.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io.ot||this.io.open(),"open"===this.io.ht&&this.onopen()),this}open(){return this.connect()}send(...t){return t.unshift("message"),this.emit.apply(this,t),this}emit(t,...e){var n,s,i;if(pt.hasOwnProperty(t))throw new Error('"'+t.toString()+'" is a reserved event name');if(e.unshift(t),this.p.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this.ct(e),this;const r={type:ot.EVENT,data:e,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof e[e.length-1]){const t=this.ids++,n=e.pop();this.ut(t,n),r.id=t}const o=null===(s=null===(n=this.io.engine)||void 0===n?void 0:n.transport)||void 0===s?void 0:s.writable,a=this.connected&&!(null===(i=this.io.engine)||void 0===i?void 0:i.st());return this.flags.volatile&&!o||(a?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}ut(t,e){var n;const s=null!==(n=this.flags.timeout)&&void 0!==n?n:this.p.ackTimeout;if(void 0===s)return void(this.acks[t]=e);const i=this.io.setTimeoutFn(()=>{delete this.acks[t];for(let e=0;e<this.sendBuffer.length;e++)this.sendBuffer[e].id===t&&this.sendBuffer.splice(e,1);e.call(this,new Error("operation has timed out"))},s),r=(...t)=>{this.io.clearTimeoutFn(i),e.apply(this,t)};r.withError=!0,this.acks[t]=r}emitWithAck(t,...e){return new Promise((n,s)=>{const i=(t,e)=>t?s(t):n(e);i.withError=!0,e.push(i),this.emit(t,...e)})}ct(t){let e;"function"==typeof t[t.length-1]&&(e=t.pop());const n={id:this.nt++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((t,...s)=>(this.et[0],null!==t?n.tryCount>this.p.retries&&(this.et.shift(),e&&e(t)):(this.et.shift(),e&&e(null,...s)),n.pending=!1,this.ft())),this.et.push(n),this.ft()}ft(t=!1){if(!this.connected||0===this.et.length)return;const e=this.et[0];e.pending&&!t||(e.pending=!0,e.tryCount++,this.flags=e.flags,this.emit.apply(this,e.args))}packet(t){t.nsp=this.nsp,this.io.lt(t)}onopen(){"function"==typeof this.auth?this.auth(t=>{this.dt(t)}):this.dt(this.auth)}dt(t){this.packet({type:ot.CONNECT,data:this.yt?Object.assign({pid:this.yt,offset:this.bt},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,e){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,e),this.wt()}wt(){Object.keys(this.acks).forEach(t=>{if(!this.sendBuffer.some(e=>String(e.id)===t)){const e=this.acks[t];delete this.acks[t],e.withError&&e.call(this,new Error("socket has been disconnected"))}})}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case ot.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):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/)"));break;case ot.EVENT:case ot.BINARY_EVENT:this.onevent(t);break;case ot.ACK:case ot.BINARY_ACK:this.onack(t);break;case ot.DISCONNECT:this.ondisconnect();break;case ot.CONNECT_ERROR:this.destroy();const e=new Error(t.data.message);e.data=t.data.data,this.emitReserved("connect_error",e)}}onevent(t){const e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?this.emitEvent(e):this.receiveBuffer.push(Object.freeze(e))}emitEvent(t){if(this.gt&&this.gt.length){const e=this.gt.slice();for(const n of e)n.apply(this,t)}super.emit.apply(this,t),this.yt&&t.length&&"string"==typeof t[t.length-1]&&(this.bt=t[t.length-1])}ack(t){const e=this;let n=!1;return function(...s){n||(n=!0,e.packet({type:ot.ACK,id:t,data:s}))}}onack(t){const e=this.acks[t.id];"function"==typeof e&&(delete this.acks[t.id],e.withError&&t.data.unshift(null),e.apply(this,t.data))}onconnect(t,e){this.id=t,this.recovered=e&&this.yt===e,this.yt=e,this.connected=!0,this.emitBuffered(),this.ft(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io.vt(this)}disconnect(){return this.connected&&this.packet({type:ot.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this.gt=this.gt||[],this.gt.push(t),this}prependAny(t){return this.gt=this.gt||[],this.gt.unshift(t),this}offAny(t){if(!this.gt)return this;if(t){const e=this.gt;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this.gt=[];return this}listenersAny(){return this.gt||[]}onAnyOutgoing(t){return this.kt=this.kt||[],this.kt.push(t),this}prependAnyOutgoing(t){return this.kt=this.kt||[],this.kt.unshift(t),this}offAnyOutgoing(t){if(!this.kt)return this;if(t){const e=this.kt;for(let n=0;n<e.length;n++)if(t===e[n])return e.splice(n,1),this}else this.kt=[];return this}listenersAnyOutgoing(){return this.kt||[]}notifyOutgoingListeners(t){if(this.kt&&this.kt.length){const e=this.kt.slice();for(const n of e)n.apply(this,t.data)}}}function yt(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}yt.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=1&Math.floor(10*e)?t+n:t-n}return 0|Math.min(t,this.max)},yt.prototype.reset=function(){this.attempts=0},yt.prototype.setMin=function(t){this.ms=t},yt.prototype.setMax=function(t){this.max=t},yt.prototype.setJitter=function(t){this.jitter=t};class mt extends w{constructor(t,e){var n;super(),this.nsps={},this.subs=[],t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.opts=e,A(this,e),this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(n=e.randomizationFactor)&&void 0!==n?n:.5),this.backoff=new yt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.ht="closed",this.uri=t;const s=e.parser||ut;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this.rt=!1!==e.autoConnect,this.rt&&this.open()}reconnection(t){return arguments.length?(this.At=!!t,t||(this.skipReconnect=!0),this):this.At}reconnectionAttempts(t){return void 0===t?this.Et:(this.Et=t,this)}reconnectionDelay(t){var e;return void 0===t?this.Ot:(this.Ot=t,null===(e=this.backoff)||void 0===e||e.setMin(t),this)}randomizationFactor(t){var e;return void 0===t?this._t:(this._t=t,null===(e=this.backoff)||void 0===e||e.setJitter(t),this)}reconnectionDelayMax(t){var e;return void 0===t?this.jt:(this.jt=t,null===(e=this.backoff)||void 0===e||e.setMax(t),this)}timeout(t){return arguments.length?(this.Bt=t,this):this.Bt}maybeReconnectOnOpen(){!this.ot&&this.At&&0===this.backoff.attempts&&this.reconnect()}open(t){if(~this.ht.indexOf("open"))return this;this.engine=new J(this.uri,this.opts);const e=this.engine,n=this;this.ht="opening",this.skipReconnect=!1;const s=lt(e,"open",function(){n.onopen(),t&&t()}),i=e=>{this.cleanup(),this.ht="closed",this.emitReserved("error",e),t?t(e):this.maybeReconnectOnOpen()},r=lt(e,"error",i);if(!1!==this.Bt){const t=this.Bt,n=this.setTimeoutFn(()=>{s(),i(new Error("timeout")),e.close()},t);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}return this.subs.push(s),this.subs.push(r),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this.ht="open",this.emitReserved("open");const t=this.engine;this.subs.push(lt(t,"ping",this.onping.bind(this)),lt(t,"data",this.ondata.bind(this)),lt(t,"error",this.onerror.bind(this)),lt(t,"close",this.onclose.bind(this)),lt(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(t){this.onclose("parse error",t)}}ondecoded(t){k(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,e){let n=this.nsps[t];return n?this.rt&&!n.active&&n.connect():(n=new ft(this,t,e),this.nsps[t]=n),n}vt(t){const e=Object.keys(this.nsps);for(const t of e)if(this.nsps[t].active)return;this.xt()}lt(t){const e=this.encoder.encode(t);for(let n=0;n<e.length;n++)this.engine.write(e[n],t.options)}cleanup(){this.subs.forEach(t=>t()),this.subs.length=0,this.decoder.destroy()}xt(){this.skipReconnect=!0,this.ot=!1,this.onclose("forced close")}disconnect(){return this.xt()}onclose(t,e){var n;this.cleanup(),null===(n=this.engine)||void 0===n||n.close(),this.backoff.reset(),this.ht="closed",this.emitReserved("close",t,e),this.At&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this.ot||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this.Et)this.backoff.reset(),this.emitReserved("reconnect_failed"),this.ot=!1;else{const e=this.backoff.duration();this.ot=!0;const n=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),t.skipReconnect||t.open(e=>{e?(t.ot=!1,t.reconnect(),this.emitReserved("reconnect_error",e)):t.onreconnect()}))},e);this.opts.autoUnref&&n.unref(),this.subs.push(()=>{this.clearTimeoutFn(n)})}}onreconnect(){const t=this.backoff.attempts;this.ot=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gt={};function vt(t,e){"object"==typeof t&&(e=t,t=void 0);const n=function(t,e="",n){let s=t;n=n||"undefined"!=typeof location&&location,null==t&&(t=n.protocol+"//"+n.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?n.protocol+t:n.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==n?n.protocol+"//"+t:"https://"+t),s=K(t)),s.port||(/^(http|ws)$/.test(s.protocol)?s.port="80":/^(http|ws)s$/.test(s.protocol)&&(s.port="443")),s.path=s.path||"/";const i=-1!==s.host.indexOf(":")?"["+s.host+"]":s.host;return s.id=s.protocol+"://"+i+":"+s.port+e,s.href=s.protocol+"://"+i+(n&&n.port===s.port?"":":"+s.port),s}(t,(e=e||{}).path||"/socket.io"),s=n.source,i=n.id,r=n.path,o=gt[i]&&r in gt[i].nsps;let a;return e.forceNew||e["force new connection"]||!1===e.multiplex||o?a=new mt(s,e):(gt[i]||(gt[i]=new mt(s,e)),a=gt[i]),n.query&&!e.query&&(e.query=n.queryKey),a.socket(n.path,e)}Object.assign(vt,{Manager:mt,Socket:ft,io:vt,connect:vt});
14
14
  /*!
15
15
  * Copyright © 2025–2026 Solomei AI SRL. All rights reserved.
16
16
  *
@@ -18,5 +18,5 @@
18
18
  * See LICENSE.md for the full terms.
19
19
  *
20
20
  */
21
- const vt="chapter-event",wt="story-created",kt="error",Rt="server-response",Et="client-ready",Ot="user-interaction",Tt=4,At={debug:0,info:1,warn:2,error:3,silent:4},St=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...t)=>{this.log("debug",...t)};info=(...t)=>{this.log("info",...t)};warn=(...t)=>{this.log("warn",...t)};error=(...t)=>{this.log("error",...t)};log(t,...e){if(!(this.config.enabled&&At[t]>=At[this.config.level]))return;const{prefix:s}=this.config,n=void 0===s||""===s?e:[s,...e];console[t](...n)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function Ct(){let t,e="";try{e=globalThis.location.search}catch{}try{t=localStorage}catch{}(function(t,e){if(new URLSearchParams(t).has("callimacus_debug"))return!0;try{return null!==(e?.getItem("callimacus:debug")??null)}catch{return!1}})(e,t)&&St.configure({enabled:!0,level:"warn"})}function Nt(){const t="undefined"==typeof crypto?void 0:crypto;if("function"==typeof t?.randomUUID)return t.randomUUID();const e=new Uint8Array(16);if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=[...e].map(t=>t.toString(16).padStart(2,"0"));return[s.slice(0,4).join(""),s.slice(4,6).join(""),s.slice(6,8).join(""),s.slice(8,10).join(""),s.slice(10,16).join("")].join("-")}var Bt,xt;!function(t){t.GET_STORY="get-story",t.CREATE_ROUND="create-round",t.RESET_STORY="reset-story",t.BACK_FROM_ROUND="back-from-round",t.SHARE_STORY="share-story",t.GET_SHARED_STORY="get-shared-story",t.SUGGEST="suggest"}(Bt||(Bt={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(xt||(xt={}));const It={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class Ut{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(t={}){const e=t.minVisibilityRatio??It.minVisibilityRatio;this.config={productSelector:t.productSelector??It.productSelector,blockSelector:t.blockSelector??It.blockSelector,maxTrackedElements:t.maxTrackedElements??It.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,e))}}rescanUi(){if(!this.canUseDom())return;let t,e;try{t=document.querySelectorAll(this.config.productSelector),e=document.querySelectorAll(this.config.blockSelector)}catch(t){return void St.warn("UI Observer: invalid selector, skipping rescan:",t)}const s=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),n=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:n>=this.config.minVisibilityRatio,visibilityRatio:n,observedAt:s})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),n=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:n>=this.config.minVisibilityRatio,visibilityRatio:n,observedAt:s})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[e]of t)this.elements.delete(e),this.elementRefs.delete(e)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const t=[...this.blocks].sort(([,t],[,e])=>{const s=t.visibilityRatio-e.visibilityRatio;return 0===s||Number.isNaN(s)?t.observedAt-e.observedAt:s}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[e]of t)this.blocks.delete(e),this.blockRefs.delete(e)}syncTrackedElement(t,e){const s=this.resolveElementId(t),n=this.resolveBlockId(t),i=this.createTrackingKey(s,n),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==i&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,i),this.elementRefs.set(i,t),this.elements.set(i,{id:s,blockId:n,trackingKey:i,...e})}syncTrackedBlock(t,e){const s=this.resolveTrackedBlockId(t),n=this.blockKeys.get(t),i=s;void 0!==n&&""!==n&&n!==i&&(this.blocks.delete(n),this.blockRefs.delete(n)),this.blockKeys.set(t,i),this.blockRefs.set(i,t),this.blocks.set(i,{id:s,...e})}resolveElementId(t){return[t.dataset.productId,t.dataset.productid,t.dataset.sku,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.productId??this.elements.size}`}resolveBlockId(t){let e;try{e=t.closest(this.config.blockSelector)??void 0}catch{return}return e instanceof HTMLElement?this.resolveTrackedBlockId(e):void 0}resolveTrackedBlockId(t){return[t.dataset.blockId,t.dataset.blockid,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.blockId??this.blocks.size}`}createTrackingKey(t,e){return void 0===e||""===e?t:`${t}::${e}`}normalizeRect(t){return{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,left:t.left,right:t.right,bottom:t.bottom}}calculateVisibilityRatio(t){const e=Math.max(0,Math.min(t.right,window.innerWidth)-Math.max(t.left,0))*Math.max(0,Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)),s=t.width*t.height;if(s<=0)return 0;const n=window.innerWidth*window.innerHeight,i=n>0?Math.min(s,n):s;return Math.min(1,Math.max(0,e/i))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const t=[],e=[],s=Date.now();for(const[e,s]of this.elements){const n=this.elementRefs.get(e);n?.isConnected?s.visibilityRatio<=0||t.push({blockId:s.blockId,element:{id:s.id,bounds:s.bounds,isVisible:s.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:s.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,s]of this.blocks){const n=this.blockRefs.get(t);n?.isConnected?s.visibilityRatio<this.config.minVisibilityRatio||e.push(s.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const n=t.slice(0,this.config.maxTrackedElements);return{timestamp:s,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...n.flatMap(t=>t.blockId??[])])],elements:n.map(t=>t.element)}}}class Lt{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;warningListeners=new Set;reportedWarnings=new Set;uiObserver;uiObserverConfig=It;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{St.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Et)}),this.socket.on("disconnect",()=>{St.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",t=>{this.updateConnectionStatus(!1);const e=function(t,e){return e?void 0:function(t){const{data:e}=t;if("object"!=typeof e||null===e)return;const{code:s,reason:n}=e;return"number"==typeof s?{code:s,..."string"==typeof n&&{reason:n}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(St.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(kt,t=>{St.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{St.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{St.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{St.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{St.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(Rt,t=>{"chapter-event"===t.type&&this.notifyWarningListeners(function(t,e){return(t.warnings??[]).filter(s=>{const n=`${t.id}:${s.block}:${s.content}`;return!e.has(n)&&(e.add(n),!0)})}(t.chapter,this.reportedWarnings)),this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in connection status listener:",t)}})}notifyRejection(t,e){this.notifyErrorListeners({code:t.code,message:e,...void 0!==t.reason&&{reason:t.reason}})}scheduleHandshakeRetry(t){if(!this.socket)return;if(this.clearHandshakeRetry(),!function(t,e){return t>=500&&e<3}(t,this.handshakeRetryAttempts))return void(t>=500&&(St.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:t,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const e=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,St.info(`Retrying Callimacus connection in ${e}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*e)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(t){this.errorListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in error listener:",t)}})}notifyWarningListeners(t){for(const e of t)0===this.warningListeners.size&&St.warn(`Block "${e.block}" was not shown: its content "${e.content}" failed (${e.cause}). \`callimacus thamyr probe\` shows why.`),this.warningListeners.forEach(t=>{try{t(e)}catch(t){St.error("Error in warning listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return St.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new Ut(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),s=new URL("thamyr",e).pathname;return{origin:e.origin,path:s}}connect(t="wss://localhost:4000",e,s){this.socket&&(St.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const n=this.socketEndpoint(t);let i;"undefined"!=typeof window&&void 0!==globalThis.location&&(i=globalThis.location.href);const r="undefined"==typeof document?void 0:function(t){const e=t.split("; ").find(t=>t.startsWith("intent_sid="))?.slice(11);return void 0===e||""===e?void 0:e}(document.cookie),o={...void 0!==i&&""!==i&&{referrer:i},...void 0!==r&&{intentSid:r},...s};St.info("Connecting to Thamyr at",n),this.socket=bt(n.origin,{path:n.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth:o}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),St.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...It,enabled:!1});const e=t.enabled??(void 0!==t.productSelector||void 0!==t.blockSelector||void 0!==t.maxTrackedElements||void 0!==t.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...t,enabled:e},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new Ut(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void St.error("Socket is not connected. Cannot send interaction.");if(t===Bt.SUGGEST)return void St.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===Bt.BACK_FROM_ROUND&&void 0===e.chapterId)return void St.error("BACK_FROM_ROUND requires chapterId.");const s={type:t,payload:this.enrichPayloadWithUiContext(e)},n={id:Nt()};this.socket.emit(Ot,{type:s.type,payload:s.payload},n.id)}async suggest(t,e={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(t){const e=t?.suggestions;return{suggestions:Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}}(await this.socket.timeout(e.timeoutMs??4e3).emitWithAck(Ot,{type:Bt.SUGGEST,payload:t}))}catch(t){return St.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}onWarning(t){return this.warningListeners.add(t),()=>{this.warningListeners.delete(t)}}}const jt="https://api.callimacus.ai",$t="/cart/add.js",_t="[callimacus]";class Dt extends Error{code;constructor(t,e,s){super(e,s),this.name="CallimacusError",this.code=t}}function qt(t){return Mt(t,"[data-callimacus-settings]","using {}")??{}}function Mt(t,e,s){if(void 0!==t&&""!==t)try{const n=JSON.parse(t);if("object"==typeof n&&null!==n&&!Array.isArray(n))return n;console.warn(`${_t} ${e} must be a JSON object — ${s}`)}catch(t){console.warn(`${_t} ${e} is not valid JSON — ${s}`,t)}}function Pt(t,e){return void 0===t||""===t?e:t}function Vt(t){return`server_${t.code??"error"}`}function Ft(t,e){t.dataset.callimacusState=e,t.setAttribute("aria-busy",String("loading"===e))}function Ht(t,e,s){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:s}))}function Kt(t){const{data:e}=t;return"object"!=typeof e||null===e?[]:Object.values(e)}function Wt(t){let e=t.language;try{Intl.NumberFormat.supportedLocalesOf(e)}catch{console.warn(`${_t} invalid data-language "${e}" — formatting with "en"`),e="en"}const s=new Map;const n=function(t,e){let s;try{s=new URL(t,"https://storefront.invalid").pathname.split("/").find(t=>""!==t)}catch{s=void 0}const n=void 0!==s&&/^[a-z]{2,3}(?:-[\da-z]{2,4})?$/iu.test(s)?s:e;try{return Intl.getCanonicalLocales(n)[0]??n}catch{return n}}(t.rootUrl,t.language);async function i(e,s,i,r={}){const o="string"==typeof s?s:s?.id,{clientId:a}=t;if(void 0===o||""===o)throw new Dt("send_failed","The item has no id to look up");if(void 0===a||""===a)throw new Dt("send_failed","No client id to look up with");const c=new AbortController,h=setTimeout(()=>{c.abort()},i.timeoutMs??1e4);try{let s;try{s=await fetch(`${new URL("api/v3",t.endpoint).href}/skesis/query/${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"x-sl-access-token":a},body:JSON.stringify({anchorId:o,locale:i.locale??n,...r}),signal:c.signal})}catch(t){throw new Dt("lookup_unreachable","Could not reach the catalogue",{cause:t})}if(!s.ok)throw new Dt(`server_${s.status}`,`The catalogue refused the lookup (HTTP ${s.status})`);return await s.json().catch(t=>{throw new Dt("lookup_unreachable","The catalogue sent an unreadable answer",{cause:t})})}finally{clearTimeout(h)}}const r=t=>(Array.isArray(t)?t:[]).filter(t=>"object"==typeof t?.item).map(t=>void 0===t.score?t.item:{...t.item,score:t.score});return Object.freeze({locale:e,currency:t.currency,settings:t.settings,picks(t){for(const e of Kt(t)){if(!Array.isArray(e))continue;const t=e.filter(t=>Boolean(t?.fields?.["shopify-handle"]));if(t.length>0)return t}return[]},text(t){for(const e of Kt(t)){if("string"==typeof e&&""!==e.trim())return e.trim();const t=e?.text;if("string"==typeof t&&""!==t.trim())return t.trim()}},money(n){const i="number"==typeof n?n:n?.amount;if("number"!=typeof i)return"";const r="object"==typeof n?n?.currency:void 0,o=void 0===r||""===r?t.currency??"USD":r;return function(t){if(!s.has(t))try{s.set(t,new Intl.NumberFormat(e,{style:"currency",currency:t}))}catch{console.warn(`${_t} invalid currency code "${t}" — showing bare amounts`),s.set(t,void 0)}return s.get(t)}(o)?.format(i)??i.toFixed(2)},productUrl(e){const s=e?.fields?.["shopify-handle"];if(void 0===s||""===s)return;return`${t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl}/products/${s}`},imageUrl(t,{width:e=800,index:s=0}={}){const n=t?.fields?.images?.[s]?.url;return void 0===n||""===n?void 0:`${n.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields?.variantTree?.variants??[],s=e.find(t=>t.orderable)??e[0];return void 0===s?.id?void 0:String(s.id).split("/").pop()},async addToCart(e,s=1){let n;try{n=await fetch(t.cartAddUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({items:[{id:Number(e),quantity:s}]})})}catch(t){throw new Dt("cart_unreachable","Could not reach the cart",{cause:t})}const i=await n.json().catch(()=>(console.warn(`${_t} cart response was not JSON (HTTP ${n.status})`),{}));if(!n.ok){const{description:t,message:e}=i??{};throw new Dt("cart_rejected",t??e??`Could not add to cart (HTTP ${n.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:i})),i},async similar(t,{topK:e,...s}={}){const n=await i("similar",t,s,void 0===e?{}:{topK:e});return r(n?.hits)},async related(t,e={}){const s=await i("related",t,e)??{};return{related:r(s.related),siblingColors:r(s.siblingColors),usedFallback:!0===s.usedFallback}}})}function zt(t){return function(){const t=globalThis;return t.callimacusRenderers??=[],t.callimacusRenderers}().find(e=>{const s=e;return s?.type===t&&"function"==typeof s.render})}function Yt(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:s}=t,n={clientId:s.clientId,endpoint:Pt(s.endpoint,jt),language:Pt(s.language,"en"),currency:""===s.currency?void 0:s.currency,rootUrl:Pt(s.rootUrl,"/"),cartAddUrl:Pt(s.cartAddUrl,$t),settings:qt(t.querySelector("[data-callimacus-settings]")?.textContent??void 0)};if("true"===s.designMode)return void Ft(t,"design-mode");if(void 0===n.clientId||""===n.clientId)return Ft(t,"error"),void console.warn(`${_t} no client id — leaving your markup in place`);t.querySelector("[data-callimacus-output]")||console.warn(`${_t} no [data-callimacus-output] inside this mount — rendered blocks will replace the mount element's entire contents`);const{clientId:i}=n,r=e.roundTimeoutMs??45e3,o=Wt(n),a=new Set;let c,h,u=!1,d=""===s.storyId?void 0:s.storyId,l=!1,p=!1;const f=new Set,y=void 0!==s.uiObserver&&"false"!==s.uiObserver,m=""===s.uiObserver?void 0:s.uiObserver;function g(){return c||(c=e.transport??new Lt,y&&c.configureUiObserver?.({enabled:!0,...void 0!==m&&{productSelector:m}}),c.onConnectionStatus&&(p=!0,c.onConnectionStatus(t=>{if(l=t,t){for(const t of f)t();f.clear()}})),c.onError(t=>{h=`${Vt(t)}: ${t.message??""}`,u||console.warn(`${_t} transport error between rounds — ${h}`)}),c.onServerResponse(e=>{if(e.type!==wt)return;const s=e.story?.id;"string"==typeof s&&""!==s&&s!==d&&(d=s,Ht(t,"callimacus:story",{storyId:s}))}),c.connect(n.endpoint,{Authorization:`Bearer ${i}`},{token:i}),c)}async function b(t){const e=g();return new Promise((s,n)=>{function i(){clearTimeout(o),c(),u()}const o=setTimeout(()=>{i();n(new Dt("timeout",`Callimacus did not answer in time${void 0===h?"":` (last transport error: ${h})`}`))},r),c=e.onServerResponse(e=>{if(e.type!==vt)return;const n=e.chapter;n?.status===Tt&&!a.has(n.id)&&function(t,e){if("object"!=typeof t||null===t)return!0;const{type:s,data:n}=t;if(void 0!==s&&s!==e.type)return!1;const i=e.data;return!(void 0!==n?.interactionId&&n.interactionId!==i.interactionId||"string"==typeof n?.value&&"string"==typeof i.value&&n.value!==i.value)}(n.inputEvent,t.inputEvent)&&(a.add(n.id),i(),s(n))}),u=e.onError(t=>{i(),n(new Dt(Vt(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(Bt.CREATE_ROUND,t)}catch(t){i(),n(new Dt("send_failed","Could not send the request",{cause:t}))}})}function v(t={}){const e=t.storyId??d;return{language:t.language??n.language,...null!=e&&{storyId:e}}}async function w(e){if(!u){u=!0;try{let s;try{s=e()}catch(t){throw new Dt("send_failed",t instanceof Error?t.message:"Could not build the request",{cause:t})}const{inputEvent:n}=s;Ft(t,"loading"),Ht(t,"callimacus:loading",{value:n.data.value,inputEvent:n});const i=await b(s),r=[...i.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:a,rendered:c}=function(t,e,s=!1){const n=document.createDocumentFragment();let i=0;for(const r of t){const t=zt(r.type);if(t)try{const o=t.render(r,e);s&&o instanceof HTMLElement&&void 0===o.dataset.blockId&&(o.dataset.blockId=r.id),o instanceof Node?(n.append(o),i++):null!=o&&console.error(`${_t} renderer for ${r.type} returned a non-Node value — skipped`)}catch(t){console.error(`${_t} renderer for ${r.type} threw`,t)}else console.info(`${_t} no renderer for ${r.type} — skipped`)}return{fragment:n,rendered:i}}(r,o,y);if(0===c)return Ft(t,"empty"),void Ht(t,"callimacus:empty",{chapter:i});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(a),Ft(t,"ready"),Ht(t,"callimacus:ready",{chapter:i,blocks:r,rendered:c})}catch(e){Ft(t,"error"),Ht(t,"callimacus:error",{error:e});const{code:s,message:n}=e instanceof Dt?e:{code:"error",message:String(e)};console.error(`${_t} ${s}: ${n} — your markup is untouched`)}finally{u=!1}}}async function k(t){if(""!==t)return w(()=>({inputEvent:{type:"question",data:{value:t}},...v()}))}async function R(t,e={}){return w(()=>function(t,e={}){const{block:s,payload:n,submissionId:i,value:r,...o}=e;return{inputEvent:{type:"customInteraction",data:{interactionId:t,...void 0!==s&&{nodeKey:s},...void 0!==n&&{payload:n},...void 0!==i&&{submissionId:i},...void 0!==r&&{value:r}}},...o}}(t,{...e,...v(e)}))}async function E(t,e={}){return w(()=>function(t,e={}){if(void 0!==t&&t.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===t?{}:{value:t}},...e}}(t,v(e)))}async function O(t){return!(!l&&p)||new Promise(e=>{const s=()=>{clearTimeout(n),e(!0)},n=setTimeout(()=>{f.delete(s),e(!1)},t);f.add(s)})}async function T(t="",e={}){const s={suggestions:[]},n=g(),i=e.timeoutMs??4e3;if(!n.suggest||!await O(i))return s;const{language:r,storyId:o}=v(e);return n.suggest({prefix:t,...void 0!==r&&{language:r},..."string"==typeof o&&{storyId:o}},{timeoutMs:i})}const A={ask:k,sendInteraction:R,openLanding:E,suggest:T,ctx:o,get state(){return t.dataset.callimacusState},get storyId(){return d},resetStory(){d=void 0}};t.callimacus=A,Ht(t,"callimacus:mounted",A),function(t,e){const{dataset:s}=t,n=""===s.interaction?void 0:s.interaction,i=""===s.prompt?void 0:s.prompt,{landing:r}=s,o=[void 0===n?void 0:"data-interaction",void 0===r?void 0:"data-landing",void 0===i?void 0:"data-prompt"].filter(t=>void 0!==t);o.length>1&&console.warn(`${_t} ${o.join(", ")} each open the first round — using ${o[0]}`);if(void 0!==n){const t=""===s.interactionValue?void 0:s.interactionValue,i=Mt(s.interactionPayload,"[data-interaction-payload]","sending the interaction without one");e.sendInteraction(n,{...void 0!==t&&{value:t},...void 0!==i&&{payload:i}})}else void 0!==r?e.openLanding(""===r?void 0:r):void 0!==i&&e.ask(i)}(t,A)}(t,e)}catch(e){Ft(t,"error"),Ht(t,"callimacus:error",{error:e}),console.error(`${_t} mount failed — your markup is untouched`,e)}}}function Jt(t,e={}){for(const s of t.querySelectorAll("[data-callimacus]"))Yt(s,e)}function Gt(){Ct(),document.addEventListener("shopify:section:load",t=>{t.target instanceof Element&&Jt(t.target)}),Jt(document)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Gt):Gt()}();
21
+ const bt="chapter-event",wt="story-created",kt="error",Rt="server-response",Et="client-ready",Tt="user-interaction",Ot=4,At={debug:0,info:1,warn:2,error:3,silent:4},St=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...t)=>{this.log("debug",...t)};info=(...t)=>{this.log("info",...t)};warn=(...t)=>{this.log("warn",...t)};error=(...t)=>{this.log("error",...t)};log(t,...e){if(!(this.config.enabled&&At[t]>=At[this.config.level]))return;const{prefix:n}=this.config,s=void 0===n||""===n?e:[n,...e];console[t](...s)}configure(t){this.config={...this.config,...t}}getConfig(){return{...this.config}}};function Ct(){let t,e="";try{e=globalThis.location.search}catch{}try{t=localStorage}catch{}(function(t,e){if(new URLSearchParams(t).has("callimacus_debug"))return!0;try{return null!==(e?.getItem("callimacus:debug")??null)}catch{return!1}})(e,t)&&St.configure({enabled:!0,level:"warn"})}function Nt(){const t="undefined"==typeof crypto?void 0:crypto;if("function"==typeof t?.randomUUID)return t.randomUUID();const e=new Uint8Array(16);if("function"==typeof t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const n=[...e].map(t=>t.toString(16).padStart(2,"0"));return[n.slice(0,4).join(""),n.slice(4,6).join(""),n.slice(6,8).join(""),n.slice(8,10).join(""),n.slice(10,16).join("")].join("-")}const It=Symbol.for("callimacus.pageViewRecorders");function Bt(){const t=globalThis,e=t.callimacusPageView;return"object"==typeof e&&null!==e&&"string"==typeof e.id||(t[It]??0)>0}var xt,Lt;!function(t){t.GET_STORY="get-story",t.CREATE_ROUND="create-round",t.RESET_STORY="reset-story",t.BACK_FROM_ROUND="back-from-round",t.SHARE_STORY="share-story",t.GET_SHARED_STORY="get-shared-story",t.SUGGEST="suggest"}(xt||(xt={})),function(t){t.ROUND_CREATED="round-created",t.ROUND_EVENT="round-event",t.ROUND_COMPLETED="round-completed",t.ERROR="error"}(Lt||(Lt={}));const Ut={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class jt{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(t={}){const e=t.minVisibilityRatio??Ut.minVisibilityRatio;this.config={productSelector:t.productSelector??Ut.productSelector,blockSelector:t.blockSelector??Ut.blockSelector,maxTrackedElements:t.maxTrackedElements??Ut.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,e))}}rescanUi(){if(!this.canUseDom())return;let t,e;try{t=document.querySelectorAll(this.config.productSelector),e=document.querySelectorAll(this.config.blockSelector)}catch(t){return void St.warn("UI Observer: invalid selector, skipping rescan:",t)}const n=Date.now();for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),s=this.calculateVisibilityRatio(t);this.syncTrackedElement(e,{bounds:t,isVisible:s>=this.config.minVisibilityRatio,visibilityRatio:s,observedAt:n})}for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),s=this.calculateVisibilityRatio(e);this.syncTrackedBlock(t,{bounds:e,isVisible:s>=this.config.minVisibilityRatio,visibilityRatio:s,observedAt:n})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const t=[...this.elements].sort(([,t],[,e])=>{const n=t.visibilityRatio-e.visibilityRatio;return 0===n||Number.isNaN(n)?t.observedAt-e.observedAt:n}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[e]of t)this.elements.delete(e),this.elementRefs.delete(e)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const t=[...this.blocks].sort(([,t],[,e])=>{const n=t.visibilityRatio-e.visibilityRatio;return 0===n||Number.isNaN(n)?t.observedAt-e.observedAt:n}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[e]of t)this.blocks.delete(e),this.blockRefs.delete(e)}syncTrackedElement(t,e){const n=this.resolveElementId(t),s=this.resolveBlockId(t),i=this.createTrackingKey(n,s),r=this.elementKeys.get(t);void 0!==r&&""!==r&&r!==i&&(this.elements.delete(r),this.elementRefs.delete(r)),this.elementKeys.set(t,i),this.elementRefs.set(i,t),this.elements.set(i,{id:n,blockId:s,trackingKey:i,...e})}syncTrackedBlock(t,e){const n=this.resolveTrackedBlockId(t),s=this.blockKeys.get(t),i=n;void 0!==s&&""!==s&&s!==i&&(this.blocks.delete(s),this.blockRefs.delete(s)),this.blockKeys.set(t,i),this.blockRefs.set(i,t),this.blocks.set(i,{id:n,...e})}resolveElementId(t){return[t.dataset.productId,t.dataset.productid,t.dataset.sku,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.productId??this.elements.size}`}resolveBlockId(t){let e;try{e=t.closest(this.config.blockSelector)??void 0}catch{return}return e instanceof HTMLElement?this.resolveTrackedBlockId(e):void 0}resolveTrackedBlockId(t){return[t.dataset.blockId,t.dataset.blockid,t.id].find(t=>void 0!==t&&""!==t)??`${t.tagName}-${t.dataset.blockId??this.blocks.size}`}createTrackingKey(t,e){return void 0===e||""===e?t:`${t}::${e}`}normalizeRect(t){return{x:t.x,y:t.y,width:t.width,height:t.height,top:t.top,left:t.left,right:t.right,bottom:t.bottom}}calculateVisibilityRatio(t){const e=Math.max(0,Math.min(t.right,window.innerWidth)-Math.max(t.left,0))*Math.max(0,Math.min(t.bottom,window.innerHeight)-Math.max(t.top,0)),n=t.width*t.height;if(n<=0)return 0;const s=window.innerWidth*window.innerHeight,i=s>0?Math.min(n,s):n;return Math.min(1,Math.max(0,e/i))}canUseDom(){return void 0!==globalThis.window&&"undefined"!=typeof document}start(){!this.started&&this.canUseDom()&&(this.started=!0)}stop(){this.started&&(this.started=!1,this.elements.clear(),this.elementRefs.clear(),this.blocks.clear(),this.blockRefs.clear())}getSnapshot(){if(!this.canUseDom())return;this.rescanUi();const t=[],e=[],n=Date.now();for(const[e,n]of this.elements){const s=this.elementRefs.get(e);s?.isConnected?n.visibilityRatio<=0||t.push({blockId:n.blockId,element:{id:n.id,bounds:n.bounds,isVisible:n.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:n.visibilityRatio}}):(this.elements.delete(e),this.elementRefs.delete(e))}for(const[t,n]of this.blocks){const s=this.blockRefs.get(t);s?.isConnected?n.visibilityRatio<this.config.minVisibilityRatio||e.push(n.id):(this.blocks.delete(t),this.blockRefs.delete(t))}const s=t.slice(0,this.config.maxTrackedElements);return{timestamp:n,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...e,...s.flatMap(t=>t.blockId??[])])],elements:s.map(t=>t.element)}}}class $t{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;warningListeners=new Set;reportedWarnings=new Set;uiObserver;uiObserverConfig=Ut;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{St.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(Et)}),this.socket.on("disconnect",()=>{St.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",t=>{this.updateConnectionStatus(!1);const e=function(t,e){return e?void 0:function(t){const{data:e}=t;if("object"!=typeof e||null===e)return;const{code:n,reason:s}=e;return"number"==typeof n?{code:n,..."string"==typeof s&&{reason:s}}:void 0}(t)??{code:0}}(t,this.socket?.active??!0);e&&(St.error("Connection refused by Callimacus:",t.message,e.reason??""),this.notifyRejection(e,t.message),this.scheduleHandshakeRetry(e.code))}),this.socket.on(kt,t=>{St.error("Received error from Callimacus:",t),this.notifyErrorListeners(t)}),this.socket.io.on("reconnect",t=>{St.info(`Reconnected to Callimacus after ${t} attempts`)}),this.socket.io.on("reconnect_attempt",t=>{St.info(`Attempting to reconnect: attempt ${t}`)}),this.socket.io.on("reconnect_error",t=>{St.error("Reconnection error:",t)}),this.socket.io.on("reconnect_failed",()=>{St.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(Rt,t=>{"chapter-event"===t.type&&this.notifyWarningListeners(function(t,e){return(t.warnings??[]).filter(n=>{const s=`${t.id}:${n.block}:${n.content}`;return!e.has(s)&&(e.add(s),!0)})}(t.chapter,this.reportedWarnings)),this.notifyServerResponseListeners(t)}))}notifyServerResponseListeners(t){this.serverResponseListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in server response listener:",t)}})}updateConnectionStatus(t){this.connectionStatusListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in connection status listener:",t)}})}notifyRejection(t,e){this.notifyErrorListeners({code:t.code,message:e,...void 0!==t.reason&&{reason:t.reason}})}scheduleHandshakeRetry(t){if(!this.socket)return;if(this.clearHandshakeRetry(),!function(t,e){return t>=500&&e<3}(t,this.handshakeRetryAttempts))return void(t>=500&&(St.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:t,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const e=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,St.info(`Retrying Callimacus connection in ${e}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*e)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(t){this.errorListeners.forEach(e=>{try{e(t)}catch(t){St.error("Error in error listener:",t)}})}notifyWarningListeners(t){for(const e of t)0===this.warningListeners.size&&St.warn(`Block "${e.block}" was not shown: its content "${e.content}" failed (${e.cause}). \`callimacus thamyr probe\` shows why.`),this.warningListeners.forEach(t=>{try{t(e)}catch(t){St.error("Error in warning listener:",t)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(t=>{navigator.geolocation.getCurrentPosition(e=>{t(e)},()=>{t(void 0)})})}enrichPayloadWithUiContext(t){try{this.ensureUiObserver();const e=this.uiObserver?.getSnapshot();return e?{...t,context:{...t.context,uiSnapshot:e}}:t}catch(e){return St.error("Error enriching payload with UI context:",e),t}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new jt(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(t){const e=new URL(t),n=new URL("thamyr",e).pathname;return{origin:e.origin,path:n}}connect(t="wss://localhost:4000",e,n){this.socket&&(St.warn("Already connected to Thamyr. Disconnecting first...."),this.disconnect());const s=this.socketEndpoint(t);let i;"undefined"!=typeof window&&void 0!==globalThis.location&&(i=globalThis.location.href);const r="undefined"==typeof document?void 0:function(t){const e=t.split("; ").find(t=>t.startsWith("intent_sid="))?.slice(11);return void 0===e||""===e?void 0:e}(document.cookie),o={...void 0!==i&&""!==i&&{referrer:i},...void 0!==r&&{intentSid:r},...n};St.info("Connecting to Thamyr at",s),this.socket=vt(s.origin,{path:s.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:e,auth(t){t({...o,...Bt()&&{recordsPageViews:!0}})}}),this.setupEventListeners(),this.ensureUiObserver()}disconnect(){this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.socket&&(this.socket.disconnect(),this.socket=void 0,this.uiObserver?.stop(),this.uiObserver=void 0,this.updateConnectionStatus(!1),St.info("Disconnected from Callimacus"))}configureUiObserver(t){if(!t)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...Ut,enabled:!1});const e=t.enabled??(void 0!==t.productSelector||void 0!==t.blockSelector||void 0!==t.maxTrackedElements||void 0!==t.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...t,enabled:e},"undefined"==typeof window||"undefined"==typeof document||!this.uiObserverConfig.enabled)return this.uiObserver?.stop(),void(this.uiObserver=void 0);this.uiObserver&&this.uiObserver.stop(),this.uiObserver=new jt(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(t,e){if(!this.socket)return void St.error("Socket is not connected. Cannot send interaction.");if(t===xt.SUGGEST)return void St.error("SUGGEST is a request/response command. Use suggest() instead.");if(t===xt.BACK_FROM_ROUND&&void 0===e.chapterId)return void St.error("BACK_FROM_ROUND requires chapterId.");const n={type:t,payload:this.enrichPayloadWithUiContext(e)},s={id:Nt()};this.socket.emit(Tt,{type:n.type,payload:n.payload},s.id)}async suggest(t,e={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(t){const e=t?.suggestions;return{suggestions:Array.isArray(e)?e.filter(t=>"string"==typeof t):[]}}(await this.socket.timeout(e.timeoutMs??4e3).emitWithAck(Tt,{type:xt.SUGGEST,payload:t}))}catch(t){return St.warn("Suggestions failed or timed out; serving none.",t),{suggestions:[]}}}async gatherClientInfo(){const t="undefined"==typeof navigator?void 0:navigator,e="undefined"==typeof window?void 0:window.screen;return{userAgent:t?.userAgent??"",language:t?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===e?"":`${e.width}x${e.height}`,location:await this.getLocation()}}onServerResponse(t){return this.serverResponseListeners.add(t),()=>{this.serverResponseListeners.delete(t)}}onConnectionStatus(t){return this.connectionStatusListeners.add(t),()=>{this.connectionStatusListeners.delete(t)}}onError(t){return this.errorListeners.add(t),()=>{this.errorListeners.delete(t)}}onWarning(t){return this.warningListeners.add(t),()=>{this.warningListeners.delete(t)}}}const _t=10,Mt=/^[A-Za-z]\w{0,39}$/u,Dt=/^[\w\-./:]{1,128}$/u,qt=new Set(["page_viewed","item_opened","added_to_cart","custom_event","conversation_started","question_asked","answer_delivered"]);const Vt=/^[\da-f]{8}-[\da-f]{4}-[1-8][\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}$/u,Pt=t=>void 0!==t&&Vt.test(t),Ft="function"==typeof TextEncoder?new TextEncoder:void 0,Ht=new WeakMap;function Kt(t){let e=Ht.get(t);if(void 0===e){const n=JSON.stringify(t);e=void 0===Ft?3*n.length:Ft.encode(n).length,Ht.set(t,e)}return e}function Wt(t){const e=[];let n=[],s=0;for(const i of t){const t=Kt(i);(50===n.length||n.length>0&&s+t>57344)&&(e.push(n),n=[],s=0),n.push(i),s+=t}return n.length>0&&e.push(n),e}function zt(t){const{transport:e,declares:n}=t,s=t.delayMs??3e3;let i,r,o,a,c=[],h=!1,d=0,u=!1;const l=new Set(n.types),p=(t,e)=>({sentAt:(new Date).toISOString(),events:t,declares:{types:[...l],addsCarryRoundId:n.addsCarryRoundId},...e>0&&{dropped:e}});function f(){clearTimeout(o),clearTimeout(a),o=void 0,a=void 0}function y(){void 0!==o||void 0!==a||u||(o=setTimeout(()=>{o=void 0,m()},s))}async function m(){if(h||u)return;f(),i??=function(){const[t]=Wt(c);if(void 0===t)return;c=c.slice(t.length);const e=d;return d=0,{events:t,dropped:e,attempts:0}}();const t=i;if(void 0===t)return;let n;h=!0;try{n=await e.send(p(t.events,t.dropped))}catch{n="retry"}if(h=!1,i!==t||u)return void(c.length>0&&y());const s="object"==typeof n?n.retryAfterMs:void 0;if(("retry"===n||void 0!==s)&&t.attempts<3)return t.attempts+=1,void(a=setTimeout(()=>{a=void 0,m()},s??2e3*2**(t.attempts-1)));i=void 0,"accepted"!==n&&(d+=t.dropped+t.events.length),c.length>0&&y()}function g(t,e){t.catch(()=>!1).then(t=>{t||(d+=e)})}function v(){if(u)return;f();const t=void 0===i||h?void 0:i,n=[...i?.events??[],...c];let s=d+(t?.dropped??0);c=[],i=void 0,d=0;const r=Wt(n);0===r.length&&s>0&&r.push([]);for(const t of r){const n=t.length+s;let i=!1;try{i=e.sendOnHide(p(t,s))}catch{}!1===i?d+=n:!0!==i&&g(i,n),s=0}}const b=()=>{v()},w=()=>{"undefined"!=typeof document&&"hidden"===document.visibilityState&&v()};return"function"==typeof globalThis.addEventListener&&globalThis.addEventListener("pagehide",b),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("visibilitychange",w),{record(e,n,s={}){const o=Date.now(),a=function(t=Date.now()){const e=new Uint8Array(16),n="undefined"==typeof crypto?void 0:crypto;if("function"==typeof n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());let s=t;for(let t=5;t>=0;t--)e[t]=s%256,s=Math.floor(s/256);e[6]=15&e[6]|112,e[8]=63&e[8]|128;const i=[...e].map(t=>t.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}(o),h="page_viewed"===e?void 0:t.conversationId?.(),p={eventId:a,type:e,typeVersion:1,clientCreatedAt:new Date(o).toISOString(),...void 0!==r&&"page_viewed"!==e&&{pageViewId:r},...Pt(s.roundId)&&{roundId:s.roundId},...Pt(h)&&{conversationId:h},payload:n};return"page_viewed"===e&&(r=a),u?a:c.length+(i?.events.length??0)>=100||Kt(p)>57344||"custom_event"===e&&!function(t){if(!Mt.test(t.name)||qt.has(t.name.toLowerCase()))return!1;const e=Object.entries(t.fields??{});return e.length<=_t&&e.every(([t,e])=>Mt.test(t)&&(t=>"boolean"==typeof t||"number"==typeof t&&Number.isFinite(t)||"string"==typeof t&&Dt.test(t))(e))}(n)?(d+=1,a):(l.add(e),c.push(p),y(),a)},get pageViewId(){return r},adoptPageView(t){r=t},flush:m,stop(){u=!0,f(),"function"==typeof globalThis.removeEventListener&&globalThis.removeEventListener("pagehide",b),"undefined"!=typeof document&&"function"==typeof document.removeEventListener&&document.removeEventListener("visibilitychange",w)}}}const Jt=Symbol.for("callimacus.eventMarkupRuntimes"),Yt=(t,e)=>{const n=t?.getAttribute(e)?.trim();return void 0===n||""===n?void 0:n};function Gt(){const t=globalThis;return t[Jt]??={runtimes:[]},t[Jt]}const Xt=t=>"object"==typeof t&&null!==t&&!Array.isArray(t),Zt=t=>String(t).split("/").pop()??"";function Qt(t,e,n=0){if(!(null===t||"object"!=typeof t||n>6)){if(function(t){if(!Xt(t)||!Xt(t.fields))return!1;const e=t.fields["shopify-handle"];return"string"==typeof e&&""!==e}(t)){const n=t.fields.variantTree?.variants??[];if(Array.isArray(n)&&n.some(t=>Zt(t?.id??"")===e))return"string"==typeof t.id&&""!==t.id?t.id:t.fields["shopify-handle"]}for(const s of Object.values(t)){const t=Qt(s,e,n+1);if(void 0!==t)return t}}}function te(t,e,n,s){const i=Zt(t),r=n.itemId??Qt(s,i);return void 0===r||""===r?void 0:{itemId:r,variantId:`gid://shopify/ProductVariant/${i}`,quantity:e,origin:n.origin??"card"}}function ee(t){const e=t?.trim()??"",n=""===e?NaN:Number(e),s=Number.isFinite(n)?1e3*n:Date.parse(e)-Date.now();return Number.isFinite(s)?Math.min(Math.max(s,0),6e5):6e4}async function ne(t,e,n){const s=void 0===n||"function"!=typeof AbortController?void 0:new AbortController,i=void 0===s?void 0:setTimeout(()=>{s.abort()},n);try{const n=await fetch(t,{...e,...void 0!==s&&{signal:s.signal}}),i=429===n.status?n.headers.get("retry-after"):void 0;return function(t,e){return t>=200&&t<300?"accepted":429===t?{retryAfterMs:ee(e)}:t>=500?"retry":"refused"}(n.status,i??void 0)}catch{return"retry"}finally{clearTimeout(i)}}function se(t){const e=()=>`${new URL("api/v3",t().endpoint).href}/events`;return{async send(n){const{token:s}=t();return ne(e(),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`,"x-sl-access-token":s},body:JSON.stringify(n),credentials:"include"},1e4)},sendOnHide(n){const s=JSON.stringify({...n,token:t().token});return"undefined"!=typeof navigator&&"function"==typeof navigator.sendBeacon?navigator.sendBeacon(e(),s):async function(t,e){return"accepted"===await ne(t,{...e,keepalive:!0})}(e(),{method:"POST",headers:{"Content-Type":"text/plain"},body:s,credentials:"include"})}}}const ie="https://api.callimacus.ai",re="/cart/add.js",oe="[callimacus]";class ae extends Error{code;constructor(t,e,n){super(e,n),this.name="CallimacusError",this.code=t}}function ce(t){return he(t,"[data-callimacus-settings]","using {}")??{}}function he(t,e,n){if(void 0!==t&&""!==t)try{const s=JSON.parse(t);if("object"==typeof s&&null!==s&&!Array.isArray(s))return s;console.warn(`${oe} ${e} must be a JSON object — ${n}`)}catch(t){console.warn(`${oe} ${e} is not valid JSON — ${n}`,t)}}function de(t,e){return void 0===t||""===t?e:t}function ue(t){return`server_${t.code??"error"}`}function le(t,e){t.dataset.callimacusState=e,t.setAttribute("aria-busy",String("loading"===e))}function pe(t,e,n){t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:n}))}function fe(t){const{data:e}=t;return"object"!=typeof e||null===e?[]:Object.values(e)}function ye(t){let e=t.language;try{Intl.NumberFormat.supportedLocalesOf(e)}catch{console.warn(`${oe} invalid data-language "${e}" — formatting with "en"`),e="en"}const n=new Map;const s=function(t,e){let n;try{n=new URL(t,"https://storefront.invalid").pathname.split("/").find(t=>""!==t)}catch{n=void 0}const s=void 0!==n&&/^[a-z]{2,3}(?:-[\da-z]{2,4})?$/iu.test(n)?n:e;try{return Intl.getCanonicalLocales(s)[0]??s}catch{return s}}(t.rootUrl,t.language);async function i(e,n,i,r={}){const o="string"==typeof n?n:n?.id,{clientId:a}=t;if(void 0===o||""===o)throw new ae("send_failed","The item has no id to look up");if(void 0===a||""===a)throw new ae("send_failed","No client id to look up with");const c=new AbortController,h=setTimeout(()=>{c.abort()},i.timeoutMs??1e4);try{let n;try{n=await fetch(`${new URL("api/v3",t.endpoint).href}/skesis/query/${e}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a}`,"x-sl-access-token":a},body:JSON.stringify({anchorId:o,locale:i.locale??s,...r}),signal:c.signal})}catch(t){throw new ae("lookup_unreachable","Could not reach the catalogue",{cause:t})}if(!n.ok)throw new ae(`server_${n.status}`,`The catalogue refused the lookup (HTTP ${n.status})`);return await n.json().catch(t=>{throw new ae("lookup_unreachable","The catalogue sent an unreadable answer",{cause:t})})}finally{clearTimeout(h)}}const r=t=>(Array.isArray(t)?t:[]).filter(t=>"object"==typeof t?.item).map(t=>void 0===t.score?t.item:{...t.item,score:t.score});return Object.freeze({locale:e,currency:t.currency,settings:t.settings,picks(t){for(const e of fe(t)){if(!Array.isArray(e))continue;const t=e.filter(t=>Boolean(t?.fields?.["shopify-handle"]));if(t.length>0)return t}return[]},text(t){for(const e of fe(t)){if("string"==typeof e&&""!==e.trim())return e.trim();const t=e?.text;if("string"==typeof t&&""!==t.trim())return t.trim()}},money(s){const i="number"==typeof s?s:s?.amount;if("number"!=typeof i)return"";const r="object"==typeof s?s?.currency:void 0,o=void 0===r||""===r?t.currency??"USD":r;return function(t){if(!n.has(t))try{n.set(t,new Intl.NumberFormat(e,{style:"currency",currency:t}))}catch{console.warn(`${oe} invalid currency code "${t}" — showing bare amounts`),n.set(t,void 0)}return n.get(t)}(o)?.format(i)??i.toFixed(2)},productUrl(e){const n=e?.fields?.["shopify-handle"];if(void 0===n||""===n)return;return`${t.rootUrl.endsWith("/")?t.rootUrl.slice(0,-1):t.rootUrl}/products/${n}`},imageUrl(t,{width:e=800,index:n=0}={}){const s=t?.fields?.images?.[n]?.url;return void 0===s||""===s?void 0:`${s.split("?",1)[0]}?width=${e}`},variantId(t){const e=t?.fields?.variantTree?.variants??[],n=e.find(t=>t.orderable)??e[0];return void 0===n?.id?void 0:String(n.id).split("/").pop()},async addToCart(e,n=1){let s;try{s=await fetch(t.cartAddUrl,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({items:[{id:Number(e),quantity:n}]})})}catch(t){throw new ae("cart_unreachable","Could not reach the cart",{cause:t})}const i=await s.json().catch(()=>(console.warn(`${oe} cart response was not JSON (HTTP ${s.status})`),{}));if(!s.ok){const{description:t,message:e}=i??{};throw new ae("cart_rejected",t??e??`Could not add to cart (HTTP ${s.status})`)}return document.dispatchEvent(new CustomEvent("cart:refresh",{bubbles:!0,detail:i})),i},async similar(t,{topK:e,...n}={}){const s=await i("similar",t,n,void 0===e?{}:{topK:e});return r(s?.hits)},async related(t,e={}){const n=await i("related",t,e)??{};return{related:r(n.related),siblingColors:r(n.siblingColors),usedFallback:!0===n.usedFallback}}})}function me(t){return function(){const t=globalThis;return t.callimacusRenderers??=[],t.callimacusRenderers}().find(e=>{const n=e;return n?.type===t&&"function"==typeof n.render})}function ge(t,e={}){if(!Object.hasOwn(t.dataset,"callimacusReady")){t.dataset.callimacusReady="";try{!function(t,e){const{dataset:n}=t,s={clientId:n.clientId,endpoint:de(n.endpoint,ie),language:de(n.language,"en"),currency:""===n.currency?void 0:n.currency,rootUrl:de(n.rootUrl,"/"),cartAddUrl:de(n.cartAddUrl,re),settings:ce(t.querySelector("[data-callimacus-settings]")?.textContent??void 0)};if("true"===n.designMode)return void le(t,"design-mode");if(void 0===s.clientId||""===s.clientId)return le(t,"error"),void console.warn(`${oe} no client id — leaving your markup in place`);t.querySelector("[data-callimacus-output]")||console.warn(`${oe} no [data-callimacus-output] inside this mount — rendered blocks will replace the mount element's entire contents`);const{clientId:i}=s,r=e.roundTimeoutMs??45e3,o=ye(s),a=new Set;let c,h,d,u=!1,l=""===n.storyId?void 0:n.storyId,p=!1,f=!1;const y=new Set,m=void 0!==n.uiObserver&&"false"!==n.uiObserver,g=""===n.uiObserver?void 0:n.uiObserver;function v(){return h||(h=e.transport??new $t,m&&h.configureUiObserver?.({enabled:!0,...void 0!==g&&{productSelector:g}}),h.onConnectionStatus&&(f=!0,h.onConnectionStatus(t=>{if(p=t,t){for(const t of y)t();y.clear()}})),h.onError(t=>{d=`${ue(t)}: ${t.message??""}`,u||console.warn(`${oe} transport error between rounds — ${d}`)}),h.onServerResponse(e=>{if(e.type!==wt)return;const n=e.story?.id;"string"==typeof n&&""!==n&&n!==l&&(l=n,pe(t,"callimacus:story",{storyId:n}))}),h.connect(s.endpoint,{Authorization:`Bearer ${i}`},{token:i}),h)}async function b(t){const e=v();return new Promise((n,s)=>{function i(){clearTimeout(o),c(),h()}const o=setTimeout(()=>{i();s(new ae("timeout",`Callimacus did not answer in time${void 0===d?"":` (last transport error: ${d})`}`))},r),c=e.onServerResponse(e=>{if(e.type!==bt)return;const s=e.chapter;s?.status===Ot&&!a.has(s.id)&&function(t,e){if("object"!=typeof t||null===t)return!0;const{type:n,data:s}=t;if(void 0!==n&&n!==e.type)return!1;const i=e.data;return!(void 0!==s?.interactionId&&s.interactionId!==i.interactionId||"string"==typeof s?.value&&"string"==typeof i.value&&s.value!==i.value)}(s.inputEvent,t.inputEvent)&&(a.add(s.id),i(),n(s))}),h=e.onError(t=>{i(),s(new ae(ue(t),t.message??"Callimacus error",{cause:t}))});try{e.sendUserInteraction(xt.CREATE_ROUND,t)}catch(t){i(),s(new ae("send_failed","Could not send the request",{cause:t}))}})}function w(t={}){const e=t.storyId??l;return{language:t.language??s.language,...null!=e&&{storyId:e}}}function k(){return c??=zt({transport:e.events??se(()=>({endpoint:s.endpoint,token:i})),declares:{types:[],addsCarryRoundId:!0},conversationId:()=>l}),c}function R(t){return Object.freeze({...o,async addToCart(e,n=1,s={}){const i=await o.addToCart(e,n),r=te(e,n,{itemId:s.productId},t.blocks);return void 0!==r&&k().record("added_to_cart",r,{roundId:t.id}),i}})}async function E(e){if(!u){u=!0;try{let n;try{n=e()}catch(t){throw new ae("send_failed",t instanceof Error?t.message:"Could not build the request",{cause:t})}const{inputEvent:s}=n;le(t,"loading"),pe(t,"callimacus:loading",{value:s.data.value,inputEvent:s});const i=await b(n),r=[...i.blocks??[]].sort((t,e)=>(t.priority??0)-(e.priority??0)),{fragment:o,rendered:a}=function(t,e,n=!1){const s=document.createDocumentFragment();let i=0;for(const r of t){const t=me(r.type);if(t)try{const o=t.render(r,e);n&&o instanceof HTMLElement&&void 0===o.dataset.blockId&&(o.dataset.blockId=r.id),o instanceof Node?(s.append(o),i++):null!=o&&console.error(`${oe} renderer for ${r.type} returned a non-Node value — skipped`)}catch(t){console.error(`${oe} renderer for ${r.type} threw`,t)}else console.info(`${oe} no renderer for ${r.type} — skipped`)}return{fragment:s,rendered:i}}(r,R(i),m);if(0===a)return le(t,"empty"),void pe(t,"callimacus:empty",{chapter:i});(t.querySelector("[data-callimacus-output]")??t).replaceChildren(o),t.dataset.callimacusRound=i.id,we=i.id,le(t,"ready"),pe(t,"callimacus:ready",{chapter:i,blocks:r,rendered:a})}catch(e){le(t,"error"),pe(t,"callimacus:error",{error:e});const{code:n,message:s}=e instanceof ae?e:{code:"error",message:String(e)};console.error(`${oe} ${n}: ${s} — your markup is untouched`)}finally{u=!1}}}async function T(t,e){if(""!==t)return E(()=>({inputEvent:{type:"question",data:{value:t,...void 0!==e&&{trigger:e}}},...w()}))}async function O(t,e={},n){return E(()=>{const s=function(t,e={}){const{block:n,payload:s,submissionId:i,value:r,...o}=e;return{inputEvent:{type:"customInteraction",data:{interactionId:t,...void 0!==n&&{nodeKey:n},...void 0!==s&&{payload:s},...void 0!==i&&{submissionId:i},...void 0!==r&&{value:r}}},...o}}(t,{...e,...w(e)});return void 0===n||"customInteraction"!==s.inputEvent.type?s:{...s,inputEvent:{...s.inputEvent,data:{...s.inputEvent.data,trigger:n}}}})}async function A(t,e={}){return E(()=>function(t,e={}){if(void 0!==t&&t.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===t?{}:{value:t}},...e}}(t,w(e)))}async function S(t){return!(!p&&f)||new Promise(e=>{const n=()=>{clearTimeout(s),e(!0)},s=setTimeout(()=>{y.delete(n),e(!1)},t);y.add(n)})}async function C(t="",e={}){const n={suggestions:[]},s=v(),i=e.timeoutMs??4e3;if(!s.suggest||!await S(i))return n;const{language:r,storyId:o}=w(e);return s.suggest({prefix:t,...void 0!==r&&{language:r},..."string"==typeof o&&{storyId:o}},{timeoutMs:i})}ve.set(t,k),be=k,ke??=function(t,e={}){const n=e.document??("undefined"==typeof document?void 0:document);if(void 0===n)return()=>{};const s=Gt();if(s.runtimes.push(t),void 0===s.stop){const t=t=>{try{const e=t.target??void 0,n=(t=>void 0!==t&&"function"==typeof t.closest)(e)?e.closest("[data-callimacus-event]")??void 0:void 0,s=Yt(n,"data-callimacus-event"),{runtimes:i}=Gt(),r=void 0===n?void 0:i.find(t=>t.owns(n))??i[0];if(void 0===n||void 0===s||void 0===r)return;const o=Yt(n.closest("[data-callimacus-round]")??void 0,"data-callimacus-round")??r.roundOf?.(n),a=function(t){const e={};for(const{name:n,value:s}of t.attributes)""!==s&&n.length>22&&n.startsWith("data-callimacus-event-")&&(e[n.slice(22)]=s);return e}(n);r.collector(n)?.record("custom_event",{name:s,...Object.keys(a).length>0&&{fields:a}},{roundId:o})}catch{}};n.addEventListener("click",t,{capture:!0}),s.stop=()=>{n.removeEventListener("click",t,{capture:!0})}}let i=!1;return()=>{if(i)return;i=!0;const e=Gt();e.runtimes=e.runtimes.filter(e=>e!==t),e.runtimes.length>0||(e.stop?.(),e.stop=void 0)}}({owns:t=>void 0!==Re(t),collector:t=>function(t){const e=Re(t);return void 0===e?void 0:ve.get(e)}(t)?.()??be?.(),roundOf:()=>we});const N={ask:async t=>T(t),sendInteraction:async(t,e)=>O(t,e),openLanding:A,suggest:C,ctx:o,get state(){return t.dataset.callimacusState},get storyId(){return l},resetStory(){l=void 0}};t.callimacus=N,pe(t,"callimacus:mounted",N),function(t,e){const{dataset:n}=t,s=""===n.interaction?void 0:n.interaction,i=""===n.prompt?void 0:n.prompt,{landing:r}=n,o=[void 0===s?void 0:"data-interaction",void 0===r?void 0:"data-landing",void 0===i?void 0:"data-prompt"].filter(t=>void 0!==t);o.length>1&&console.warn(`${oe} ${o.join(", ")} each open the first round — using ${o[0]}`);if(void 0!==s){const t=""===n.interactionValue?void 0:n.interactionValue,i=he(n.interactionPayload,"[data-interaction-payload]","sending the interaction without one");e.sendInteraction(s,{...void 0!==t&&{value:t},...void 0!==i&&{payload:i}})}else void 0!==r?e.openLanding(""===r?void 0:r):void 0!==i&&e.ask(i)}(t,{ask:async t=>T(t,"site"),sendInteraction:async(t,e)=>O(t,e,"site"),openLanding:A})}(t,e)}catch(e){le(t,"error"),pe(t,"callimacus:error",{error:e}),console.error(`${oe} mount failed — your markup is untouched`,e)}}}const ve=new WeakMap;let be,we,ke;function Re(t){const e=t.closest("[data-callimacus]")??void 0;return void 0!==e&&ve.has(e)?e:void 0}function Ee(t,e={}){for(const n of t.querySelectorAll("[data-callimacus]"))ge(n,e)}function Te(){Ct(),document.addEventListener("shopify:section:load",t=>{t.target instanceof Element&&Ee(t.target)}),Ee(document)}"loading"===document.readyState?document.addEventListener("DOMContentLoaded",Te):Te()}();
22
22
  //# sourceMappingURL=callimacus-runtime.min.js.map