@callimacus/thamyr-core 4.18.0 → 4.19.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.md +7 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.native.js +1 -1
- package/dist/esm/index.native.js.map +1 -1
- package/dist/types/index.d.ts +124 -79
- package/dist/types/index.native.d.ts +124 -79
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,13 @@
|
|
|
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
|
+
## [4.19.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.18.0...thamyr-core-v4.19.0) (2026-11-03)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
### Features
|
|
10
|
+
|
|
11
|
+
* **core:** onWarning reports the blocks a round dropped because a content failed ([#882](https://github.com/callimacus/thamyr-sdk/issues/882)) ([1a044b3](https://github.com/callimacus/thamyr-sdk/commit/1a044b35cea13040965ad04a9ba7c919532ca816))
|
|
12
|
+
|
|
6
13
|
## [4.18.0](https://github.com/callimacus/thamyr-sdk/compare/thamyr-core-v4.17.3...thamyr-core-v4.18.0) (2026-11-03)
|
|
7
14
|
|
|
8
15
|
|
package/dist/esm/index.js
CHANGED
|
@@ -5,5 +5,5 @@
|
|
|
5
5
|
* See LICENSE.md for the full terms.
|
|
6
6
|
*
|
|
7
7
|
*/
|
|
8
|
-
export*from"@callimacus/intent";import{io as e}from"socket.io-client";const t={ERROR:"error",CHAPTER_EVENT:"chapter-event",CHAPTER_DELETED:"chapter-deleted",STORY_RESET:"story-reset",STORY_CREATED:"story-created",STORY_SHARED:"story-shared",BLOCK_PATCH:"block-patch",CART_COMMAND:"cart-command"},n={ERROR:"error",SYSTEM_MESSAGE:"system-message",SERVER_STATUS:"server-status",SERVER_RESPONSE:"server-response"},r={CLIENT_READY:"client-ready",USER_INTERACTION:"user-interaction"},s={question:"question",content:"content",topic:"topic",tag:"tag",image:"image",video:"video",gallery:"gallery",relatedQuestion:"relatedQuestion",page:"page",customInteraction:"customInteraction",customPage:"customPage"},i={masonry:"masonry",carousel:"carousel"},o={understandingQuery:1,craftingAnswer:2,curatingContent:3,done:4};function a(e){return e.type.startsWith("custom:")}function c(e){return"set"in e.type&&e.type.set}function u(e){return"master"in e.type&&e.type.master}const l={debug:0,info:1,warn:2,error:3,silent:4};const d=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...e)=>{this.log("debug",...e)};info=(...e)=>{this.log("info",...e)};warn=(...e)=>{this.log("warn",...e)};error=(...e)=>{this.log("error",...e)};log(e,...t){if(!(this.config.enabled&&l[e]>=l[this.config.level]))return;const{prefix:n}=this.config,r=void 0===n||""===n?t:[n,...t];console[e](...r)}configure(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}};function h(e,t){const n=new URL(e),r=decodeURIComponent(n.pathname.slice(1)),s=(new TextEncoder).encode(JSON.stringify({bucket:"storage.callimacus.ai",key:r,edits:t})).toBase64();return`${n.origin}/${encodeURIComponent(s)}`}function y(){const e="undefined"==typeof crypto?void 0:crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if("function"==typeof e?.getRandomValues)e.getRandomValues(t);else for(let e=0;e<16;e++)t[e]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=[...t].map(e=>e.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("-")}var f,p;function m(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.audioUrl&&"string"==typeof t.mimeType}function g(e){if("object"==typeof e&&null!==e)for(const t of Object.values(e))if(m(t))return t}!function(e){e.GET_STORY="get-story",e.CREATE_ROUND="create-round",e.RESET_STORY="reset-story",e.BACK_FROM_ROUND="back-from-round",e.SHARE_STORY="share-story",e.GET_SHARED_STORY="get-shared-story",e.SUGGEST="suggest"}(f||(f={})),function(e){e.ROUND_CREATED="round-created",e.ROUND_EVENT="round-event",e.ROUND_COMPLETED="round-completed",e.ERROR="error"}(p||(p={}));const v={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class b{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(e={}){const t=e.minVisibilityRatio??v.minVisibilityRatio;this.config={productSelector:e.productSelector??v.productSelector,blockSelector:e.blockSelector??v.blockSelector,maxTrackedElements:e.maxTrackedElements??v.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,t))}}rescanUi(){if(!this.canUseDom())return;let e,t;try{e=document.querySelectorAll(this.config.productSelector),t=document.querySelectorAll(this.config.blockSelector)}catch(e){return void d.warn("UI Observer: invalid selector, skipping rescan:",e)}const n=Date.now();for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),r=this.calculateVisibilityRatio(e);this.syncTrackedElement(t,{bounds:e,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),r=this.calculateVisibilityRatio(t);this.syncTrackedBlock(e,{bounds:t,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const e=[...this.elements].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[t]of e)this.elements.delete(t),this.elementRefs.delete(t)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const e=[...this.blocks].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[t]of e)this.blocks.delete(t),this.blockRefs.delete(t)}syncTrackedElement(e,t){const n=this.resolveElementId(e),r=this.resolveBlockId(e),s=this.createTrackingKey(n,r),i=this.elementKeys.get(e);void 0!==i&&""!==i&&i!==s&&(this.elements.delete(i),this.elementRefs.delete(i)),this.elementKeys.set(e,s),this.elementRefs.set(s,e),this.elements.set(s,{id:n,blockId:r,trackingKey:s,...t})}syncTrackedBlock(e,t){const n=this.resolveTrackedBlockId(e),r=this.blockKeys.get(e),s=n;void 0!==r&&""!==r&&r!==s&&(this.blocks.delete(r),this.blockRefs.delete(r)),this.blockKeys.set(e,s),this.blockRefs.set(s,e),this.blocks.set(s,{id:n,...t})}resolveElementId(e){return[e.dataset.productId,e.dataset.productid,e.dataset.sku,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.productId??this.elements.size}`}resolveBlockId(e){let t;try{t=e.closest(this.config.blockSelector)??void 0}catch{return}return t instanceof HTMLElement?this.resolveTrackedBlockId(t):void 0}resolveTrackedBlockId(e){return[e.dataset.blockId,e.dataset.blockid,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.blockId??this.blocks.size}`}createTrackingKey(e,t){return void 0===t||""===t?e:`${e}::${t}`}normalizeRect(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,left:e.left,right:e.right,bottom:e.bottom}}calculateVisibilityRatio(e){const t=Math.max(0,Math.min(e.right,window.innerWidth)-Math.max(e.left,0))*Math.max(0,Math.min(e.bottom,window.innerHeight)-Math.max(e.top,0)),n=e.width*e.height;if(n<=0)return 0;const r=window.innerWidth*window.innerHeight,s=r>0?Math.min(n,r):n;return Math.min(1,Math.max(0,t/s))}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 e=[],t=[],n=Date.now();for(const[t,n]of this.elements){const r=this.elementRefs.get(t);r?.isConnected?n.visibilityRatio<=0||e.push({blockId:n.blockId,element:{id:n.id,bounds:n.bounds,isVisible:n.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:n.visibilityRatio}}):(this.elements.delete(t),this.elementRefs.delete(t))}for(const[e,n]of this.blocks){const r=this.blockRefs.get(e);r?.isConnected?n.visibilityRatio<this.config.minVisibilityRatio||t.push(n.id):(this.blocks.delete(e),this.blockRefs.delete(e))}const r=e.slice(0,this.config.maxTrackedElements);return{timestamp:n,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...t,...r.flatMap(e=>e.blockId??[])])],elements:r.map(e=>e.element)}}}function k(e){const{data:t}=e;if("object"!=typeof t||null===t)return;const{code:n,reason:r}=t;return"number"==typeof n?{code:n,..."string"==typeof r&&{reason:r}}:void 0}const w=3;function R(e,t){return e>=500&&t<3}function T(e,t){return t?void 0:k(e)??{code:0}}class S{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;uiObserver;uiObserverConfig=v;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{d.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(r.CLIENT_READY)}),this.socket.on("disconnect",()=>{d.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",e=>{this.updateConnectionStatus(!1);const t=T(e,this.socket?.active??!0);t&&(d.error("Connection refused by Callimacus:",e.message,t.reason??""),this.notifyRejection(t,e.message),this.scheduleHandshakeRetry(t.code))}),this.socket.on(n.ERROR,e=>{d.error("Received error from Callimacus:",e),this.notifyErrorListeners(e)}),this.socket.io.on("reconnect",e=>{d.info(`Reconnected to Callimacus after ${e} attempts`)}),this.socket.io.on("reconnect_attempt",e=>{d.info(`Attempting to reconnect: attempt ${e}`)}),this.socket.io.on("reconnect_error",e=>{d.error("Reconnection error:",e)}),this.socket.io.on("reconnect_failed",()=>{d.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(n.SERVER_RESPONSE,e=>{this.notifyServerResponseListeners(e)}))}notifyServerResponseListeners(e){this.serverResponseListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in server response listener:",e)}})}updateConnectionStatus(e){this.connectionStatusListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in connection status listener:",e)}})}notifyRejection(e,t){this.notifyErrorListeners({code:e.code,message:t,...void 0!==e.reason&&{reason:e.reason}})}scheduleHandshakeRetry(e){if(!this.socket)return;if(this.clearHandshakeRetry(),!R(e,this.handshakeRetryAttempts))return void(e>=500&&(d.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:e,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const t=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,d.info(`Retrying Callimacus connection in ${t}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*t)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(e){this.errorListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in error listener:",e)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(e=>{navigator.geolocation.getCurrentPosition(t=>{e(t)},()=>{e(void 0)})})}enrichPayloadWithUiContext(e){try{this.ensureUiObserver();const t=this.uiObserver?.getSnapshot();return t?{...e,context:{...e.context,uiSnapshot:t}}:e}catch(t){return d.error("Error enriching payload with UI context:",t),e}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new b(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(e){const t=new URL(e),n=new URL("thamyr",t).pathname;return{origin:t.origin,path:n}}connect(t="wss://localhost:4000",n,r){this.socket&&(d.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 o="undefined"==typeof document?void 0:function(e){const t="intent_sid=",n=e.split("; ").find(e=>e.startsWith(t))?.slice(11);return void 0===n||""===n?void 0:n}(document.cookie),a={...void 0!==i&&""!==i&&{referrer:i},...void 0!==o&&{intentSid:o},...r};d.info("Connecting to Thamyr at",s),this.socket=e(s.origin,{path:s.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:n,auth:a}),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),d.info("Disconnected from Callimacus"))}configureUiObserver(e){if(!e)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...v,enabled:!1});const t=e.enabled??(void 0!==e.productSelector||void 0!==e.blockSelector||void 0!==e.maxTrackedElements||void 0!==e.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...e,enabled:t},"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 b(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(e,t){if(!this.socket)return void d.error("Socket is not connected. Cannot send interaction.");if(e===f.SUGGEST)return void d.error("SUGGEST is a request/response command. Use suggest() instead.");if(e===f.BACK_FROM_ROUND){if(void 0===t.chapterId)return void d.error("BACK_FROM_ROUND requires chapterId.")}const n={type:e,payload:this.enrichPayloadWithUiContext(t)},s={id:y()};this.socket.emit(r.USER_INTERACTION,{type:n.type,payload:n.payload},s.id)}async suggest(e,t={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(e){const t=e?.suggestions;return{suggestions:Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}}(await this.socket.timeout(t.timeoutMs??4e3).emitWithAck(r.USER_INTERACTION,{type:f.SUGGEST,payload:e}))}catch(e){return d.warn("Suggestions failed or timed out; serving none.",e),{suggestions:[]}}}async gatherClientInfo(){const e="undefined"==typeof navigator?void 0:navigator,t="undefined"==typeof window?void 0:window.screen;return{userAgent:e?.userAgent??"",language:e?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===t?"":`${t.width}x${t.height}`,location:await this.getLocation()}}onServerResponse(e){return this.serverResponseListeners.add(e),()=>{this.serverResponseListeners.delete(e)}}onConnectionStatus(e){return this.connectionStatusListeners.add(e),()=>{this.connectionStatusListeners.delete(e)}}onError(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}}const E=new S,I=200;function C(e,t={}){if(void 0!==e&&e.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===e?{}:{value:e}},...t}}function A(e,t={}){const{block:n,payload:r,submissionId:s,value:i,...o}=t;return{inputEvent:{type:"customInteraction",data:{interactionId:e,...void 0!==n&&{nodeKey:n},...void 0!==r&&{payload:r},...void 0!==s&&{submissionId:s},...void 0!==i&&{value:i}}},...o}}function O(e){return e.receptors??e.intent??[]}function x(e){return"key"in e?e.key:void 0}const $="custom:addToCartResult";function _(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const q=e=>"string"==typeof e&&e.length>0,N=e=>_(e)&&q(e.size)&&q(e.variantId)&&"boolean"==typeof e.orderable;function D(e){if(!_(e.data)||!_(e.data.addToCart))return;const t=e.data.addToCart;return"error"===t.status?{status:"error"}:"resolved"===t.status&&q(t.variantId)&&q(t.productName)&&q(t.size)?{status:"resolved",variantId:t.variantId,productName:t.productName,size:t.size}:"size_selection_needed"===t.status&&q(t.productSku)&&q(t.productName)&&Array.isArray(t.availableSizes)&&t.availableSizes.every(N)?{status:"size_selection_needed",productSku:t.productSku,productName:t.productName,availableSizes:t.availableSizes}:void 0}const j=e=>_(e)?e:{};function U(e,t,n){const[r,...s]=t;if(!_(e)||!Object.hasOwn(e,r))return;const i=0===s.length?function(e,t){if(_(e)&&"string"==typeof e.docId)return{...e,values:{...j(e.values),...t.values},inputs:{...j(e.inputs),...t.inputs},textRuns:{...j(e.textRuns),...t.textRuns}}}(e[r],n):U(e[r],s,n);return i&&{...e,[r]:i}}function L(e,t){const n=e.blocks??[],r=e.id===t.chapterId?n.findIndex(e=>e.id===t.blockId):-1;if(-1===r)return e;const s=n[r],i=U(s.data,t.contentId.split("."),t);return i?{...e,blocks:n.with(r,{...s,data:i})}:e}function K(e){const t=/^\/?map\/(?<language>[^\/]+)(?:\/(?<slug>.*))?$/v.exec(e)?.groups,n=t?.language;if(void 0===n||""===n)return;const r=t?.slug;return void 0===r||""===r?{language:n}:{language:n,slug:r}}async function z(e){try{const{data:t}=await e();return t}catch(e){if("object"==typeof e&&null!==e&&404===e.status)return;throw e}}async function M(e,t){const n=K(t);if(!n)return;const{language:r,slug:s}=n;if(void 0===s){const{data:t}=await e.content.listDocuments({language:r},{throwOnError:!0});return{kind:"index",language:r,entries:t}}const i=`/map/${r}/${s}`,o=await z(async()=>e.content.getDocumentByPath({path:i},{throwOnError:!0}));if(o)return{kind:"document",language:r,slug:s,document:o};if(!s.includes("/"))return;const a=await z(async()=>e.skesis.getItemByPath({path:i},{throwOnError:!0}));return a&&{kind:"item",language:r,slug:s,itemPage:a}}const P=["link","ask","interact","cart","submit"],B=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),W=e=>"string"==typeof e&&e.trim().length>0,V=new Set(["http:","https:","mailto:","tel:"]),H=e=>{try{return V.has(new URL(e,"https://relative.invalid").protocol)}catch{return!1}};function G(e){const{id:t,value:n,payload:r,block:s}=e,i=void 0===n||"string"==typeof n||(e=>Array.isArray(e)&&e.every(e=>"string"==typeof e))(n),o=void 0===r||B(r);if(i&&o&&(void 0===s||"string"==typeof s)&&W(t))return{type:"interact",id:t,...void 0!==n&&{value:n},...void 0!==r&&{payload:r},...void 0!==s&&{block:s}}}function F(e){if(B(e))switch(e.type){case"link":return function(e){const{url:t,newTab:n}=e;return(void 0===n||"boolean"==typeof n)&&W(t)&&H(t)?{type:"link",url:t,...void 0!==n&&{newTab:n}}:void 0}(e);case"ask":return W(e.value)?{type:"ask",value:e.value}:void 0;case"interact":return G(e);case"cart":return W(e.productId)?{type:"cart",productId:e.productId}:void 0;case"submit":return W(e.form)?{type:"submit",form:e.form}:void 0;default:return}}function J(e){const t=e instanceof FormData?e:new FormData(e),n=[];for(const e of new Set(t.keys())){const r=t.getAll(e).filter(e=>"string"==typeof e),s=e.endsWith("[]");r.length>0&&n.push([s?e.slice(0,-2):e,s||r.length>1?r:r[0]])}return Object.fromEntries(n)}const Y="custom:deliverResult",Q=new Set(["done","pending","ambiguous","skipped"]),X=e=>void 0===e||"string"==typeof e,Z=e=>B(e)&&"string"==typeof e.message&&X(e.field),ee=e=>B(e)&&"string"==typeof e.status&&Q.has(e.status)&&X(e.ref);function te(e){const t=e.type===Y&&B(e.data)?e.data:void 0;if(void 0===t)return;const{status:n,submissionId:r,message:s,redirect:i,errors:o,results:a}=t;var c;return("accepted"===n||"refused"===n)&&W(r)&&X(s)&&X(i)&&(void 0===o||Array.isArray(o)&&o.every(Z))&&(B(c=a)&&Object.values(c).every(ee))?{status:n,submissionId:r,results:a,...void 0!==s&&{message:s},...void 0!==i&&H(i)&&{redirect:i},...void 0!==o&&{errors:o}}:void 0}const ne="2026-10",re=15e3,se=2e4,ie="fragment CartFields on Cart {\n\tid checkoutUrl totalQuantity\n\tcost {subtotalAmount {amount currencyCode} totalAmount {amount currencyCode}}\n\tlines(first: 100) {nodes {\n\t\tid quantity\n\t\tmerchandise {... on ProductVariant {id title product {title handle} image {url altText} price {amount currencyCode} selectedOptions {name value}}}\n\t\tcost {totalAmount {amount currencyCode}}\n\t}}\n}",oe=(e,t,n)=>`mutation ${e}(${t}, $country: CountryCode) @inContext(country: $country) {${n} {cart {...CartFields} userErrors {code field message} warnings {code message target}}}\n${ie}`,ae=`query CartQuery($id: ID!, $country: CountryCode) @inContext(country: $country) {cart(id: $id) {...CartFields}}\n${ie}`,ce=oe("CartCreate","$input: CartInput!","cartCreate(input: $input)"),ue=oe("CartLinesAdd","$cartId: ID!, $lines: [CartLineInput!]!","cartLinesAdd(cartId: $cartId, lines: $lines)"),le=oe("CartLinesUpdate","$cartId: ID!, $lines: [CartLineUpdateInput!]!","cartLinesUpdate(cartId: $cartId, lines: $lines)"),de=oe("CartLinesRemove","$cartId: ID!, $lineIds: [ID!]!","cartLinesRemove(cartId: $cartId, lineIds: $lineIds)"),he="The store is busy. Try again in a moment.",ye="The store is not open to the cart: its storefront password may be on.",fe=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),pe=e=>"string"==typeof e&&""!==e,me=(e,t)=>({error:{code:e,message:t},warnings:[]});const ge=(e,t=[])=>({data:e,warnings:t}),ve=(e,t,n)=>({error:{code:e,message:t,...void 0!==n&&{status:n}},isRefusedAccess:!1}),be=e=>({error:{code:"cart_unavailable",message:"The store refused the cart request.",status:e},isRefusedAccess:!0}),ke=/^gid:\/\/shopify\/ProductVariant\/\d+$/v,we=e=>ke.test(e);const Re=(e,t)=>Number.isSafeInteger(e)&&e>=t,Te=e=>({...e,lines:e.lines?.nodes??[]});const Se=e=>e.lines.map(e=>({id:e.id,merchandiseId:e.merchandise.id,quantity:e.quantity})),Ee=e=>e.map(({merchandiseId:e,quantity:t})=>({merchandiseId:e,quantity:t}));function Ie(e,t){const n=Ee(e),r=n.find(e=>e.merchandiseId===t.merchandiseId);return r?r.quantity+=t.quantity:n.push(t),n}async function Ce(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return ve("cart_unavailable",ye,0===t?void 0:t);if(430===t||429===t)return ve("throttled",he,t);if(401===t||403===t)return be(t);if(!e.ok)return ve("http",`The store answered ${t}.`,t);let n;try{n=await e.json()}catch{return ve("cart_unavailable",ye,t)}return fe(n)&&fe(n.data)?{data:n.data}:function(e,t){const n=fe(e)&&Array.isArray(e.errors)?e.errors:[],r=new Set(n.map(e=>fe(e)&&fe(e.extensions)?e.extensions.code:void 0));if(r.has("THROTTLED"))return ve("throttled",he,t);if(r.has("ACCESS_DENIED")||r.has("UNAUTHORIZED")||r.has("FORBIDDEN"))return be(t);const s=n.find(e=>fe(e)&&pe(e.message));return ve("graphql",fe(s)&&pe(s.message)?s.message:"The store could not read the cart request.",t)}(n,t)}const Ae=e=>e instanceof Error?e.message:String(e);async function Oe(e){return new Promise(t=>{setTimeout(t,e)})}function xe(e){return"function"==typeof AbortSignal.timeout?AbortSignal.timeout(e):void 0}function $e(){try{return localStorage}catch{return}}function _e(e){const t=new Map;return{getItem(n){try{const t=e?.getItem(n);if("string"==typeof t)return t}catch{}return t.get(n)??null},setItem(n,r){try{if(void 0!==e)return e.setItem(n,r),void t.delete(n)}catch{}t.set(n,r)},removeItem(n){t.delete(n);try{e?.removeItem(n)}catch{}}}}function qe(e,t={}){const{waitMs:n=se,ttlMs:r=re,retryMs:s=50,settleMs:i=30}=t;return async(t,o)=>{const a=`${t}:lease`,c=`${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`,u=()=>{const t=function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;return fe(t)&&pe(t.owner)&&"number"==typeof t.expires?{owner:t.owner,expires:t.expires}:void 0}catch{return}}(e.getItem(a));return void 0!==t&&t.expires>Date.now()?t.owner:void 0},l=Date.now()+n;let d=!1;for(;!d;){if(void 0===u()){try{e.setItem(a,JSON.stringify({owner:c,expires:Date.now()+r}))}catch{return o()}if(await Oe(i),d=u()===c,d)continue}if(Date.now()>=l)throw new Error(`[thamyr] the ${t} lock was not granted within ${n} ms`);await Oe(s)}try{return await o()}finally{u()===c&&e.removeItem(a)}}}function Ne(){const e=globalThis.navigator?.locks;if("function"==typeof e?.request)return async(t,n)=>{const r=xe(se);return e.request(t,r?{signal:r}:{},async()=>n())}}function De(){return _e($e())}function je(e){const t=_e(e.storage??$e()),n=e.lock??Ne()??qe(t),r=e.fetch??(async(e,t)=>fetch(e,t)),s=e.navigate??(e=>{location.assign(e)});function i(e){const s=`callimacus:shopify-cart:${e.cartKey??e.storeDomain}`,i=`callimacus:shopify-cart-lock:${e.cartKey??e.storeDomain}`,o=void 0!==e.storefrontToken,a=()=>function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;if(!fe(t)||!pe(t.id)||!t.id.startsWith("gid://shopify/Cart/"))return;const n=Array.isArray(t.lines)?t.lines:[];return{id:t.id,lines:n.filter(e=>fe(e)&&pe(e.id)&&pe(e.merchandiseId)&&"number"==typeof e.quantity)}}catch{return}}(t.getItem(s));function c(e){return t.setItem(s,JSON.stringify({id:e.id,lines:Se(e)})),e}function u(e){a()?.id===e&&t.removeItem(s)}async function l(t,n){const s={"Content-Type":"application/json",Accept:"application/json"};void 0!==e.storefrontToken&&(s["X-Shopify-Storefront-Access-Token"]=e.storefrontToken);try{const i=await r(`https://${e.storeDomain}/api/${ne}/graphql.json`,{method:"POST",headers:s,body:JSON.stringify({query:t,variables:{...n,country:e.country??null}}),redirect:"manual",signal:xe(1e4)});return await Ce(i)}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return ve("network",t?"The store did not answer in time.":"Could not reach the store. Check your connection and try again.")}}async function d(e){return l(ae,{id:e})}async function h(e,t,n){const r=await l(t,n);if("error"in r)return o&&r.isRefusedAccess?{refusedAccess:r.error}:{error:r.error,warnings:[]};const s=r.data[e];if(!fe(s))return me("graphql","The store answered without the cart.");const i=Array.isArray(s.userErrors)?s.userErrors:[],a=Array.isArray(s.warnings)?s.warnings:[];if(!s.cart&&i.every(e=>e.field?.includes("cartId")??!1))return{isGone:!0};const u=s.cart?c(Te(s.cart)):void 0;return i.length>0?{...void 0!==u&&{data:u},error:{code:"refused",message:i.map(e=>e.message).join(" "),userErrors:i},warnings:a}:ge(u,a)}function y(e,t){return"isGone"in e?(u(t),me("no_cart","The cart is no longer there.")):"refusedAccess"in e?{error:e.refusedAccess,warnings:[]}:e}async function f(t,r,s){let o,l=!1;try{o=await n(i,async()=>{l=!0;const n=a();return void 0!==n&&n.id!==s?n:0===t.length?(void 0!==s&&u(s),ge(void 0)):async function(t){const n={lines:t,...void 0!==e.country&&{buyerIdentity:{countryCode:e.country}},...void 0!==e.sourceName&&{sourceName:e.sourceName}},r=await h("cartCreate",ce,{input:n});return"isGone"in r?me("graphql","The store created no cart."):"refusedAccess"in r?{error:r.refusedAccess,warnings:[]}:r}(t)})}catch(e){return l?me("cart_unavailable",Ae(e)):me("busy","The cart is being set up in another tab. Try again in a moment.")}if("warnings"in o)return o;if(r.length>0)return y(await h("cartLinesAdd",ue,{cartId:o.id,lines:r}),o.id);const f=await d(o.id);return"error"in f?{error:f.error,warnings:[]}:ge(f.data.cart?c(Te(f.data.cart)):void 0)}return{hasToken:o,read:a,keep:c,drop:u,query:d,change:async function(e,t,n){const r=await h(t.field,t.document,{cartId:e.id,...t.variables});return"isGone"in r&&void 0!==n.whenGone?f(n.whenGone,n.added??[],e.id):"refusedAccess"in r?f(n.whenRefused,n.added??[],e.id):y(r,e.id)},createOnce:f}}let o=Promise.resolve();async function a(t){const n=o.then(async()=>async function(t){let n;try{n=await e.settings()}catch(e){return me("cart_unavailable",Ae(e))}if(!n.cartEnabled)return me("cart_disabled","The cart is off on this site.");const{storeDomain:r}=n;if(void 0===r)return me("cart_unavailable","No Shopify store is set up for this site.");try{return await t(i({...n,storeDomain:r}))}catch(e){return me("cart_unavailable",Ae(e))}}(t));return o=n.catch(()=>{}),n}async function c(){return a(async e=>{const t=e.read();if(void 0===t)return ge(void 0);const n=await e.query(t.id);return"error"in n?n.isRefusedAccess&&e.hasToken?e.createOnce(Ee(t.lines),[],t.id):{error:n.error,warnings:[]}:n.data.cart?ge(e.keep(Te(n.data.cart))):(e.drop(t.id),ge(void 0))})}const u={getCart:c,async addItem(e,t=1){const n=function(e){if("string"==typeof e)return we(e)?e:/^\d+$/v.test(e)?`gid://shopify/ProductVariant/${e}`:void 0}(e);if(void 0===n)return me("invalid_input",`Not a Shopify product variant id: ${e}.`);if(!Re(t,1))return me("invalid_input",`Not a quantity to add: ${t}.`);const r={merchandiseId:n,quantity:t},s=await a(async e=>{const t=e.read();return void 0===t?e.createOnce([r],[r]):e.change(t,{field:"cartLinesAdd",document:ue,variables:{lines:[r]}},{whenGone:[r],whenRefused:Ie(t.lines,r),added:[r]})}),i=function(e,t){if(void 0!==e.error||void 0===e.data)return;const{lines:n}=e.data;for(const r of e.warnings){const e="MERCHANDISE_OUT_OF_STOCK"===r.code?n.find(e=>0===e.quantity&&e.merchandise.id===t):void 0;if(void 0!==e)return{line:e,warning:r}}}(s,n);if(void 0===i)return s;return{data:(await u.removeItem(i.line.id)).data??s.data,error:{code:"refused",message:i.warning.message},warnings:s.warnings}},removeItem:async e=>pe(e)?a(async t=>{const n=t.read();return void 0===n?me("no_cart","There is no cart yet."):t.change(n,{field:"cartLinesRemove",document:de,variables:{lineIds:[e]}},{whenRefused:Ee(n.lines.filter(t=>t.id!==e))})}):me("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>pe(e)&&Re(t,0)?a(async n=>{const r=n.read();if(void 0===r)return me("no_cart","There is no cart yet.");const s=r.lines.map(n=>n.id===e?{...n,quantity:t}:n).filter(e=>e.quantity>0);return n.change(r,{field:"cartLinesUpdate",document:le,variables:{lines:[{id:e,quantity:t}]}},{whenRefused:Ee(s)})}):me("invalid_input",`Not a cart line and quantity: ${e} × ${t}.`),async checkout(){const e=await c();if(void 0!==e.error)return{error:e.error,warnings:e.warnings};const t=e.data;if(void 0===t||0===t.totalQuantity)return me("no_cart","The cart is empty.");if(!function(e){try{return"https:"===new URL(e).protocol}catch{return!1}}(t.checkoutUrl))return me("cart_unavailable","The store answered without a checkout link.");try{s(t.checkoutUrl)}catch(e){return me("cart_unavailable",Ae(e))}return ge(t.checkoutUrl,e.warnings)}};return u}const Ue=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Le=e=>"string"==typeof e&&""!==e.trim()?e.trim():void 0;function Ke(e){const t=e?.trim()??"";if(""!==t)try{const{host:e}=new URL(/^https?:\/\//iv.test(t)?t:`https://${t}`);return""===e?void 0:e}catch{return}}const ze=e=>void 0!==e&&/^[a-z]{2}$/iv.test(e)?e.toUpperCase():void 0;const Me=(e,t)=>Ke(e?.storeDomain)??t;function Pe(e,t){const n=Ke(e?.domain??t?.storeDomain),r=e?.storefrontToken??Le(t?.storefrontToken),s=e?.sourceName??void 0,i=ze(t?.country);return{cartEnabled:e?.cartEnabled??!0,...void 0!==n&&{storeDomain:n,cartKey:Me(t,n)},...void 0!==r&&{storefrontToken:r},...void 0!==s&&{sourceName:s},countries:e?.countries??{},...void 0!==i&&{country:i}}}async function Be(e,t){try{const n="function"==typeof AbortSignal.timeout?AbortSignal.timeout(5e3):void 0,{data:r,response:s}=await e.get({url:"/shopify/storefront",...void 0!==n&&{signal:n}});return Pe(200===s?.status?function(e){if(!Ue(e)||"boolean"!=typeof e.cartEnabled)return;const t=Ue(e.countries)?Object.fromEntries(Object.entries(e.countries).filter(e=>"string"==typeof e[1])):{};return{domain:Le(e.domain)??null,storefrontToken:Le(e.storefrontToken)??null,sourceName:Le(e.sourceName)??null,countries:t,cartEnabled:e.cartEnabled}}(r):void 0,t)}catch{return Pe(void 0,t)}}function We(e,t){const{countries:n,country:r,...s}=e,i=function(e,t){if(void 0===t||""===t)return;const n=t.toLowerCase(),[r]=n.split(/[\-_]/v,1),s=Object.entries(e),i=s.find(([e])=>e.toLowerCase()===n)??s.find(([e])=>e.toLowerCase()===r);return ze(i?.[1])}(n,t)??r;return{...s,...void 0!==i&&{country:i}}}const Ve="callimacus:woocommerce-cart",He=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ge=e=>"string"==typeof e&&""!==e,Fe=(e,t,n={})=>({error:{code:e,message:t,...n}}),Je=e=>({data:e}),Ye=e=>e instanceof Error?e.message:String(e),Qe=(e,t)=>Number.isSafeInteger(e)&&e>=t;function Xe(e){try{return"string"==typeof e&&"https:"===new URL(e).protocol}catch{return!1}}const Ze={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ldquo:"“",rdquo:"”",lsquo:"‘",rsquo:"’",hellip:"…",ndash:"–",mdash:"—"};async function et(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return Fe("cart_unavailable","The store did not answer the cart request.",0===t?{}:{status:t});let n;try{n=await e.json()}catch{}if(e.ok)return He(n)&&Array.isArray(n.items)?Je(n):Fe("cart_unavailable","The store answered without the cart.",{status:t});if(429===t)return Fe("throttled","The store is busy. Try again in a moment.",{status:t});if(401===t||403===t)return Fe("cart_unavailable","The store refused the cart request.",{status:t});const r=He(n)&&Ge(n.code)?n.code:void 0,s=He(n)&&Ge(n.message)?function(e){let t,n=e.replaceAll(/&(?<name>#x[\da-f]+|#\d+|[a-z]+);/giv,(e,t)=>{if(t.startsWith("#")){const n="x"===t[1]||"X"===t[1]?Number.parseInt(t.slice(2),16):Number(t.slice(1));return Number.isSafeInteger(n)&&n>0&&n<=1114111?String.fromCodePoint(n):e}return Ze[t.toLowerCase()]??e});do{t=n,n=n.replaceAll(/<[^<>]*>/gv,"")}while(n!==t);return n.replaceAll(/[<>]/gv,"").trim()}(n.message):`The store answered ${t}.`;return void 0!==r&&t<500?Fe("refused",s,{status:t,storeCode:r}):Fe("http",s,{status:t})}function tt(e){const{storage:t,lock:n}=e,r=e.fetch??(async(e,t)=>fetch(e,t)),s=e.navigate??(e=>{location.assign(e)});function i(){const e=function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;return He(t)&&Xe(t.store)&&Xe(t.storeApi)&&Ge(t.token)?{store:t.store,storeApi:t.storeApi,token:t.token}:void 0}catch{return}}(t.getItem(Ve));if(void 0===e)return;const n=function(e){try{const[,t=""]=e.split(".",2),n=JSON.parse(atob(t.replaceAll("-","+").replaceAll("_","/")));return He(n)&&"number"==typeof n.exp?1e3*n.exp:void 0}catch{return}}(e.token);if(!(void 0===n||n-Date.now()<6e5))return e;t.removeItem(Ve)}function o(e){t.setItem(Ve,JSON.stringify(e))}async function a(e,t,n){const s={Accept:"application/json","Cart-Token":e.token};let a;void 0!==n&&(s["Content-Type"]="application/json");try{a=await r(`${e.storeApi}${t}`,{method:void 0===n?"GET":"POST",headers:s,...void 0!==n&&{body:JSON.stringify(n)},credentials:"omit",redirect:"manual",signal:(c=1e4,"function"==typeof AbortSignal.timeout?AbortSignal.timeout(c):void 0)})}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return Fe("network",t?"The store did not answer in time.":"Could not reach the store. Check your connection and try again.")}var c;const u=a.headers.get("Cart-Token");return Ge(u)&&i()?.token===e.token&&o({...e,token:u}),et(a)}let c=Promise.resolve();async function u(e){const t=c.then(async()=>{try{return await e()}catch(e){return Fe("cart_unavailable",Ye(e))}});return c=t.catch(()=>{}),t}async function l(e,t){return u(async()=>{const n=i();return void 0===n?Fe("no_cart","There is no cart yet."):a(n,e,t)})}async function d(){return u(async()=>{const e=i();return void 0===e?Je(void 0):a(e,"/cart")})}return{getCart:d,async addItem(t,r=1){const s=Number(t);return Qe(s,1)&&String(t).trim()===String(s)?Qe(r,1)?u(async()=>{const t=i()??await async function(){let t=!1;try{return await n("callimacus:woocommerce-cart-lock",async()=>{t=!0;const n=i();if(void 0!==n)return n;const r=await e.start();if(!Xe(r?.store)||!Xe(r.storeApi)||!Ge(r.cartToken))return Fe("cart_unavailable","No WooCommerce store is connected to this site.");const s={store:r.store,storeApi:r.storeApi,token:r.cartToken};return o(s),s})}catch(e){return t?Fe("cart_unavailable",Ye(e)):Fe("busy","The cart is being set up in another tab. Try again in a moment.")}}();return"error"in t?t:a(t,"/cart/add-item",{id:s,quantity:r})}):Fe("invalid_input",`Not a quantity to add: ${r}.`):Fe("invalid_input",`Not a WooCommerce product id: ${t}.`)},removeItem:async e=>Ge(e)?l("/cart/remove-item",{key:e}):Fe("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>Ge(e)&&Qe(t,0)?0===t?l("/cart/remove-item",{key:e}):l("/cart/update-item",{key:e,quantity:t}):Fe("invalid_input",`Not a cart line and quantity: ${e} × ${t}.`),async checkout(){const e=i(),n=await d();if(void 0!==n.error)return n;if(void 0===e||void 0===n.data||0===n.data.items.length)return Fe("no_cart","The cart is empty.");const r=function(e,t){const n=new URL(e.endsWith("/")?e:`${e}/`);return n.searchParams.set("checkout-link","1"),n.searchParams.set("products",t.map(e=>`${e.id}:${e.quantity}`).join(",")),n.href}(e.store,n.data.items);try{s(r)}catch(e){return Fe("cart_unavailable",Ye(e))}return t.removeItem(Ve),Je(r)}}}const nt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},rt=Object.entries({$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"});function st(e,t){t||(t=new Map);for(const n of e)"in"in n?n.key&&t.set(n.key,{in:n.in,map:n.map}):"key"in n?t.set(n.key,{map:n.map}):n.args&&st(n.args,t);return t}function it(e,t){const n={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},r=st(t);function s(e,t,r){let s=n[e];void 0===s&&(s=Object.create(null),n[e]=s),s[t]=r}let i;for(const[o,a]of e.entries())if(t[o]&&(i=t[o]),i)if("in"in i)if(i.key){const e=r.get(i.key),t=e.map||i.key;e.in&&s(e.in,t,a)}else n.body=a;else for(const[e,t]of Object.entries(a??{})){const o=r.get(e);if(o)if(o.in){const n=o.map||e;s(o.in,n,t)}else n[o.map]=t;else{const n=rt.find(([t])=>e.startsWith(t));if(n){const[r,i]=n;s(i,e.slice(r.length),t)}else if("allowExtra"in i&&i.allowExtra)for(const[n,r]of Object.entries(i.allowExtra))if(r){s(n,e,t);break}}}return function(e){for(const[t,n]of Object.entries(e))"body"!==t&&(!n||"object"!=typeof n||Array.isArray(n)||Object.keys(n).length||delete e[t])}(n),n}const ot=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),o=s.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):at({allowReserved:e,name:n,value:t})).join(i);return"label"===r||"matrix"===r?i+o:o},at=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},ct=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:i})=>{if(s instanceof Date)return i?s.toISOString():`${n}=${s.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(s).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const i=t.join(",");switch(r){case"form":return`${n}=${i}`;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return i}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(s).map(([t,s])=>at({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+a:a},ut=/\{[^{}]+\}/g,lt=({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let i=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(i=(({path:e,url:t})=>{let n=t;const r=t.match(ut);if(r)for(const t of r){let r=!1,s=t.substring(1,t.length-1),i="simple";s.endsWith("*")&&(r=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),i="label"):s.startsWith(";")&&(s=s.substring(1),i="matrix");const o=e[s];if(null==o)continue;if(Array.isArray(o)){n=n.replace(t,ot({explode:r,name:s,style:i,value:o}));continue}if("object"==typeof o){n=n.replace(t,ct({explode:r,name:s,style:i,value:o,valueOnly:!0}));continue}if("matrix"===i){n=n.replace(t,`;${at({name:s,value:o})}`);continue}const a=encodeURIComponent("label"===i?`.${o}`:o);n=n.replace(t,a)}return n})({path:t,url:i}));let o=n?r(n):"";return o.startsWith("?")&&(o=o.substring(1)),o&&(i+=`?${o}`),i};function dt(e){const t=void 0!==e.body;if(t&&e.bodySerializer){if("serializedBody"in e){return void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null}return""!==e.body?e.body:null}if(t)return e.body}const ht=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},yt=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const s in n){const i=n[s];if(null==i)continue;const o=e[s]||t;if(Array.isArray(i)){const e=ot({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:i,...o.array});e&&r.push(e)}else if("object"==typeof i){const e=ct({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:i,...o.object});e&&r.push(e)}else{const e=at({allowReserved:o.allowReserved,name:s,value:i});e&&r.push(e)}}return r.join("&")},ft=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`));const pt=e=>lt({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:yt(e.querySerializer),url:e.url}),mt=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=vt(e.headers,t.headers),n},gt=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},vt=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?gt(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t};class bt{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}}const kt=yt({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),wt={"Content-Type":"application/json"},Rt=(e={})=>({...nt,headers:wt,parseAs:"auto",querySerializer:kt,...e}),Tt=(e={})=>{let t=mt(Rt(),e);const n=()=>({...t}),r={error:new bt,request:new bt,response:new bt},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:vt(t.headers,e.headers),serializedBody:void 0};n.security&&await async function(e){for(const t of e.security??[]){if(ft(e,t.name))continue;const n=await ht(t,e.auth);if(!n)continue;const r=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[r]=n;break;case"cookie":e.headers.append("Cookie",`${r}=${n}`);break;default:e.headers.set(r,n)}}}(n),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type");return{opts:n,url:pt(n)}},i=async e=>{const n=e.throwOnError??t.throwOnError,i=e.responseStyle??t.responseStyle;let o,a;try{const{opts:t,url:n}=await s(e),i={redirect:"follow",...t,body:dt(t)};o=new Request(n,i);for(const e of r.request.fns)e&&(o=await e(o,t));const c=t.fetch;a=await c(o);for(const e of r.response.fns)e&&(a=await e(a,o,t));const u={request:o,response:a};if(a.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(a.headers.get("Content-Type")):t.parseAs)??"json";if(204===a.status||"0"===a.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await a[e]();break;case"formData":n=new FormData;break;case"stream":n=a.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...u}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"text":n=await a[e]();break;case"json":{const e=await a.text();n=e?JSON.parse(e):{};break}case"stream":return"data"===t.responseStyle?a.body:{data:a.body,...u}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...u}}const l=await a.text();let d;try{d=JSON.parse(l)}catch{}throw d??l}catch(t){let s=t;for(const t of r.error.fns)t&&(s=await t(s,a,o,e));if(s=s||{},n)throw s;return"data"===i?void 0:{error:s,request:o,response:a}}},o=e=>t=>i({...t,method:e}),a=e=>async t=>{const{opts:n,url:i}=await s(t);return function({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:i,sseMaxRetryAttempts:o,sseMaxRetryDelay:a,sseSleepFn:c,url:u,...l}){let d;const h=c??(e=>new Promise(t=>setTimeout(t,e))),y=async function*(){let c=i??3e3,y=0;const f=l.signal??(new AbortController).signal;for(;!f.aborted;){y++;const i=l.headers instanceof Headers?l.headers:new Headers(l.headers);void 0!==d&&i.set("Last-Event-ID",d);try{const t={redirect:"follow",...l,body:l.serializedBody,headers:i,signal:f};let o=new Request(u,t);e&&(o=await e(u,t));const a=l.fetch??globalThis.fetch,h=await a(o);if(!h.ok)throw new Error(`SSE failed: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("No body in SSE response");const y=h.body.pipeThrough(new TextDecoderStream).getReader();let p="";const m=()=>{try{y.cancel()}catch{}};f.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await y.read();if(e)break;p+=t,p=p.replace(/\r\n?/g,"\n");const i=p.split("\n\n");p=i.pop()??"";for(const e of i){const t=e.split("\n"),i=[];let o,a;for(const e of t)if(e.startsWith("data:"))i.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))o=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let u=!1;if(i.length){const e=i.join("\n");try{a=JSON.parse(e),u=!0}catch{a=e}}u&&(s&&await s(a),r&&(a=await r(a))),n?.({data:a,event:o,id:d,retry:c}),i.length&&(yield a)}}}finally{f.removeEventListener("abort",m),y.releaseLock()}break}catch(e){if(t?.(e),void 0!==o&&y>=o)break;const n=Math.min(c*2**(y-1),a??3e4);await h(n)}}}();return{stream:y}}({...n,body:n.body,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of r.request.fns)e&&(s=await e(s,n));return s},serializedBody:dt(n),url:i})};return{buildUrl:e=>pt({...t,...e}),connect:o("CONNECT"),delete:o("DELETE"),get:o("GET"),getConfig:n,head:o("HEAD"),interceptors:r,options:o("OPTIONS"),patch:o("PATCH"),post:o("POST"),put:o("PUT"),request:i,setConfig:e=>(t=mt(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:o("TRACE")}};class St{client;constructor(e){this.client=e.client}}class Et{defaultKey="default";instances=new Map;get(e){const t=this.instances.get(e??this.defaultKey);if(!t)throw new Error('No SDK client found. Create one with "new CallimacusApi()" to fix this error.');return t}set(e,t){this.instances.set(t??this.defaultKey,e)}}class It extends St{getPage(e,t){const n=it([e],[{args:[{in:"path",key:"language"},{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/page/{language}/{id}",...t,...n})}listTopics(e,t){const n=it([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}",...t,...n})}getTopicContents(e,t){const n=it([e],[{args:[{in:"path",key:"language"},{in:"path",key:"idOrSlug"},{in:"query",key:"offset"},{in:"query",key:"limit"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}/{idOrSlug}",...t,...n})}getDocumentBySlug(e,t){const n=it([e],[{args:[{in:"path",key:"language"},{in:"path",key:"slug"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/{language}/{slug}",...t,...n})}getDocumentByGroup(e,t){const n=it([e],[{args:[{in:"path",key:"language"},{in:"path",key:"groupId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-group/{language}/{groupId}",...t,...n})}getDocumentByPath(e,t){const n=it([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-path",...t,...n})}listDocuments(e,t){const n=it([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/documents/{language}",...t,...n})}}class Ct extends St{getShared(e,t){const n=it([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}share(e,t){const n=it([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}}class At extends St{getSimilar(e,t){const n=it([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"topK"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/similar",...t,...n})}getRecommendations(e,t){const n=it([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/recommendations",...t,...n})}}class Ot extends St{getLast(e,t){const n=it([e],[{args:[{in:"query",key:"storyId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/whisper",...t,...n})}}class xt extends St{trackEvent(e,t){const n=it([e],[{args:[{in:"body",key:"storyId"},{in:"body",key:"eventName"},{in:"body",key:"content"},{in:"body",key:"payload"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/track-event",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class $t extends St{getCart(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart",...e})}addItemToCart(e,t){const n=it([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/add",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}removeItemFromCart(e,t){const n=it([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/remove",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}updateProductQuantity(e,t){const n=it([e],[{args:[{in:"body",key:"productId"},{in:"body",key:"quantity"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/update",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class _t extends St{getStorefrontSettings(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/shopify/storefront",...e})}}class qt extends St{get(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/evaluation",...e})}}class Nt extends St{startCart(e){return(e?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/woocommerce/cart",...e})}}class Dt extends St{similar(e,t){const n=it([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"topK"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/similar",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}related(e,t){const n=it([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/related",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}getItemByPath(e,t){const n=it([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/item/by-path",...t,...n})}}class jt extends St{static __registry=new Et;constructor(e){super(e),jt.__registry.set(this,e.key)}_content;get content(){return this._content??=new It({client:this.client})}_stories;get stories(){return this._stories??=new Ct({client:this.client})}_products;get products(){return this._products??=new At({client:this.client})}_whisper;get whisper(){return this._whisper??=new Ot({client:this.client})}_analytics;get analytics(){return this._analytics??=new xt({client:this.client})}_cart;get cart(){return this._cart??=new $t({client:this.client})}_shopify;get shopify(){return this._shopify??=new _t({client:this.client})}_evaluation;get evaluation(){return this._evaluation??=new qt({client:this.client})}_woocommerce;get woocommerce(){return this._woocommerce??=new Nt({client:this.client})}_skesis;get skesis(){return this._skesis??=new Dt({client:this.client})}}class Ut extends Error{status;body;response;request;constructor(e,t,n){const r=t?.status,s=n?`${n.method} ${n.url}`:"request";let i=`[thamyr] ${s} failed before a response arrived`;t&&(i=t.ok?`[thamyr] ${s} → ${t.status}, but the response could not be processed`:`[thamyr] ${s} → ${t.status}`),super(i,e instanceof Error?{cause:e}:void 0),this.name="ThamyrHttpError",this.status=r,this.body=e,this.response=t,this.request=n}}function Lt(e){const t=Tt(Rt({baseUrl:new URL("api/v3",e.endpoint).href,headers:{Authorization:`Bearer ${e.accessToken}`,"x-sl-access-token":e.accessToken},credentials:e.withCredentials?"include":"same-origin"}));return t.interceptors.error.use((e,n,r,s)=>{if(!(s.throwOnError??t.getConfig().throwOnError??!1)||!0===s.signal?.aborted)return e;return new Ut(""===e?{}:e??{},n,r)}),t}export{P as ACTION_TYPES,$ as ADD_TO_CART_RESULT_BLOCK,jt as CallimacusApi,p as CallimacusEvent,S as CallimacusService,o as ChapterStatus,r as ClientEvents,Y as DELIVER_RESULT_BLOCK,i as GalleryMode,I as LANDING_VALUE_MAX_LENGTH,w as MAX_HANDSHAKE_RETRIES,s as SLInputEventType,ne as STOREFRONT_API_VERSION,n as ServerEvents,Ut as ThamyrHttpError,t as ThamyrResponseType,f as UserInteractionType,F as actionOf,D as addToCartResultOf,L as applyBlockPatch,x as blockKeyOf,E as callimacusService,We as cartSettingsFor,T as classifyConnectError,Lt as createContractClient,De as createPageStorage,je as createShopifyCart,tt as createWooCommerceCart,te as deliverResultOf,g as extractTtsAudio,J as fieldsOf,A as interactionRound,a as isCustomBlock,u as isMasterProduct,c as isSetProduct,we as isVariantGid,C as landingRound,qe as leaseLock,d as logger,Pe as mergeShopifySettings,k as parseConnectRejection,K as parseMapPath,y as randomUuid,Be as readShopifySettings,O as receptorsOf,M as resolveMapPage,R as shouldRetryHandshake,h as transformImageUrl,Ne as webLocks};
|
|
8
|
+
export*from"@callimacus/intent";import{io as e}from"socket.io-client";const t={ERROR:"error",CHAPTER_EVENT:"chapter-event",CHAPTER_DELETED:"chapter-deleted",STORY_RESET:"story-reset",STORY_CREATED:"story-created",STORY_SHARED:"story-shared",BLOCK_PATCH:"block-patch",CART_COMMAND:"cart-command"},n={ERROR:"error",SYSTEM_MESSAGE:"system-message",SERVER_STATUS:"server-status",SERVER_RESPONSE:"server-response"},r={CLIENT_READY:"client-ready",USER_INTERACTION:"user-interaction"},s={question:"question",content:"content",topic:"topic",tag:"tag",image:"image",video:"video",gallery:"gallery",relatedQuestion:"relatedQuestion",page:"page",customInteraction:"customInteraction",customPage:"customPage"},i={masonry:"masonry",carousel:"carousel"},o={understandingQuery:1,craftingAnswer:2,curatingContent:3,done:4};function a(e){return e.type.startsWith("custom:")}function c(e){return"set"in e.type&&e.type.set}function u(e){return"master"in e.type&&e.type.master}const l={debug:0,info:1,warn:2,error:3,silent:4};const d=new class{config={enabled:!1,level:"info",prefix:"[Thamyr]"};debug=(...e)=>{this.log("debug",...e)};info=(...e)=>{this.log("info",...e)};warn=(...e)=>{this.log("warn",...e)};error=(...e)=>{this.log("error",...e)};log(e,...t){if(!(this.config.enabled&&l[e]>=l[this.config.level]))return;const{prefix:n}=this.config,r=void 0===n||""===n?t:[n,...t];console[e](...r)}configure(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}};function h(e,t){const n=new URL(e),r=decodeURIComponent(n.pathname.slice(1)),s=(new TextEncoder).encode(JSON.stringify({bucket:"storage.callimacus.ai",key:r,edits:t})).toBase64();return`${n.origin}/${encodeURIComponent(s)}`}function y(){const e="undefined"==typeof crypto?void 0:crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();const t=new Uint8Array(16);if("function"==typeof e?.getRandomValues)e.getRandomValues(t);else for(let e=0;e<16;e++)t[e]=Math.floor(256*Math.random());t[6]=15&t[6]|64,t[8]=63&t[8]|128;const n=[...t].map(e=>e.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("-")}var f,p;function m(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.audioUrl&&"string"==typeof t.mimeType}function g(e){if("object"==typeof e&&null!==e)for(const t of Object.values(e))if(m(t))return t}!function(e){e.GET_STORY="get-story",e.CREATE_ROUND="create-round",e.RESET_STORY="reset-story",e.BACK_FROM_ROUND="back-from-round",e.SHARE_STORY="share-story",e.GET_SHARED_STORY="get-shared-story",e.SUGGEST="suggest"}(f||(f={})),function(e){e.ROUND_CREATED="round-created",e.ROUND_EVENT="round-event",e.ROUND_COMPLETED="round-completed",e.ERROR="error"}(p||(p={}));const v={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class b{elements=new Map;elementRefs=new Map;elementKeys=new WeakMap;blocks=new Map;blockRefs=new Map;blockKeys=new WeakMap;started=!1;config;constructor(e={}){const t=e.minVisibilityRatio??v.minVisibilityRatio;this.config={productSelector:e.productSelector??v.productSelector,blockSelector:e.blockSelector??v.blockSelector,maxTrackedElements:e.maxTrackedElements??v.maxTrackedElements,minVisibilityRatio:Math.min(1,Math.max(0,t))}}rescanUi(){if(!this.canUseDom())return;let e,t;try{e=document.querySelectorAll(this.config.productSelector),t=document.querySelectorAll(this.config.blockSelector)}catch(e){return void d.warn("UI Observer: invalid selector, skipping rescan:",e)}const n=Date.now();for(const t of e){const e=this.normalizeRect(t.getBoundingClientRect()),r=this.calculateVisibilityRatio(e);this.syncTrackedElement(t,{bounds:e,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}for(const e of t){const t=this.normalizeRect(e.getBoundingClientRect()),r=this.calculateVisibilityRatio(t);this.syncTrackedBlock(e,{bounds:t,isVisible:r>=this.config.minVisibilityRatio,visibilityRatio:r,observedAt:n})}this.pruneTrackedElements(),this.pruneTrackedBlocks()}pruneTrackedElements(){if(this.elements.size<=this.config.maxTrackedElements)return;const e=[...this.elements].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.elements.size-this.config.maxTrackedElements);for(const[t]of e)this.elements.delete(t),this.elementRefs.delete(t)}pruneTrackedBlocks(){if(this.blocks.size<=this.config.maxTrackedElements)return;const e=[...this.blocks].sort(([,e],[,t])=>{const n=e.visibilityRatio-t.visibilityRatio;return 0===n||Number.isNaN(n)?e.observedAt-t.observedAt:n}).slice(0,this.blocks.size-this.config.maxTrackedElements);for(const[t]of e)this.blocks.delete(t),this.blockRefs.delete(t)}syncTrackedElement(e,t){const n=this.resolveElementId(e),r=this.resolveBlockId(e),s=this.createTrackingKey(n,r),i=this.elementKeys.get(e);void 0!==i&&""!==i&&i!==s&&(this.elements.delete(i),this.elementRefs.delete(i)),this.elementKeys.set(e,s),this.elementRefs.set(s,e),this.elements.set(s,{id:n,blockId:r,trackingKey:s,...t})}syncTrackedBlock(e,t){const n=this.resolveTrackedBlockId(e),r=this.blockKeys.get(e),s=n;void 0!==r&&""!==r&&r!==s&&(this.blocks.delete(r),this.blockRefs.delete(r)),this.blockKeys.set(e,s),this.blockRefs.set(s,e),this.blocks.set(s,{id:n,...t})}resolveElementId(e){return[e.dataset.productId,e.dataset.productid,e.dataset.sku,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.productId??this.elements.size}`}resolveBlockId(e){let t;try{t=e.closest(this.config.blockSelector)??void 0}catch{return}return t instanceof HTMLElement?this.resolveTrackedBlockId(t):void 0}resolveTrackedBlockId(e){return[e.dataset.blockId,e.dataset.blockid,e.id].find(e=>void 0!==e&&""!==e)??`${e.tagName}-${e.dataset.blockId??this.blocks.size}`}createTrackingKey(e,t){return void 0===t||""===t?e:`${e}::${t}`}normalizeRect(e){return{x:e.x,y:e.y,width:e.width,height:e.height,top:e.top,left:e.left,right:e.right,bottom:e.bottom}}calculateVisibilityRatio(e){const t=Math.max(0,Math.min(e.right,window.innerWidth)-Math.max(e.left,0))*Math.max(0,Math.min(e.bottom,window.innerHeight)-Math.max(e.top,0)),n=e.width*e.height;if(n<=0)return 0;const r=window.innerWidth*window.innerHeight,s=r>0?Math.min(n,r):n;return Math.min(1,Math.max(0,t/s))}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 e=[],t=[],n=Date.now();for(const[t,n]of this.elements){const r=this.elementRefs.get(t);r?.isConnected?n.visibilityRatio<=0||e.push({blockId:n.blockId,element:{id:n.id,bounds:n.bounds,isVisible:n.visibilityRatio>=this.config.minVisibilityRatio,visibilityRatio:n.visibilityRatio}}):(this.elements.delete(t),this.elementRefs.delete(t))}for(const[e,n]of this.blocks){const r=this.blockRefs.get(e);r?.isConnected?n.visibilityRatio<this.config.minVisibilityRatio||t.push(n.id):(this.blocks.delete(e),this.blockRefs.delete(e))}const r=e.slice(0,this.config.maxTrackedElements);return{timestamp:n,viewport:{width:window.innerWidth,height:window.innerHeight},blockIds:[...new Set([...t,...r.flatMap(e=>e.blockId??[])])],elements:r.map(e=>e.element)}}}function k(e){const{data:t}=e;if("object"!=typeof t||null===t)return;const{code:n,reason:r}=t;return"number"==typeof n?{code:n,..."string"==typeof r&&{reason:r}}:void 0}const w=3;function R(e,t){return e>=500&&t<3}function T(e,t){return t?void 0:k(e)??{code:0}}const S=200;function E(e,t={}){if(void 0!==e&&e.length>200)throw new RangeError("[thamyr] landing value exceeds 200 characters");return{inputEvent:{type:"customPage",data:void 0===e?{}:{value:e}},...t}}function I(e,t={}){const{block:n,payload:r,submissionId:s,value:i,...o}=t;return{inputEvent:{type:"customInteraction",data:{interactionId:e,...void 0!==n&&{nodeKey:n},...void 0!==r&&{payload:r},...void 0!==s&&{submissionId:s},...void 0!==i&&{value:i}}},...o}}function C(e){return e.receptors??e.intent??[]}function A(e){return"key"in e?e.key:void 0}const O="custom:addToCartResult";function x(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}const $=e=>"string"==typeof e&&e.length>0,_=e=>x(e)&&$(e.size)&&$(e.variantId)&&"boolean"==typeof e.orderable;function q(e){if(!x(e.data)||!x(e.data.addToCart))return;const t=e.data.addToCart;return"error"===t.status?{status:"error"}:"resolved"===t.status&&$(t.variantId)&&$(t.productName)&&$(t.size)?{status:"resolved",variantId:t.variantId,productName:t.productName,size:t.size}:"size_selection_needed"===t.status&&$(t.productSku)&&$(t.productName)&&Array.isArray(t.availableSizes)&&t.availableSizes.every(_)?{status:"size_selection_needed",productSku:t.productSku,productName:t.productName,availableSizes:t.availableSizes}:void 0}const N=e=>x(e)?e:{};function D(e,t,n){const[r,...s]=t;if(!x(e)||!Object.hasOwn(e,r))return;const i=0===s.length?function(e,t){if(x(e)&&"string"==typeof e.docId)return{...e,values:{...N(e.values),...t.values},inputs:{...N(e.inputs),...t.inputs},textRuns:{...N(e.textRuns),...t.textRuns}}}(e[r],n):D(e[r],s,n);return i&&{...e,[r]:i}}function j(e,t){const n=e.blocks??[],r=e.id===t.chapterId?n.findIndex(e=>e.id===t.blockId):-1;if(-1===r)return e;const s=n[r],i=D(s.data,t.contentId.split("."),t);return i?{...e,blocks:n.with(r,{...s,data:i})}:e}function U(e,t){return(e.warnings??[]).filter(n=>{const r=`${e.id}:${n.block}:${n.content}`;return!t.has(r)&&(t.add(r),!0)})}class L{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;warningListeners=new Set;reportedWarnings=new Set;uiObserver;uiObserverConfig=v;handshakeRetryAttempts=0;handshakeRetryTimer;setupEventListeners(){this.socket&&(this.socket.on("connect",()=>{d.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(r.CLIENT_READY)}),this.socket.on("disconnect",()=>{d.info("Disconnected from Callimacus"),this.updateConnectionStatus(!1)}),this.socket.on("connect_error",e=>{this.updateConnectionStatus(!1);const t=T(e,this.socket?.active??!0);t&&(d.error("Connection refused by Callimacus:",e.message,t.reason??""),this.notifyRejection(t,e.message),this.scheduleHandshakeRetry(t.code))}),this.socket.on(n.ERROR,e=>{d.error("Received error from Callimacus:",e),this.notifyErrorListeners(e)}),this.socket.io.on("reconnect",e=>{d.info(`Reconnected to Callimacus after ${e} attempts`)}),this.socket.io.on("reconnect_attempt",e=>{d.info(`Attempting to reconnect: attempt ${e}`)}),this.socket.io.on("reconnect_error",e=>{d.error("Reconnection error:",e)}),this.socket.io.on("reconnect_failed",()=>{d.error("Failed to reconnect to Callimacus service!"),this.updateConnectionStatus(!1)}),this.socket.on(n.SERVER_RESPONSE,e=>{"chapter-event"===e.type&&this.notifyWarningListeners(U(e.chapter,this.reportedWarnings)),this.notifyServerResponseListeners(e)}))}notifyServerResponseListeners(e){this.serverResponseListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in server response listener:",e)}})}updateConnectionStatus(e){this.connectionStatusListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in connection status listener:",e)}})}notifyRejection(e,t){this.notifyErrorListeners({code:e.code,message:t,...void 0!==e.reason&&{reason:e.reason}})}scheduleHandshakeRetry(e){if(!this.socket)return;if(this.clearHandshakeRetry(),!R(e,this.handshakeRetryAttempts))return void(e>=500&&(d.error("Giving up on the Callimacus connection after 3 retries"),this.notifyRejection({code:e,reason:"retries_exhausted"},"Connection failed after 3 retries; call connect() to try again")));const t=2**(this.handshakeRetryAttempts+1);this.handshakeRetryAttempts+=1,d.info(`Retrying Callimacus connection in ${t}s (attempt ${this.handshakeRetryAttempts}/3)`),this.handshakeRetryTimer=setTimeout(()=>{this.socket?.connect()},1e3*t)}clearHandshakeRetry(){void 0!==this.handshakeRetryTimer&&(clearTimeout(this.handshakeRetryTimer),this.handshakeRetryTimer=void 0)}notifyErrorListeners(e){this.errorListeners.forEach(t=>{try{t(e)}catch(e){d.error("Error in error listener:",e)}})}notifyWarningListeners(e){for(const t of e)0===this.warningListeners.size&&d.warn(`Block "${t.block}" was not shown: its content "${t.content}" failed (${t.cause}). \`callimacus thamyr probe\` shows why.`),this.warningListeners.forEach(e=>{try{e(t)}catch(e){d.error("Error in warning listener:",e)}})}async getLocation(){if("undefined"!=typeof navigator&&"function"==typeof navigator.geolocation?.getCurrentPosition)return new Promise(e=>{navigator.geolocation.getCurrentPosition(t=>{e(t)},()=>{e(void 0)})})}enrichPayloadWithUiContext(e){try{this.ensureUiObserver();const t=this.uiObserver?.getSnapshot();return t?{...e,context:{...e.context,uiSnapshot:t}}:e}catch(t){return d.error("Error enriching payload with UI context:",t),e}}ensureUiObserver(){"undefined"!=typeof window&&"undefined"!=typeof document&&this.uiObserverConfig.enabled&&(this.uiObserver??=new b(this.uiObserverConfig),this.uiObserver.start())}socketEndpoint(e){const t=new URL(e),n=new URL("thamyr",t).pathname;return{origin:t.origin,path:n}}connect(t="wss://localhost:4000",n,r){this.socket&&(d.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 o="undefined"==typeof document?void 0:function(e){const t="intent_sid=",n=e.split("; ").find(e=>e.startsWith(t))?.slice(11);return void 0===n||""===n?void 0:n}(document.cookie),a={...void 0!==i&&""!==i&&{referrer:i},...void 0!==o&&{intentSid:o},...r};d.info("Connecting to Thamyr at",s),this.socket=e(s.origin,{path:s.path,transports:["websocket","polling"],tryAllTransports:!0,extraHeaders:n,auth:a}),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),d.info("Disconnected from Callimacus"))}configureUiObserver(e){if(!e)return this.uiObserver?.stop(),this.uiObserver=void 0,void(this.uiObserverConfig={...v,enabled:!1});const t=e.enabled??(void 0!==e.productSelector||void 0!==e.blockSelector||void 0!==e.maxTrackedElements||void 0!==e.minVisibilityRatio||this.uiObserverConfig.enabled);if(this.uiObserverConfig={...this.uiObserverConfig,...e,enabled:t},"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 b(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(e,t){if(!this.socket)return void d.error("Socket is not connected. Cannot send interaction.");if(e===f.SUGGEST)return void d.error("SUGGEST is a request/response command. Use suggest() instead.");if(e===f.BACK_FROM_ROUND){if(void 0===t.chapterId)return void d.error("BACK_FROM_ROUND requires chapterId.")}const n={type:e,payload:this.enrichPayloadWithUiContext(t)},s={id:y()};this.socket.emit(r.USER_INTERACTION,{type:n.type,payload:n.payload},s.id)}async suggest(e,t={}){if(!this.socket?.connected)return{suggestions:[]};try{return function(e){const t=e?.suggestions;return{suggestions:Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}}(await this.socket.timeout(t.timeoutMs??4e3).emitWithAck(r.USER_INTERACTION,{type:f.SUGGEST,payload:e}))}catch(e){return d.warn("Suggestions failed or timed out; serving none.",e),{suggestions:[]}}}async gatherClientInfo(){const e="undefined"==typeof navigator?void 0:navigator,t="undefined"==typeof window?void 0:window.screen;return{userAgent:e?.userAgent??"",language:e?.language??"",timezone:(new Intl.DateTimeFormat).resolvedOptions().timeZone,localTime:(new Date).toLocaleString(),screenResolution:void 0===t?"":`${t.width}x${t.height}`,location:await this.getLocation()}}onServerResponse(e){return this.serverResponseListeners.add(e),()=>{this.serverResponseListeners.delete(e)}}onConnectionStatus(e){return this.connectionStatusListeners.add(e),()=>{this.connectionStatusListeners.delete(e)}}onError(e){return this.errorListeners.add(e),()=>{this.errorListeners.delete(e)}}onWarning(e){return this.warningListeners.add(e),()=>{this.warningListeners.delete(e)}}}const K=new L;function z(e){const t=/^\/?map\/(?<language>[^\/]+)(?:\/(?<slug>.*))?$/v.exec(e)?.groups,n=t?.language;if(void 0===n||""===n)return;const r=t?.slug;return void 0===r||""===r?{language:n}:{language:n,slug:r}}async function M(e){try{const{data:t}=await e();return t}catch(e){if("object"==typeof e&&null!==e&&404===e.status)return;throw e}}async function P(e,t){const n=z(t);if(!n)return;const{language:r,slug:s}=n;if(void 0===s){const{data:t}=await e.content.listDocuments({language:r},{throwOnError:!0});return{kind:"index",language:r,entries:t}}const i=`/map/${r}/${s}`,o=await M(async()=>e.content.getDocumentByPath({path:i},{throwOnError:!0}));if(o)return{kind:"document",language:r,slug:s,document:o};if(!s.includes("/"))return;const a=await M(async()=>e.skesis.getItemByPath({path:i},{throwOnError:!0}));return a&&{kind:"item",language:r,slug:s,itemPage:a}}const B=["link","ask","interact","cart","submit"],W=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),V=e=>"string"==typeof e&&e.trim().length>0,H=new Set(["http:","https:","mailto:","tel:"]),G=e=>{try{return H.has(new URL(e,"https://relative.invalid").protocol)}catch{return!1}};function F(e){const{id:t,value:n,payload:r,block:s}=e,i=void 0===n||"string"==typeof n||(e=>Array.isArray(e)&&e.every(e=>"string"==typeof e))(n),o=void 0===r||W(r);if(i&&o&&(void 0===s||"string"==typeof s)&&V(t))return{type:"interact",id:t,...void 0!==n&&{value:n},...void 0!==r&&{payload:r},...void 0!==s&&{block:s}}}function J(e){if(W(e))switch(e.type){case"link":return function(e){const{url:t,newTab:n}=e;return(void 0===n||"boolean"==typeof n)&&V(t)&&G(t)?{type:"link",url:t,...void 0!==n&&{newTab:n}}:void 0}(e);case"ask":return V(e.value)?{type:"ask",value:e.value}:void 0;case"interact":return F(e);case"cart":return V(e.productId)?{type:"cart",productId:e.productId}:void 0;case"submit":return V(e.form)?{type:"submit",form:e.form}:void 0;default:return}}function Y(e){const t=e instanceof FormData?e:new FormData(e),n=[];for(const e of new Set(t.keys())){const r=t.getAll(e).filter(e=>"string"==typeof e),s=e.endsWith("[]");r.length>0&&n.push([s?e.slice(0,-2):e,s||r.length>1?r:r[0]])}return Object.fromEntries(n)}const Q="custom:deliverResult",X=new Set(["done","pending","ambiguous","skipped"]),Z=e=>void 0===e||"string"==typeof e,ee=e=>W(e)&&"string"==typeof e.message&&Z(e.field),te=e=>W(e)&&"string"==typeof e.status&&X.has(e.status)&&Z(e.ref);function ne(e){const t=e.type===Q&&W(e.data)?e.data:void 0;if(void 0===t)return;const{status:n,submissionId:r,message:s,redirect:i,errors:o,results:a}=t;var c;return("accepted"===n||"refused"===n)&&V(r)&&Z(s)&&Z(i)&&(void 0===o||Array.isArray(o)&&o.every(ee))&&(W(c=a)&&Object.values(c).every(te))?{status:n,submissionId:r,results:a,...void 0!==s&&{message:s},...void 0!==i&&G(i)&&{redirect:i},...void 0!==o&&{errors:o}}:void 0}const re="2026-10",se=15e3,ie=2e4,oe="fragment CartFields on Cart {\n\tid checkoutUrl totalQuantity\n\tcost {subtotalAmount {amount currencyCode} totalAmount {amount currencyCode}}\n\tlines(first: 100) {nodes {\n\t\tid quantity\n\t\tmerchandise {... on ProductVariant {id title product {title handle} image {url altText} price {amount currencyCode} selectedOptions {name value}}}\n\t\tcost {totalAmount {amount currencyCode}}\n\t}}\n}",ae=(e,t,n)=>`mutation ${e}(${t}, $country: CountryCode) @inContext(country: $country) {${n} {cart {...CartFields} userErrors {code field message} warnings {code message target}}}\n${oe}`,ce=`query CartQuery($id: ID!, $country: CountryCode) @inContext(country: $country) {cart(id: $id) {...CartFields}}\n${oe}`,ue=ae("CartCreate","$input: CartInput!","cartCreate(input: $input)"),le=ae("CartLinesAdd","$cartId: ID!, $lines: [CartLineInput!]!","cartLinesAdd(cartId: $cartId, lines: $lines)"),de=ae("CartLinesUpdate","$cartId: ID!, $lines: [CartLineUpdateInput!]!","cartLinesUpdate(cartId: $cartId, lines: $lines)"),he=ae("CartLinesRemove","$cartId: ID!, $lineIds: [ID!]!","cartLinesRemove(cartId: $cartId, lineIds: $lineIds)"),ye="The store is busy. Try again in a moment.",fe="The store is not open to the cart: its storefront password may be on.",pe=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),me=e=>"string"==typeof e&&""!==e,ge=(e,t)=>({error:{code:e,message:t},warnings:[]});const ve=(e,t=[])=>({data:e,warnings:t}),be=(e,t,n)=>({error:{code:e,message:t,...void 0!==n&&{status:n}},isRefusedAccess:!1}),ke=e=>({error:{code:"cart_unavailable",message:"The store refused the cart request.",status:e},isRefusedAccess:!0}),we=/^gid:\/\/shopify\/ProductVariant\/\d+$/v,Re=e=>we.test(e);const Te=(e,t)=>Number.isSafeInteger(e)&&e>=t,Se=e=>({...e,lines:e.lines?.nodes??[]});const Ee=e=>e.lines.map(e=>({id:e.id,merchandiseId:e.merchandise.id,quantity:e.quantity})),Ie=e=>e.map(({merchandiseId:e,quantity:t})=>({merchandiseId:e,quantity:t}));function Ce(e,t){const n=Ie(e),r=n.find(e=>e.merchandiseId===t.merchandiseId);return r?r.quantity+=t.quantity:n.push(t),n}async function Ae(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return be("cart_unavailable",fe,0===t?void 0:t);if(430===t||429===t)return be("throttled",ye,t);if(401===t||403===t)return ke(t);if(!e.ok)return be("http",`The store answered ${t}.`,t);let n;try{n=await e.json()}catch{return be("cart_unavailable",fe,t)}return pe(n)&&pe(n.data)?{data:n.data}:function(e,t){const n=pe(e)&&Array.isArray(e.errors)?e.errors:[],r=new Set(n.map(e=>pe(e)&&pe(e.extensions)?e.extensions.code:void 0));if(r.has("THROTTLED"))return be("throttled",ye,t);if(r.has("ACCESS_DENIED")||r.has("UNAUTHORIZED")||r.has("FORBIDDEN"))return ke(t);const s=n.find(e=>pe(e)&&me(e.message));return be("graphql",pe(s)&&me(s.message)?s.message:"The store could not read the cart request.",t)}(n,t)}const Oe=e=>e instanceof Error?e.message:String(e);async function xe(e){return new Promise(t=>{setTimeout(t,e)})}function $e(e){return"function"==typeof AbortSignal.timeout?AbortSignal.timeout(e):void 0}function _e(){try{return localStorage}catch{return}}function qe(e){const t=new Map;return{getItem(n){try{const t=e?.getItem(n);if("string"==typeof t)return t}catch{}return t.get(n)??null},setItem(n,r){try{if(void 0!==e)return e.setItem(n,r),void t.delete(n)}catch{}t.set(n,r)},removeItem(n){t.delete(n);try{e?.removeItem(n)}catch{}}}}function Ne(e,t={}){const{waitMs:n=ie,ttlMs:r=se,retryMs:s=50,settleMs:i=30}=t;return async(t,o)=>{const a=`${t}:lease`,c=`${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`,u=()=>{const t=function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;return pe(t)&&me(t.owner)&&"number"==typeof t.expires?{owner:t.owner,expires:t.expires}:void 0}catch{return}}(e.getItem(a));return void 0!==t&&t.expires>Date.now()?t.owner:void 0},l=Date.now()+n;let d=!1;for(;!d;){if(void 0===u()){try{e.setItem(a,JSON.stringify({owner:c,expires:Date.now()+r}))}catch{return o()}if(await xe(i),d=u()===c,d)continue}if(Date.now()>=l)throw new Error(`[thamyr] the ${t} lock was not granted within ${n} ms`);await xe(s)}try{return await o()}finally{u()===c&&e.removeItem(a)}}}function De(){const e=globalThis.navigator?.locks;if("function"==typeof e?.request)return async(t,n)=>{const r=$e(ie);return e.request(t,r?{signal:r}:{},async()=>n())}}function je(){return qe(_e())}function Ue(e){const t=qe(e.storage??_e()),n=e.lock??De()??Ne(t),r=e.fetch??(async(e,t)=>fetch(e,t)),s=e.navigate??(e=>{location.assign(e)});function i(e){const s=`callimacus:shopify-cart:${e.cartKey??e.storeDomain}`,i=`callimacus:shopify-cart-lock:${e.cartKey??e.storeDomain}`,o=void 0!==e.storefrontToken,a=()=>function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;if(!pe(t)||!me(t.id)||!t.id.startsWith("gid://shopify/Cart/"))return;const n=Array.isArray(t.lines)?t.lines:[];return{id:t.id,lines:n.filter(e=>pe(e)&&me(e.id)&&me(e.merchandiseId)&&"number"==typeof e.quantity)}}catch{return}}(t.getItem(s));function c(e){return t.setItem(s,JSON.stringify({id:e.id,lines:Ee(e)})),e}function u(e){a()?.id===e&&t.removeItem(s)}async function l(t,n){const s={"Content-Type":"application/json",Accept:"application/json"};void 0!==e.storefrontToken&&(s["X-Shopify-Storefront-Access-Token"]=e.storefrontToken);try{const i=await r(`https://${e.storeDomain}/api/${re}/graphql.json`,{method:"POST",headers:s,body:JSON.stringify({query:t,variables:{...n,country:e.country??null}}),redirect:"manual",signal:$e(1e4)});return await Ae(i)}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return be("network",t?"The store did not answer in time.":"Could not reach the store. Check your connection and try again.")}}async function d(e){return l(ce,{id:e})}async function h(e,t,n){const r=await l(t,n);if("error"in r)return o&&r.isRefusedAccess?{refusedAccess:r.error}:{error:r.error,warnings:[]};const s=r.data[e];if(!pe(s))return ge("graphql","The store answered without the cart.");const i=Array.isArray(s.userErrors)?s.userErrors:[],a=Array.isArray(s.warnings)?s.warnings:[];if(!s.cart&&i.every(e=>e.field?.includes("cartId")??!1))return{isGone:!0};const u=s.cart?c(Se(s.cart)):void 0;return i.length>0?{...void 0!==u&&{data:u},error:{code:"refused",message:i.map(e=>e.message).join(" "),userErrors:i},warnings:a}:ve(u,a)}function y(e,t){return"isGone"in e?(u(t),ge("no_cart","The cart is no longer there.")):"refusedAccess"in e?{error:e.refusedAccess,warnings:[]}:e}async function f(t,r,s){let o,l=!1;try{o=await n(i,async()=>{l=!0;const n=a();return void 0!==n&&n.id!==s?n:0===t.length?(void 0!==s&&u(s),ve(void 0)):async function(t){const n={lines:t,...void 0!==e.country&&{buyerIdentity:{countryCode:e.country}},...void 0!==e.sourceName&&{sourceName:e.sourceName}},r=await h("cartCreate",ue,{input:n});return"isGone"in r?ge("graphql","The store created no cart."):"refusedAccess"in r?{error:r.refusedAccess,warnings:[]}:r}(t)})}catch(e){return l?ge("cart_unavailable",Oe(e)):ge("busy","The cart is being set up in another tab. Try again in a moment.")}if("warnings"in o)return o;if(r.length>0)return y(await h("cartLinesAdd",le,{cartId:o.id,lines:r}),o.id);const f=await d(o.id);return"error"in f?{error:f.error,warnings:[]}:ve(f.data.cart?c(Se(f.data.cart)):void 0)}return{hasToken:o,read:a,keep:c,drop:u,query:d,change:async function(e,t,n){const r=await h(t.field,t.document,{cartId:e.id,...t.variables});return"isGone"in r&&void 0!==n.whenGone?f(n.whenGone,n.added??[],e.id):"refusedAccess"in r?f(n.whenRefused,n.added??[],e.id):y(r,e.id)},createOnce:f}}let o=Promise.resolve();async function a(t){const n=o.then(async()=>async function(t){let n;try{n=await e.settings()}catch(e){return ge("cart_unavailable",Oe(e))}if(!n.cartEnabled)return ge("cart_disabled","The cart is off on this site.");const{storeDomain:r}=n;if(void 0===r)return ge("cart_unavailable","No Shopify store is set up for this site.");try{return await t(i({...n,storeDomain:r}))}catch(e){return ge("cart_unavailable",Oe(e))}}(t));return o=n.catch(()=>{}),n}async function c(){return a(async e=>{const t=e.read();if(void 0===t)return ve(void 0);const n=await e.query(t.id);return"error"in n?n.isRefusedAccess&&e.hasToken?e.createOnce(Ie(t.lines),[],t.id):{error:n.error,warnings:[]}:n.data.cart?ve(e.keep(Se(n.data.cart))):(e.drop(t.id),ve(void 0))})}const u={getCart:c,async addItem(e,t=1){const n=function(e){if("string"==typeof e)return Re(e)?e:/^\d+$/v.test(e)?`gid://shopify/ProductVariant/${e}`:void 0}(e);if(void 0===n)return ge("invalid_input",`Not a Shopify product variant id: ${e}.`);if(!Te(t,1))return ge("invalid_input",`Not a quantity to add: ${t}.`);const r={merchandiseId:n,quantity:t},s=await a(async e=>{const t=e.read();return void 0===t?e.createOnce([r],[r]):e.change(t,{field:"cartLinesAdd",document:le,variables:{lines:[r]}},{whenGone:[r],whenRefused:Ce(t.lines,r),added:[r]})}),i=function(e,t){if(void 0!==e.error||void 0===e.data)return;const{lines:n}=e.data;for(const r of e.warnings){const e="MERCHANDISE_OUT_OF_STOCK"===r.code?n.find(e=>0===e.quantity&&e.merchandise.id===t):void 0;if(void 0!==e)return{line:e,warning:r}}}(s,n);if(void 0===i)return s;return{data:(await u.removeItem(i.line.id)).data??s.data,error:{code:"refused",message:i.warning.message},warnings:s.warnings}},removeItem:async e=>me(e)?a(async t=>{const n=t.read();return void 0===n?ge("no_cart","There is no cart yet."):t.change(n,{field:"cartLinesRemove",document:he,variables:{lineIds:[e]}},{whenRefused:Ie(n.lines.filter(t=>t.id!==e))})}):ge("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>me(e)&&Te(t,0)?a(async n=>{const r=n.read();if(void 0===r)return ge("no_cart","There is no cart yet.");const s=r.lines.map(n=>n.id===e?{...n,quantity:t}:n).filter(e=>e.quantity>0);return n.change(r,{field:"cartLinesUpdate",document:de,variables:{lines:[{id:e,quantity:t}]}},{whenRefused:Ie(s)})}):ge("invalid_input",`Not a cart line and quantity: ${e} × ${t}.`),async checkout(){const e=await c();if(void 0!==e.error)return{error:e.error,warnings:e.warnings};const t=e.data;if(void 0===t||0===t.totalQuantity)return ge("no_cart","The cart is empty.");if(!function(e){try{return"https:"===new URL(e).protocol}catch{return!1}}(t.checkoutUrl))return ge("cart_unavailable","The store answered without a checkout link.");try{s(t.checkoutUrl)}catch(e){return ge("cart_unavailable",Oe(e))}return ve(t.checkoutUrl,e.warnings)}};return u}const Le=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ke=e=>"string"==typeof e&&""!==e.trim()?e.trim():void 0;function ze(e){const t=e?.trim()??"";if(""!==t)try{const{host:e}=new URL(/^https?:\/\//iv.test(t)?t:`https://${t}`);return""===e?void 0:e}catch{return}}const Me=e=>void 0!==e&&/^[a-z]{2}$/iv.test(e)?e.toUpperCase():void 0;const Pe=(e,t)=>ze(e?.storeDomain)??t;function Be(e,t){const n=ze(e?.domain??t?.storeDomain),r=e?.storefrontToken??Ke(t?.storefrontToken),s=e?.sourceName??void 0,i=Me(t?.country);return{cartEnabled:e?.cartEnabled??!0,...void 0!==n&&{storeDomain:n,cartKey:Pe(t,n)},...void 0!==r&&{storefrontToken:r},...void 0!==s&&{sourceName:s},countries:e?.countries??{},...void 0!==i&&{country:i}}}async function We(e,t){try{const n="function"==typeof AbortSignal.timeout?AbortSignal.timeout(5e3):void 0,{data:r,response:s}=await e.get({url:"/shopify/storefront",...void 0!==n&&{signal:n}});return Be(200===s?.status?function(e){if(!Le(e)||"boolean"!=typeof e.cartEnabled)return;const t=Le(e.countries)?Object.fromEntries(Object.entries(e.countries).filter(e=>"string"==typeof e[1])):{};return{domain:Ke(e.domain)??null,storefrontToken:Ke(e.storefrontToken)??null,sourceName:Ke(e.sourceName)??null,countries:t,cartEnabled:e.cartEnabled}}(r):void 0,t)}catch{return Be(void 0,t)}}function Ve(e,t){const{countries:n,country:r,...s}=e,i=function(e,t){if(void 0===t||""===t)return;const n=t.toLowerCase(),[r]=n.split(/[\-_]/v,1),s=Object.entries(e),i=s.find(([e])=>e.toLowerCase()===n)??s.find(([e])=>e.toLowerCase()===r);return Me(i?.[1])}(n,t)??r;return{...s,...void 0!==i&&{country:i}}}const He="callimacus:woocommerce-cart",Ge=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Fe=e=>"string"==typeof e&&""!==e,Je=(e,t,n={})=>({error:{code:e,message:t,...n}}),Ye=e=>({data:e}),Qe=e=>e instanceof Error?e.message:String(e),Xe=(e,t)=>Number.isSafeInteger(e)&&e>=t;function Ze(e){try{return"string"==typeof e&&"https:"===new URL(e).protocol}catch{return!1}}const et={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ldquo:"“",rdquo:"”",lsquo:"‘",rsquo:"’",hellip:"…",ndash:"–",mdash:"—"};async function tt(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return Je("cart_unavailable","The store did not answer the cart request.",0===t?{}:{status:t});let n;try{n=await e.json()}catch{}if(e.ok)return Ge(n)&&Array.isArray(n.items)?Ye(n):Je("cart_unavailable","The store answered without the cart.",{status:t});if(429===t)return Je("throttled","The store is busy. Try again in a moment.",{status:t});if(401===t||403===t)return Je("cart_unavailable","The store refused the cart request.",{status:t});const r=Ge(n)&&Fe(n.code)?n.code:void 0,s=Ge(n)&&Fe(n.message)?function(e){let t,n=e.replaceAll(/&(?<name>#x[\da-f]+|#\d+|[a-z]+);/giv,(e,t)=>{if(t.startsWith("#")){const n="x"===t[1]||"X"===t[1]?Number.parseInt(t.slice(2),16):Number(t.slice(1));return Number.isSafeInteger(n)&&n>0&&n<=1114111?String.fromCodePoint(n):e}return et[t.toLowerCase()]??e});do{t=n,n=n.replaceAll(/<[^<>]*>/gv,"")}while(n!==t);return n.replaceAll(/[<>]/gv,"").trim()}(n.message):`The store answered ${t}.`;return void 0!==r&&t<500?Je("refused",s,{status:t,storeCode:r}):Je("http",s,{status:t})}function nt(e){const{storage:t,lock:n}=e,r=e.fetch??(async(e,t)=>fetch(e,t)),s=e.navigate??(e=>{location.assign(e)});function i(){const e=function(e){try{const t="string"==typeof e?JSON.parse(e):void 0;return Ge(t)&&Ze(t.store)&&Ze(t.storeApi)&&Fe(t.token)?{store:t.store,storeApi:t.storeApi,token:t.token}:void 0}catch{return}}(t.getItem(He));if(void 0===e)return;const n=function(e){try{const[,t=""]=e.split(".",2),n=JSON.parse(atob(t.replaceAll("-","+").replaceAll("_","/")));return Ge(n)&&"number"==typeof n.exp?1e3*n.exp:void 0}catch{return}}(e.token);if(!(void 0===n||n-Date.now()<6e5))return e;t.removeItem(He)}function o(e){t.setItem(He,JSON.stringify(e))}async function a(e,t,n){const s={Accept:"application/json","Cart-Token":e.token};let a;void 0!==n&&(s["Content-Type"]="application/json");try{a=await r(`${e.storeApi}${t}`,{method:void 0===n?"GET":"POST",headers:s,...void 0!==n&&{body:JSON.stringify(n)},credentials:"omit",redirect:"manual",signal:(c=1e4,"function"==typeof AbortSignal.timeout?AbortSignal.timeout(c):void 0)})}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return Je("network",t?"The store did not answer in time.":"Could not reach the store. Check your connection and try again.")}var c;const u=a.headers.get("Cart-Token");return Fe(u)&&i()?.token===e.token&&o({...e,token:u}),tt(a)}let c=Promise.resolve();async function u(e){const t=c.then(async()=>{try{return await e()}catch(e){return Je("cart_unavailable",Qe(e))}});return c=t.catch(()=>{}),t}async function l(e,t){return u(async()=>{const n=i();return void 0===n?Je("no_cart","There is no cart yet."):a(n,e,t)})}async function d(){return u(async()=>{const e=i();return void 0===e?Ye(void 0):a(e,"/cart")})}return{getCart:d,async addItem(t,r=1){const s=Number(t);return Xe(s,1)&&String(t).trim()===String(s)?Xe(r,1)?u(async()=>{const t=i()??await async function(){let t=!1;try{return await n("callimacus:woocommerce-cart-lock",async()=>{t=!0;const n=i();if(void 0!==n)return n;const r=await e.start();if(!Ze(r?.store)||!Ze(r.storeApi)||!Fe(r.cartToken))return Je("cart_unavailable","No WooCommerce store is connected to this site.");const s={store:r.store,storeApi:r.storeApi,token:r.cartToken};return o(s),s})}catch(e){return t?Je("cart_unavailable",Qe(e)):Je("busy","The cart is being set up in another tab. Try again in a moment.")}}();return"error"in t?t:a(t,"/cart/add-item",{id:s,quantity:r})}):Je("invalid_input",`Not a quantity to add: ${r}.`):Je("invalid_input",`Not a WooCommerce product id: ${t}.`)},removeItem:async e=>Fe(e)?l("/cart/remove-item",{key:e}):Je("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>Fe(e)&&Xe(t,0)?0===t?l("/cart/remove-item",{key:e}):l("/cart/update-item",{key:e,quantity:t}):Je("invalid_input",`Not a cart line and quantity: ${e} × ${t}.`),async checkout(){const e=i(),n=await d();if(void 0!==n.error)return n;if(void 0===e||void 0===n.data||0===n.data.items.length)return Je("no_cart","The cart is empty.");const r=function(e,t){const n=new URL(e.endsWith("/")?e:`${e}/`);return n.searchParams.set("checkout-link","1"),n.searchParams.set("products",t.map(e=>`${e.id}:${e.quantity}`).join(",")),n.href}(e.store,n.data.items);try{s(r)}catch(e){return Je("cart_unavailable",Qe(e))}return t.removeItem(He),Ye(r)}}}const rt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},st=Object.entries({$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"});function it(e,t){t||(t=new Map);for(const n of e)"in"in n?n.key&&t.set(n.key,{in:n.in,map:n.map}):"key"in n?t.set(n.key,{map:n.map}):n.args&&it(n.args,t);return t}function ot(e,t){const n={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},r=it(t);function s(e,t,r){let s=n[e];void 0===s&&(s=Object.create(null),n[e]=s),s[t]=r}let i;for(const[o,a]of e.entries())if(t[o]&&(i=t[o]),i)if("in"in i)if(i.key){const e=r.get(i.key),t=e.map||i.key;e.in&&s(e.in,t,a)}else n.body=a;else for(const[e,t]of Object.entries(a??{})){const o=r.get(e);if(o)if(o.in){const n=o.map||e;s(o.in,n,t)}else n[o.map]=t;else{const n=st.find(([t])=>e.startsWith(t));if(n){const[r,i]=n;s(i,e.slice(r.length),t)}else if("allowExtra"in i&&i.allowExtra)for(const[n,r]of Object.entries(i.allowExtra))if(r){s(n,e,t);break}}}return function(e){for(const[t,n]of Object.entries(e))"body"!==t&&(!n||"object"!=typeof n||Array.isArray(n)||Object.keys(n).length||delete e[t])}(n),n}const at=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const i=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),o=s.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):ct({allowReserved:e,name:n,value:t})).join(i);return"label"===r||"matrix"===r?i+o:o},ct=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},ut=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:i})=>{if(s instanceof Date)return i?s.toISOString():`${n}=${s.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(s).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const i=t.join(",");switch(r){case"form":return`${n}=${i}`;case"label":return`.${i}`;case"matrix":return`;${n}=${i}`;default:return i}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),a=Object.entries(s).map(([t,s])=>ct({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+a:a},lt=/\{[^{}]+\}/g,dt=({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let i=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(i=(({path:e,url:t})=>{let n=t;const r=t.match(lt);if(r)for(const t of r){let r=!1,s=t.substring(1,t.length-1),i="simple";s.endsWith("*")&&(r=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),i="label"):s.startsWith(";")&&(s=s.substring(1),i="matrix");const o=e[s];if(null==o)continue;if(Array.isArray(o)){n=n.replace(t,at({explode:r,name:s,style:i,value:o}));continue}if("object"==typeof o){n=n.replace(t,ut({explode:r,name:s,style:i,value:o,valueOnly:!0}));continue}if("matrix"===i){n=n.replace(t,`;${ct({name:s,value:o})}`);continue}const a=encodeURIComponent("label"===i?`.${o}`:o);n=n.replace(t,a)}return n})({path:t,url:i}));let o=n?r(n):"";return o.startsWith("?")&&(o=o.substring(1)),o&&(i+=`?${o}`),i};function ht(e){const t=void 0!==e.body;if(t&&e.bodySerializer){if("serializedBody"in e){return void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null}return""!==e.body?e.body:null}if(t)return e.body}const yt=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},ft=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const s in n){const i=n[s];if(null==i)continue;const o=e[s]||t;if(Array.isArray(i)){const e=at({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:i,...o.array});e&&r.push(e)}else if("object"==typeof i){const e=ut({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:i,...o.object});e&&r.push(e)}else{const e=ct({allowReserved:o.allowReserved,name:s,value:i});e&&r.push(e)}}return r.join("&")},pt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`));const mt=e=>dt({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:ft(e.querySerializer),url:e.url}),gt=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=bt(e.headers,t.headers),n},vt=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},bt=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?vt(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t};class kt{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}}const wt=ft({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Rt={"Content-Type":"application/json"},Tt=(e={})=>({...rt,headers:Rt,parseAs:"auto",querySerializer:wt,...e}),St=(e={})=>{let t=gt(Tt(),e);const n=()=>({...t}),r={error:new kt,request:new kt,response:new kt},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:bt(t.headers,e.headers),serializedBody:void 0};n.security&&await async function(e){for(const t of e.security??[]){if(pt(e,t.name))continue;const n=await yt(t,e.auth);if(!n)continue;const r=t.name??"Authorization";switch(t.in){case"query":e.query||(e.query={}),e.query[r]=n;break;case"cookie":e.headers.append("Cookie",`${r}=${n}`);break;default:e.headers.set(r,n)}}}(n),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type");return{opts:n,url:mt(n)}},i=async e=>{const n=e.throwOnError??t.throwOnError,i=e.responseStyle??t.responseStyle;let o,a;try{const{opts:t,url:n}=await s(e),i={redirect:"follow",...t,body:ht(t)};o=new Request(n,i);for(const e of r.request.fns)e&&(o=await e(o,t));const c=t.fetch;a=await c(o);for(const e of r.response.fns)e&&(a=await e(a,o,t));const u={request:o,response:a};if(a.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(a.headers.get("Content-Type")):t.parseAs)??"json";if(204===a.status||"0"===a.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await a[e]();break;case"formData":n=new FormData;break;case"stream":n=a.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...u}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"text":n=await a[e]();break;case"json":{const e=await a.text();n=e?JSON.parse(e):{};break}case"stream":return"data"===t.responseStyle?a.body:{data:a.body,...u}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...u}}const l=await a.text();let d;try{d=JSON.parse(l)}catch{}throw d??l}catch(t){let s=t;for(const t of r.error.fns)t&&(s=await t(s,a,o,e));if(s=s||{},n)throw s;return"data"===i?void 0:{error:s,request:o,response:a}}},o=e=>t=>i({...t,method:e}),a=e=>async t=>{const{opts:n,url:i}=await s(t);return function({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:i,sseMaxRetryAttempts:o,sseMaxRetryDelay:a,sseSleepFn:c,url:u,...l}){let d;const h=c??(e=>new Promise(t=>setTimeout(t,e))),y=async function*(){let c=i??3e3,y=0;const f=l.signal??(new AbortController).signal;for(;!f.aborted;){y++;const i=l.headers instanceof Headers?l.headers:new Headers(l.headers);void 0!==d&&i.set("Last-Event-ID",d);try{const t={redirect:"follow",...l,body:l.serializedBody,headers:i,signal:f};let o=new Request(u,t);e&&(o=await e(u,t));const a=l.fetch??globalThis.fetch,h=await a(o);if(!h.ok)throw new Error(`SSE failed: ${h.status} ${h.statusText}`);if(!h.body)throw new Error("No body in SSE response");const y=h.body.pipeThrough(new TextDecoderStream).getReader();let p="";const m=()=>{try{y.cancel()}catch{}};f.addEventListener("abort",m);try{for(;;){const{done:e,value:t}=await y.read();if(e)break;p+=t,p=p.replace(/\r\n?/g,"\n");const i=p.split("\n\n");p=i.pop()??"";for(const e of i){const t=e.split("\n"),i=[];let o,a;for(const e of t)if(e.startsWith("data:"))i.push(e.replace(/^data:\s*/,""));else if(e.startsWith("event:"))o=e.replace(/^event:\s*/,"");else if(e.startsWith("id:"))d=e.replace(/^id:\s*/,"");else if(e.startsWith("retry:")){const t=Number.parseInt(e.replace(/^retry:\s*/,""),10);Number.isNaN(t)||(c=t)}let u=!1;if(i.length){const e=i.join("\n");try{a=JSON.parse(e),u=!0}catch{a=e}}u&&(s&&await s(a),r&&(a=await r(a))),n?.({data:a,event:o,id:d,retry:c}),i.length&&(yield a)}}}finally{f.removeEventListener("abort",m),y.releaseLock()}break}catch(e){if(t?.(e),void 0!==o&&y>=o)break;const n=Math.min(c*2**(y-1),a??3e4);await h(n)}}}();return{stream:y}}({...n,body:n.body,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const e of r.request.fns)e&&(s=await e(s,n));return s},serializedBody:ht(n),url:i})};return{buildUrl:e=>mt({...t,...e}),connect:o("CONNECT"),delete:o("DELETE"),get:o("GET"),getConfig:n,head:o("HEAD"),interceptors:r,options:o("OPTIONS"),patch:o("PATCH"),post:o("POST"),put:o("PUT"),request:i,setConfig:e=>(t=gt(t,e),n()),sse:{connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),head:a("HEAD"),options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),trace:a("TRACE")},trace:o("TRACE")}};class Et{client;constructor(e){this.client=e.client}}class It{defaultKey="default";instances=new Map;get(e){const t=this.instances.get(e??this.defaultKey);if(!t)throw new Error('No SDK client found. Create one with "new CallimacusApi()" to fix this error.');return t}set(e,t){this.instances.set(t??this.defaultKey,e)}}class Ct extends Et{getPage(e,t){const n=ot([e],[{args:[{in:"path",key:"language"},{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/page/{language}/{id}",...t,...n})}listTopics(e,t){const n=ot([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}",...t,...n})}getTopicContents(e,t){const n=ot([e],[{args:[{in:"path",key:"language"},{in:"path",key:"idOrSlug"},{in:"query",key:"offset"},{in:"query",key:"limit"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/topic/{language}/{idOrSlug}",...t,...n})}getDocumentBySlug(e,t){const n=ot([e],[{args:[{in:"path",key:"language"},{in:"path",key:"slug"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/{language}/{slug}",...t,...n})}getDocumentByGroup(e,t){const n=ot([e],[{args:[{in:"path",key:"language"},{in:"path",key:"groupId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-group/{language}/{groupId}",...t,...n})}getDocumentByPath(e,t){const n=ot([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/document/by-path",...t,...n})}listDocuments(e,t){const n=ot([e],[{args:[{in:"path",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/documents/{language}",...t,...n})}}class At extends Et{getShared(e,t){const n=ot([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}share(e,t){const n=ot([e],[{args:[{in:"path",key:"id"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/share/{id}",...t,...n})}}class Ot extends Et{getSimilar(e,t){const n=ot([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"topK"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/similar",...t,...n})}getRecommendations(e,t){const n=ot([e],[{args:[{in:"path",key:"productId"},{in:"query",key:"language"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/product/{productId}/recommendations",...t,...n})}}class xt extends Et{getLast(e,t){const n=ot([e],[{args:[{in:"query",key:"storyId"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/whisper",...t,...n})}}class $t extends Et{trackEvent(e,t){const n=ot([e],[{args:[{in:"body",key:"storyId"},{in:"body",key:"eventName"},{in:"body",key:"content"},{in:"body",key:"payload"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/track-event",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class _t extends Et{getCart(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart",...e})}addItemToCart(e,t){const n=ot([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/add",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}removeItemFromCart(e,t){const n=ot([e],[{args:[{in:"body",key:"productId"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/remove",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}updateProductQuantity(e,t){const n=ot([e],[{args:[{in:"body",key:"productId"},{in:"body",key:"quantity"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart/update",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}}class qt extends Et{getStorefrontSettings(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/shopify/storefront",...e})}}class Nt extends Et{get(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/evaluation",...e})}}class Dt extends Et{startCart(e){return(e?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/woocommerce/cart",...e})}}class jt extends Et{similar(e,t){const n=ot([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"topK"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/similar",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}related(e,t){const n=ot([e],[{args:[{in:"body",key:"anchorId"},{in:"body",key:"locale"}]}]);return(t?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/query/related",...t,...n,headers:{"Content-Type":"application/json",...t?.headers,...n.headers}})}getItemByPath(e,t){const n=ot([e],[{args:[{in:"query",key:"path"}]}]);return(t?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/skesis/item/by-path",...t,...n})}}class Ut extends Et{static __registry=new It;constructor(e){super(e),Ut.__registry.set(this,e.key)}_content;get content(){return this._content??=new Ct({client:this.client})}_stories;get stories(){return this._stories??=new At({client:this.client})}_products;get products(){return this._products??=new Ot({client:this.client})}_whisper;get whisper(){return this._whisper??=new xt({client:this.client})}_analytics;get analytics(){return this._analytics??=new $t({client:this.client})}_cart;get cart(){return this._cart??=new _t({client:this.client})}_shopify;get shopify(){return this._shopify??=new qt({client:this.client})}_evaluation;get evaluation(){return this._evaluation??=new Nt({client:this.client})}_woocommerce;get woocommerce(){return this._woocommerce??=new Dt({client:this.client})}_skesis;get skesis(){return this._skesis??=new jt({client:this.client})}}class Lt extends Error{status;body;response;request;constructor(e,t,n){const r=t?.status,s=n?`${n.method} ${n.url}`:"request";let i=`[thamyr] ${s} failed before a response arrived`;t&&(i=t.ok?`[thamyr] ${s} → ${t.status}, but the response could not be processed`:`[thamyr] ${s} → ${t.status}`),super(i,e instanceof Error?{cause:e}:void 0),this.name="ThamyrHttpError",this.status=r,this.body=e,this.response=t,this.request=n}}function Kt(e){const t=St(Tt({baseUrl:new URL("api/v3",e.endpoint).href,headers:{Authorization:`Bearer ${e.accessToken}`,"x-sl-access-token":e.accessToken},credentials:e.withCredentials?"include":"same-origin"}));return t.interceptors.error.use((e,n,r,s)=>{if(!(s.throwOnError??t.getConfig().throwOnError??!1)||!0===s.signal?.aborted)return e;return new Lt(""===e?{}:e??{},n,r)}),t}export{B as ACTION_TYPES,O as ADD_TO_CART_RESULT_BLOCK,Ut as CallimacusApi,p as CallimacusEvent,L as CallimacusService,o as ChapterStatus,r as ClientEvents,Q as DELIVER_RESULT_BLOCK,i as GalleryMode,S as LANDING_VALUE_MAX_LENGTH,w as MAX_HANDSHAKE_RETRIES,s as SLInputEventType,re as STOREFRONT_API_VERSION,n as ServerEvents,Lt as ThamyrHttpError,t as ThamyrResponseType,f as UserInteractionType,J as actionOf,q as addToCartResultOf,j as applyBlockPatch,A as blockKeyOf,K as callimacusService,Ve as cartSettingsFor,T as classifyConnectError,Kt as createContractClient,je as createPageStorage,Ue as createShopifyCart,nt as createWooCommerceCart,ne as deliverResultOf,g as extractTtsAudio,Y as fieldsOf,I as interactionRound,a as isCustomBlock,u as isMasterProduct,c as isSetProduct,Re as isVariantGid,E as landingRound,Ne as leaseLock,d as logger,Be as mergeShopifySettings,U as newRoundWarnings,k as parseConnectRejection,z as parseMapPath,y as randomUuid,We as readShopifySettings,C as receptorsOf,P as resolveMapPage,R as shouldRetryHandshake,h as transformImageUrl,De as webLocks};
|
|
9
9
|
//# sourceMappingURL=index.js.map
|