@callimacus/thamyr-core 4.19.0 → 4.21.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.
@@ -5,5 +5,5 @@
5
5
  * See LICENSE.md for the full terms.
6
6
  *
7
7
  */
8
- 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 P(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=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 P(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 P(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 Pe=e=>void 0!==e&&/^[a-z]{2}$/iv.test(e)?e.toUpperCase():void 0;const Me=(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=Pe(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 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 Pe(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=new Set;function st(e){rt.has(e)||(rt.add(e),d.warn(`${e}() is a browser-only intent API and does nothing on React Native. Use @callimacus/intent/native (initIntentNative) for intent tracking on native.`))}function it(e){st("setConsent")}function ot(e){st("setGeo")}function at(e){st("setDebug")}function ct(e){st("setDebugPanel")}function ut(e={}){st("initIntent")}function lt(){st("getIntentSessionId")}function dt(){st("ensureIntentSessionId")}function ht(){st("clearIntentSessionId")}function yt(e){st("setIntentSessionMaxAge")}const ft={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},pt=Object.entries({$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"});function mt(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&&mt(n.args,t);return t}function gt(e,t){const n={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},r=mt(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=pt.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 vt=({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):bt({allowReserved:e,name:n,value:t})).join(i);return"label"===r||"matrix"===r?i+o:o},bt=({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)}`},kt=({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])=>bt({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+a:a},wt=/\{[^{}]+\}/g,Rt=({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(wt);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,vt({explode:r,name:s,style:i,value:o}));continue}if("object"==typeof o){n=n.replace(t,kt({explode:r,name:s,style:i,value:o,valueOnly:!0}));continue}if("matrix"===i){n=n.replace(t,`;${bt({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 Tt(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 St=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},Et=({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=vt({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:i,...o.array});e&&r.push(e)}else if("object"==typeof i){const e=kt({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:i,...o.object});e&&r.push(e)}else{const e=bt({allowReserved:o.allowReserved,name:s,value:i});e&&r.push(e)}}return r.join("&")},It=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`));const Ct=e=>Rt({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Et(e.querySerializer),url:e.url}),At=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=xt(e.headers,t.headers),n},Ot=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},xt=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?Ot(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 $t{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 _t=Et({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),qt={"Content-Type":"application/json"},Nt=(e={})=>({...ft,headers:qt,parseAs:"auto",querySerializer:_t,...e}),Dt=(e={})=>{let t=At(Nt(),e);const n=()=>({...t}),r={error:new $t,request:new $t,response:new $t},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:xt(t.headers,e.headers),serializedBody:void 0};n.security&&await async function(e){for(const t of e.security??[]){if(It(e,t.name))continue;const n=await St(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:Ct(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:Tt(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:Tt(n),url:i})};return{buildUrl:e=>Ct({...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=At(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 jt{client;constructor(e){this.client=e.client}}class Ut{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 Lt extends jt{getPage(e,t){const n=gt([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=gt([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=gt([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=gt([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=gt([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=gt([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=gt([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 Kt extends jt{getShared(e,t){const n=gt([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=gt([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 zt extends jt{getSimilar(e,t){const n=gt([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=gt([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 Pt extends jt{getLast(e,t){const n=gt([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 Mt extends jt{trackEvent(e,t){const n=gt([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 Bt extends jt{getCart(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart",...e})}addItemToCart(e,t){const n=gt([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=gt([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=gt([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 Wt extends jt{getStorefrontSettings(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/shopify/storefront",...e})}}class Vt extends jt{get(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/evaluation",...e})}}class Ht extends jt{startCart(e){return(e?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/woocommerce/cart",...e})}}class Gt extends jt{similar(e,t){const n=gt([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=gt([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=gt([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 Ft extends jt{static __registry=new Ut;constructor(e){super(e),Ft.__registry.set(this,e.key)}_content;get content(){return this._content??=new Lt({client:this.client})}_stories;get stories(){return this._stories??=new Kt({client:this.client})}_products;get products(){return this._products??=new zt({client:this.client})}_whisper;get whisper(){return this._whisper??=new Pt({client:this.client})}_analytics;get analytics(){return this._analytics??=new Mt({client:this.client})}_cart;get cart(){return this._cart??=new Bt({client:this.client})}_shopify;get shopify(){return this._shopify??=new Wt({client:this.client})}_evaluation;get evaluation(){return this._evaluation??=new Vt({client:this.client})}_woocommerce;get woocommerce(){return this._woocommerce??=new Ht({client:this.client})}_skesis;get skesis(){return this._skesis??=new Gt({client:this.client})}}class Jt 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 Yt(e){const t=Dt(Nt({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 Jt(""===e?{}:e??{},n,r)}),t}export{B as ACTION_TYPES,O as ADD_TO_CART_RESULT_BLOCK,Ft 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,Jt 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,ht as clearIntentSessionId,Yt as createContractClient,je as createPageStorage,Ue as createShopifyCart,nt as createWooCommerceCart,ne as deliverResultOf,dt as ensureIntentSessionId,g as extractTtsAudio,Y as fieldsOf,lt as getIntentSessionId,ut as initIntent,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,M as resolveMapPage,it as setConsent,at as setDebug,ct as setDebugPanel,ot as setGeo,yt as setIntentSessionMaxAge,R as shouldRetryHandshake,h as transformImageUrl,De as webLocks};
8
+ 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){if(new URLSearchParams(e).has("callimacus_debug"))return!0;try{return null!==(t?.getItem("callimacus:debug")??null)}catch{return!1}}function y(){let e,t="";try{t=globalThis.location.search}catch{}try{e=localStorage}catch{}h(t,e)&&d.configure({enabled:!0,level:"warn"})}function f(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 p(){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 m,g;function v(e){if("object"!=typeof e||null===e)return!1;const t=e;return"string"==typeof t.audioUrl&&"string"==typeof t.mimeType}function b(e){if("object"==typeof e&&null!==e)for(const t of Object.values(e))if(v(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"}(m||(m={})),function(e){e.ROUND_CREATED="round-created",e.ROUND_EVENT="round-event",e.ROUND_COMPLETED="round-completed",e.ERROR="error"}(g||(g={}));const w={productSelector:"[data-product-id]",blockSelector:"[data-block-id]",maxTrackedElements:40,minVisibilityRatio:.5};class k{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??w.minVisibilityRatio;this.config={productSelector:e.productSelector??w.productSelector,blockSelector:e.blockSelector??w.blockSelector,maxTrackedElements:e.maxTrackedElements??w.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 R(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 S=3;function T(e,t){return e>=500&&t<3}function I(e,t){return t?void 0:R(e)??{code:0}}const E=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,t){return(e.warnings??[]).filter(n=>{const r=`${e.id}:${n.block}:${n.content}`;return!t.has(r)&&(t.add(r),!0)})}class M{socket;serverResponseListeners=new Set;connectionStatusListeners=new Set;errorListeners=new Set;warningListeners=new Set;reportedWarnings=new Set;uiObserver;uiObserverConfig=w;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=I(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(K(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(),!T(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 k(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={...w,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 k(this.uiObserverConfig),this.uiObserver.start()}sendUserInteraction(e,t){if(!this.socket)return void d.error("Socket is not connected. Cannot send interaction.");if(e===m.SUGGEST)return void d.error("SUGGEST is a request/response command. Use suggest() instead.");if(e===m.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:p()};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:m.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 z=new M;function P(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 B(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 W(e,t){const n=P(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 B(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 B(async()=>e.skesis.getItemByPath({path:i},{throwOnError:!0}));return a&&{kind:"item",language:r,slug:s,itemPage:a}}const V=["link","ask","interact","cart","submit"],H=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),G=e=>"string"==typeof e&&e.trim().length>0,J=new Set(["http:","https:","mailto:","tel:"]),F=e=>{try{return J.has(new URL(e,"https://relative.invalid").protocol)}catch{return!1}};function Y(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||H(r);if(i&&o&&(void 0===s||"string"==typeof s)&&G(t))return{type:"interact",id:t,...void 0!==n&&{value:n},...void 0!==r&&{payload:r},...void 0!==s&&{block:s}}}function Q(e){if(H(e))switch(e.type){case"link":return function(e){const{url:t,newTab:n}=e;return(void 0===n||"boolean"==typeof n)&&G(t)&&F(t)?{type:"link",url:t,...void 0!==n&&{newTab:n}}:void 0}(e);case"ask":return G(e.value)?{type:"ask",value:e.value}:void 0;case"interact":return Y(e);case"cart":return G(e.productId)?{type:"cart",productId:e.productId}:void 0;case"submit":return G(e.form)?{type:"submit",form:e.form}:void 0;default:return}}function X(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 Z="custom:deliverResult",ee=new Set(["done","pending","ambiguous","skipped"]),te=e=>void 0===e||"string"==typeof e,ne=e=>H(e)&&"string"==typeof e.message&&te(e.field),re=e=>H(e)&&"string"==typeof e.status&&ee.has(e.status)&&te(e.ref);function se(e){const t=e.type===Z&&H(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)&&G(r)&&te(s)&&te(i)&&(void 0===o||Array.isArray(o)&&o.every(ne))&&(H(c=a)&&Object.values(c).every(re))?{status:n,submissionId:r,results:a,...void 0!==s&&{message:s},...void 0!==i&&F(i)&&{redirect:i},...void 0!==o&&{errors:o}}:void 0}const ie="callimacus:shopify-cart-commands",oe=new Set(["cart_disabled","cart_unavailable"]);function ae(e,t){const{item:n,quantity:r}=e,s=`${r>1?`${r} × `:""}${n.name}${n.options.length>0?` (${n.options.map(e=>e.value).join(", ")})`:""}`;return void 0===t.error?{...e,outcome:"added",message:t.warnings?.[0]?.message??`${s} is in your bag.`}:"refused"===t.error.code?{...e,outcome:"refused",message:t.error.message}:oe.has(t.error.code)?{...e,outcome:"unavailable",message:"The bag is not available on this site right now."}:{...e,outcome:"failed",message:t.error.message}}function ce(e){const t=new Set;function n(n){const r=function(){try{const t=JSON.parse(e().getItem(ie)??"[]");return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return}}();if(r?.includes(n)||t.has(n))return!1;try{e().setItem(ie,JSON.stringify([...r??[],n].slice(-50)))}catch{t.add(n)}return!0}return async(e,t)=>{if(void 0===t||!n(e.chapterId))return;const r=Math.trunc(e.quantity),s=Math.min(Math.max(Number.isFinite(r)?r:1,1),10),i=await t(s);return{notice:ae({id:e.chapterId,item:e.item,quantity:s},i),...i.error&&{code:i.error.code}}}}const ue="2026-10",le=15e3,de=2e4,he="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}",ye=(e,t,n)=>`mutation ${e}(${t}, $country: CountryCode) @inContext(country: $country) {${n} {cart {...CartFields} userErrors {code field message} warnings {code message target}}}\n${he}`,fe=`query CartQuery($id: ID!, $country: CountryCode) @inContext(country: $country) {cart(id: $id) {...CartFields}}\n${he}`,pe=ye("CartCreate","$input: CartInput!","cartCreate(input: $input)"),me=ye("CartLinesAdd","$cartId: ID!, $lines: [CartLineInput!]!","cartLinesAdd(cartId: $cartId, lines: $lines)"),ge=ye("CartLinesUpdate","$cartId: ID!, $lines: [CartLineUpdateInput!]!","cartLinesUpdate(cartId: $cartId, lines: $lines)"),ve=ye("CartLinesRemove","$cartId: ID!, $lineIds: [ID!]!","cartLinesRemove(cartId: $cartId, lineIds: $lineIds)"),be="The store is busy. Try again in a moment.",we="The store is not open to the cart: its storefront password may be on.",ke=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Re=e=>"string"==typeof e&&""!==e,Se=(e,t)=>({error:{code:e,message:t},warnings:[]});const Te=(e,t=[])=>({data:e,warnings:t}),Ie=(e,t,n)=>({error:{code:e,message:t,...void 0!==n&&{status:n}},isRefusedAccess:!1}),Ee=e=>({error:{code:"cart_unavailable",message:"The store refused the cart request.",status:e},isRefusedAccess:!0}),Ce=/^gid:\/\/shopify\/ProductVariant\/\d+$/v,Ae=e=>Ce.test(e);const Oe=(e,t)=>Number.isSafeInteger(e)&&e>=t,xe=e=>({...e,lines:e.lines?.nodes??[]});const $e=e=>e.lines.map(e=>({id:e.id,merchandiseId:e.merchandise.id,quantity:e.quantity})),_e=e=>e.map(({merchandiseId:e,quantity:t})=>({merchandiseId:e,quantity:t}));function qe(e,t){const n=_e(e),r=n.find(e=>e.merchandiseId===t.merchandiseId);return r?r.quantity+=t.quantity:n.push(t),n}async function Ne(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return Ie("cart_unavailable",we,0===t?void 0:t);if(430===t||429===t)return Ie("throttled",be,t);if(401===t||403===t)return Ee(t);if(!e.ok)return Ie("http",`The store answered ${t}.`,t);let n;try{n=await e.json()}catch{return Ie("cart_unavailable",we,t)}return ke(n)&&ke(n.data)?{data:n.data}:function(e,t){const n=ke(e)&&Array.isArray(e.errors)?e.errors:[],r=new Set(n.map(e=>ke(e)&&ke(e.extensions)?e.extensions.code:void 0));if(r.has("THROTTLED"))return Ie("throttled",be,t);if(r.has("ACCESS_DENIED")||r.has("UNAUTHORIZED")||r.has("FORBIDDEN"))return Ee(t);const s=n.find(e=>ke(e)&&Re(e.message));return Ie("graphql",ke(s)&&Re(s.message)?s.message:"The store could not read the cart request.",t)}(n,t)}const De=e=>e instanceof Error?e.message:String(e);async function je(e){return new Promise(t=>{setTimeout(t,e)})}function Ue(e){return"function"==typeof AbortSignal.timeout?AbortSignal.timeout(e):void 0}function Le(){try{return localStorage}catch{return}}function Ke(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 Me(e,t={}){const{waitMs:n=de,ttlMs:r=le,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 ke(t)&&Re(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 je(i),d=u()===c,d)continue}if(Date.now()>=l)throw new Error(`[thamyr] the ${t} lock was not granted within ${n} ms`);await je(s)}try{return await o()}finally{u()===c&&e.removeItem(a)}}}function ze(){const e=globalThis.navigator?.locks;if("function"==typeof e?.request)return async(t,n)=>{const r=Ue(de);return e.request(t,r?{signal:r}:{},async()=>n())}}function Pe(){return Ke(Le())}function Be(e){const t=Ke(e.storage??Le()),n=e.lock??ze()??Me(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(!ke(t)||!Re(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=>ke(e)&&Re(e.id)&&Re(e.merchandiseId)&&"number"==typeof e.quantity)}}catch{return}}(t.getItem(s));function c(e){return t.setItem(s,JSON.stringify({id:e.id,lines:$e(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/${ue}/graphql.json`,{method:"POST",headers:s,body:JSON.stringify({query:t,variables:{...n,country:e.country??null}}),redirect:"manual",signal:Ue(1e4)});return await Ne(i)}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return Ie("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(fe,{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(!ke(s))return Se("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(xe(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}:Te(u,a)}function y(e,t){return"isGone"in e?(u(t),Se("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),Te(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",pe,{input:n});return"isGone"in r?Se("graphql","The store created no cart."):"refusedAccess"in r?{error:r.refusedAccess,warnings:[]}:r}(t)})}catch(e){return l?Se("cart_unavailable",De(e)):Se("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",me,{cartId:o.id,lines:r}),o.id);const f=await d(o.id);return"error"in f?{error:f.error,warnings:[]}:Te(f.data.cart?c(xe(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 Se("cart_unavailable",De(e))}if(!n.cartEnabled)return Se("cart_disabled","The cart is off on this site.");const{storeDomain:r}=n;if(void 0===r)return Se("cart_unavailable","No Shopify store is set up for this site.");try{return await t(i({...n,storeDomain:r}))}catch(e){return Se("cart_unavailable",De(e))}}(t));return o=n.catch(()=>{}),n}async function c(){return a(async e=>{const t=e.read();if(void 0===t)return Te(void 0);const n=await e.query(t.id);return"error"in n?n.isRefusedAccess&&e.hasToken?e.createOnce(_e(t.lines),[],t.id):{error:n.error,warnings:[]}:n.data.cart?Te(e.keep(xe(n.data.cart))):(e.drop(t.id),Te(void 0))})}const u={getCart:c,async addItem(e,t=1){const n=function(e){if("string"==typeof e)return Ae(e)?e:/^\d+$/v.test(e)?`gid://shopify/ProductVariant/${e}`:void 0}(e);if(void 0===n)return Se("invalid_input",`Not a Shopify product variant id: ${e}.`);if(!Oe(t,1))return Se("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:me,variables:{lines:[r]}},{whenGone:[r],whenRefused:qe(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=>Re(e)?a(async t=>{const n=t.read();return void 0===n?Se("no_cart","There is no cart yet."):t.change(n,{field:"cartLinesRemove",document:ve,variables:{lineIds:[e]}},{whenRefused:_e(n.lines.filter(t=>t.id!==e))})}):Se("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>Re(e)&&Oe(t,0)?a(async n=>{const r=n.read();if(void 0===r)return Se("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:ge,variables:{lines:[{id:e,quantity:t}]}},{whenRefused:_e(s)})}):Se("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 Se("no_cart","The cart is empty.");if(!function(e){try{return"https:"===new URL(e).protocol}catch{return!1}}(t.checkoutUrl))return Se("cart_unavailable","The store answered without a checkout link.");try{s(t.checkoutUrl)}catch(e){return Se("cart_unavailable",De(e))}return Te(t.checkoutUrl,e.warnings)}};return u}const We=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ve=e=>"string"==typeof e&&""!==e.trim()?e.trim():void 0;function He(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 Ge=e=>void 0!==e&&/^[a-z]{2}$/iv.test(e)?e.toUpperCase():void 0;const Je=(e,t)=>He(e?.storeDomain)??t;function Fe(e,t){const n=He(e?.domain??t?.storeDomain),r=e?.storefrontToken??Ve(t?.storefrontToken),s=e?.sourceName??void 0,i=Ge(t?.country);return{cartEnabled:e?.cartEnabled??!0,...void 0!==n&&{storeDomain:n,cartKey:Je(t,n)},...void 0!==r&&{storefrontToken:r},...void 0!==s&&{sourceName:s},countries:e?.countries??{},...void 0!==i&&{country:i}}}async function Ye(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 Fe(200===s?.status?function(e){if(!We(e)||"boolean"!=typeof e.cartEnabled)return;const t=We(e.countries)?Object.fromEntries(Object.entries(e.countries).filter(e=>"string"==typeof e[1])):{};return{domain:Ve(e.domain)??null,storefrontToken:Ve(e.storefrontToken)??null,sourceName:Ve(e.sourceName)??null,countries:t,cartEnabled:e.cartEnabled}}(r):void 0,t)}catch{return Fe(void 0,t)}}function Qe(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 Ge(i?.[1])}(n,t)??r;return{...s,...void 0!==i&&{country:i}}}const Xe="callimacus:woocommerce-cart",Ze=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),et=e=>"string"==typeof e&&""!==e,tt=(e,t,n={})=>({error:{code:e,message:t,...n}}),nt=e=>({data:e}),rt=e=>e instanceof Error?e.message:String(e),st=(e,t)=>Number.isSafeInteger(e)&&e>=t;function it(e){try{return"string"==typeof e&&"https:"===new URL(e).protocol}catch{return!1}}const ot={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ldquo:"“",rdquo:"”",lsquo:"‘",rsquo:"’",hellip:"…",ndash:"–",mdash:"—"};async function at(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return tt("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 Ze(n)&&Array.isArray(n.items)?nt(n):tt("cart_unavailable","The store answered without the cart.",{status:t});if(429===t)return tt("throttled","The store is busy. Try again in a moment.",{status:t});if(401===t||403===t)return tt("cart_unavailable","The store refused the cart request.",{status:t});const r=Ze(n)&&et(n.code)?n.code:void 0,s=Ze(n)&&et(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 ot[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?tt("refused",s,{status:t,storeCode:r}):tt("http",s,{status:t})}function ct(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 Ze(t)&&it(t.store)&&it(t.storeApi)&&et(t.token)?{store:t.store,storeApi:t.storeApi,token:t.token}:void 0}catch{return}}(t.getItem(Xe));if(void 0===e)return;const n=function(e){try{const[,t=""]=e.split(".",2),n=JSON.parse(atob(t.replaceAll("-","+").replaceAll("_","/")));return Ze(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(Xe)}function o(e){t.setItem(Xe,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 tt("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 et(u)&&i()?.token===e.token&&o({...e,token:u}),at(a)}let c=Promise.resolve();async function u(e){const t=c.then(async()=>{try{return await e()}catch(e){return tt("cart_unavailable",rt(e))}});return c=t.catch(()=>{}),t}async function l(e,t){return u(async()=>{const n=i();return void 0===n?tt("no_cart","There is no cart yet."):a(n,e,t)})}async function d(){return u(async()=>{const e=i();return void 0===e?nt(void 0):a(e,"/cart")})}return{getCart:d,async addItem(t,r=1){const s=Number(t);return st(s,1)&&String(t).trim()===String(s)?st(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(!it(r?.store)||!it(r.storeApi)||!et(r.cartToken))return tt("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?tt("cart_unavailable",rt(e)):tt("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})}):tt("invalid_input",`Not a quantity to add: ${r}.`):tt("invalid_input",`Not a WooCommerce product id: ${t}.`)},removeItem:async e=>et(e)?l("/cart/remove-item",{key:e}):tt("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>et(e)&&st(t,0)?0===t?l("/cart/remove-item",{key:e}):l("/cart/update-item",{key:e,quantity:t}):tt("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 tt("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 tt("cart_unavailable",rt(e))}return t.removeItem(Xe),nt(r)}}}const ut=new Set;function lt(e){ut.has(e)||(ut.add(e),d.warn(`${e}() is a browser-only intent API and does nothing on React Native. Use @callimacus/intent/native (initIntentNative) for intent tracking on native.`))}function dt(e){lt("setConsent")}function ht(e){lt("setGeo")}function yt(e){lt("setDebug")}function ft(e){lt("setDebugPanel")}function pt(e={}){lt("initIntent")}function mt(){lt("getIntentSessionId")}function gt(){lt("ensureIntentSessionId")}function vt(){lt("clearIntentSessionId")}function bt(e){lt("setIntentSessionMaxAge")}const wt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},kt=Object.entries({$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"});function Rt(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&&Rt(n.args,t);return t}function St(e,t){const n={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},r=Rt(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=kt.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 Tt=({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):It({allowReserved:e,name:n,value:t})).join(i);return"label"===r||"matrix"===r?i+o:o},It=({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)}`},Et=({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])=>It({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+a:a},Ct=/\{[^{}]+\}/g,At=({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(Ct);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,Tt({explode:r,name:s,style:i,value:o}));continue}if("object"==typeof o){n=n.replace(t,Et({explode:r,name:s,style:i,value:o,valueOnly:!0}));continue}if("matrix"===i){n=n.replace(t,`;${It({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 Ot(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 xt=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},$t=({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=Tt({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:i,...o.array});e&&r.push(e)}else if("object"==typeof i){const e=Et({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:i,...o.object});e&&r.push(e)}else{const e=It({allowReserved:o.allowReserved,name:s,value:i});e&&r.push(e)}}return r.join("&")},_t=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`));const qt=e=>At({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:$t(e.querySerializer),url:e.url}),Nt=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=jt(e.headers,t.headers),n},Dt=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},jt=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?Dt(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 Ut{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 Lt=$t({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Kt={"Content-Type":"application/json"},Mt=(e={})=>({...wt,headers:Kt,parseAs:"auto",querySerializer:Lt,...e}),zt=(e={})=>{let t=Nt(Mt(),e);const n=()=>({...t}),r={error:new Ut,request:new Ut,response:new Ut},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:jt(t.headers,e.headers),serializedBody:void 0};n.security&&await async function(e){for(const t of e.security??[]){if(_t(e,t.name))continue;const n=await xt(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:qt(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:Ot(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:Ot(n),url:i})};return{buildUrl:e=>qt({...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=Nt(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 Pt{client;constructor(e){this.client=e.client}}class Bt{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 Wt extends Pt{getPage(e,t){const n=St([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=St([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=St([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=St([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=St([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=St([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=St([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 Vt extends Pt{getShared(e,t){const n=St([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=St([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 Ht extends Pt{getSimilar(e,t){const n=St([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=St([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 Gt extends Pt{getLast(e,t){const n=St([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 Jt extends Pt{trackEvent(e,t){const n=St([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 Ft extends Pt{getCart(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart",...e})}addItemToCart(e,t){const n=St([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=St([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=St([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 Yt extends Pt{getStorefrontSettings(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/shopify/storefront",...e})}}class Qt extends Pt{get(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/evaluation",...e})}}class Xt extends Pt{startCart(e){return(e?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/woocommerce/cart",...e})}}class Zt extends Pt{similar(e,t){const n=St([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=St([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=St([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 en extends Pt{static __registry=new Bt;constructor(e){super(e),en.__registry.set(this,e.key)}_content;get content(){return this._content??=new Wt({client:this.client})}_stories;get stories(){return this._stories??=new Vt({client:this.client})}_products;get products(){return this._products??=new Ht({client:this.client})}_whisper;get whisper(){return this._whisper??=new Gt({client:this.client})}_analytics;get analytics(){return this._analytics??=new Jt({client:this.client})}_cart;get cart(){return this._cart??=new Ft({client:this.client})}_shopify;get shopify(){return this._shopify??=new Yt({client:this.client})}_evaluation;get evaluation(){return this._evaluation??=new Qt({client:this.client})}_woocommerce;get woocommerce(){return this._woocommerce??=new Xt({client:this.client})}_skesis;get skesis(){return this._skesis??=new Zt({client:this.client})}}class tn 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 nn(e){const t=zt(Mt({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 tn(""===e?{}:e??{},n,r)}),t}export{V as ACTION_TYPES,$ as ADD_TO_CART_RESULT_BLOCK,en as CallimacusApi,g as CallimacusEvent,M as CallimacusService,o as ChapterStatus,r as ClientEvents,Z as DELIVER_RESULT_BLOCK,i as GalleryMode,E as LANDING_VALUE_MAX_LENGTH,S as MAX_HANDSHAKE_RETRIES,s as SLInputEventType,ue as STOREFRONT_API_VERSION,n as ServerEvents,tn as ThamyrHttpError,t as ThamyrResponseType,m as UserInteractionType,Q as actionOf,D as addToCartResultOf,L as applyBlockPatch,x as blockKeyOf,z as callimacusService,ae as cartNoticeOf,Qe as cartSettingsFor,I as classifyConnectError,vt as clearIntentSessionId,ce as createCartCommandRunner,nn as createContractClient,Pe as createPageStorage,Be as createShopifyCart,ct as createWooCommerceCart,se as deliverResultOf,y as enableLoggerIfRequested,gt as ensureIntentSessionId,b as extractTtsAudio,X as fieldsOf,mt as getIntentSessionId,pt as initIntent,A as interactionRound,a as isCustomBlock,h as isDebugRequested,u as isMasterProduct,c as isSetProduct,Ae as isVariantGid,C as landingRound,Me as leaseLock,d as logger,Fe as mergeShopifySettings,K as newRoundWarnings,R as parseConnectRejection,P as parseMapPath,p as randomUuid,Ye as readShopifySettings,O as receptorsOf,W as resolveMapPage,dt as setConsent,yt as setDebug,ft as setDebugPanel,ht as setGeo,bt as setIntentSessionMaxAge,T as shouldRetryHandshake,f as transformImageUrl,ze as webLocks};
9
9
  //# sourceMappingURL=index.native.js.map