@callimacus/thamyr-core 4.19.0 → 4.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/index.native.js +1 -1
- package/dist/esm/index.native.js.map +1 -1
- package/dist/types/index.d.ts +59 -2
- package/dist/types/index.native.d.ts +59 -2
- package/package.json +1 -1
package/dist/esm/index.native.js
CHANGED
|
@@ -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 d={debug:0,info:1,warn:2,error:3,silent:4};const l=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&&d[e]>=d[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 l.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 w(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 k=3;function R(e,t){return e>=500&&t<3}function T(e,t){return t?void 0:w(e)??{code:0}}const S=200;function I(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 E(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",()=>{l.debug("Connected to Callimacus"),this.clearHandshakeRetry(),this.handshakeRetryAttempts=0,this.updateConnectionStatus(!0),this.socket?.emit(r.CLIENT_READY)}),this.socket.on("disconnect",()=>{l.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&&(l.error("Connection refused by Callimacus:",e.message,t.reason??""),this.notifyRejection(t,e.message),this.scheduleHandshakeRetry(t.code))}),this.socket.on(n.ERROR,e=>{l.error("Received error from Callimacus:",e),this.notifyErrorListeners(e)}),this.socket.io.on("reconnect",e=>{l.info(`Reconnected to Callimacus after ${e} attempts`)}),this.socket.io.on("reconnect_attempt",e=>{l.info(`Attempting to reconnect: attempt ${e}`)}),this.socket.io.on("reconnect_error",e=>{l.error("Reconnection error:",e)}),this.socket.io.on("reconnect_failed",()=>{l.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){l.error("Error in server response listener:",e)}})}updateConnectionStatus(e){this.connectionStatusListeners.forEach(t=>{try{t(e)}catch(e){l.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&&(l.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,l.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){l.error("Error in error listener:",e)}})}notifyWarningListeners(e){for(const t of e)0===this.warningListeners.size&&l.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){l.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 l.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&&(l.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};l.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),l.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 l.error("Socket is not connected. Cannot send interaction.");if(e===f.SUGGEST)return void l.error("SUGGEST is a request/response command. Use suggest() instead.");if(e===f.BACK_FROM_ROUND){if(void 0===t.chapterId)return void l.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 l.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 M(e){const t=/^\/?map\/(?<language>[^\/]+)(?:\/(?<slug>.*))?$/v.exec(e)?.groups,n=t?.language;if(void 0===n||""===n)return;const r=t?.slug;return void 0===r||""===r?{language:n}:{language:n,slug:r}}async function z(e){try{const{data:t}=await e();return t}catch(e){if("object"==typeof e&&null!==e&&404===e.status)return;throw e}}async function P(e,t){const n=M(t);if(!n)return;const{language:r,slug:s}=n;if(void 0===s){const{data:t}=await e.content.listDocuments({language:r},{throwOnError:!0});return{kind:"index",language:r,entries:t}}const i=`/map/${r}/${s}`,o=await z(async()=>e.content.getDocumentByPath({path:i},{throwOnError:!0}));if(o)return{kind:"document",language:r,slug:s,document:o};if(!s.includes("/"))return;const a=await z(async()=>e.skesis.getItemByPath({path:i},{throwOnError:!0}));return a&&{kind:"item",language:r,slug:s,itemPage:a}}const 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 J(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 F(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 J(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="callimacus:shopify-cart-commands",se=new Set(["cart_disabled","cart_unavailable"]);function ie(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}:se.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 oe(e){const t=new Set;function n(n){const r=function(){try{const t=JSON.parse(e().getItem(re)??"[]");return Array.isArray(t)?t.filter(e=>"string"==typeof e):[]}catch{return}}();if(r?.includes(n)||t.has(n))return!1;try{e().setItem(re,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:ie({id:e.chapterId,item:e.item,quantity:s},i),...i.error&&{code:i.error.code}}}}const ae="2026-10",ce=15e3,ue=2e4,de="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}",le=(e,t,n)=>`mutation ${e}(${t}, $country: CountryCode) @inContext(country: $country) {${n} {cart {...CartFields} userErrors {code field message} warnings {code message target}}}\n${de}`,he=`query CartQuery($id: ID!, $country: CountryCode) @inContext(country: $country) {cart(id: $id) {...CartFields}}\n${de}`,ye=le("CartCreate","$input: CartInput!","cartCreate(input: $input)"),fe=le("CartLinesAdd","$cartId: ID!, $lines: [CartLineInput!]!","cartLinesAdd(cartId: $cartId, lines: $lines)"),pe=le("CartLinesUpdate","$cartId: ID!, $lines: [CartLineUpdateInput!]!","cartLinesUpdate(cartId: $cartId, lines: $lines)"),me=le("CartLinesRemove","$cartId: ID!, $lineIds: [ID!]!","cartLinesRemove(cartId: $cartId, lineIds: $lineIds)"),ge="The store is busy. Try again in a moment.",ve="The store is not open to the cart: its storefront password may be on.",be=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),we=e=>"string"==typeof e&&""!==e,ke=(e,t)=>({error:{code:e,message:t},warnings:[]});const Re=(e,t=[])=>({data:e,warnings:t}),Te=(e,t,n)=>({error:{code:e,message:t,...void 0!==n&&{status:n}},isRefusedAccess:!1}),Se=e=>({error:{code:"cart_unavailable",message:"The store refused the cart request.",status:e},isRefusedAccess:!0}),Ie=/^gid:\/\/shopify\/ProductVariant\/\d+$/v,Ee=e=>Ie.test(e);const Ce=(e,t)=>Number.isSafeInteger(e)&&e>=t,Ae=e=>({...e,lines:e.lines?.nodes??[]});const Oe=e=>e.lines.map(e=>({id:e.id,merchandiseId:e.merchandise.id,quantity:e.quantity})),xe=e=>e.map(({merchandiseId:e,quantity:t})=>({merchandiseId:e,quantity:t}));function $e(e,t){const n=xe(e),r=n.find(e=>e.merchandiseId===t.merchandiseId);return r?r.quantity+=t.quantity:n.push(t),n}async function _e(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return Te("cart_unavailable",ve,0===t?void 0:t);if(430===t||429===t)return Te("throttled",ge,t);if(401===t||403===t)return Se(t);if(!e.ok)return Te("http",`The store answered ${t}.`,t);let n;try{n=await e.json()}catch{return Te("cart_unavailable",ve,t)}return be(n)&&be(n.data)?{data:n.data}:function(e,t){const n=be(e)&&Array.isArray(e.errors)?e.errors:[],r=new Set(n.map(e=>be(e)&&be(e.extensions)?e.extensions.code:void 0));if(r.has("THROTTLED"))return Te("throttled",ge,t);if(r.has("ACCESS_DENIED")||r.has("UNAUTHORIZED")||r.has("FORBIDDEN"))return Se(t);const s=n.find(e=>be(e)&&we(e.message));return Te("graphql",be(s)&&we(s.message)?s.message:"The store could not read the cart request.",t)}(n,t)}const qe=e=>e instanceof Error?e.message:String(e);async function Ne(e){return new Promise(t=>{setTimeout(t,e)})}function De(e){return"function"==typeof AbortSignal.timeout?AbortSignal.timeout(e):void 0}function je(){try{return localStorage}catch{return}}function Ue(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 Le(e,t={}){const{waitMs:n=ue,ttlMs:r=ce,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 be(t)&&we(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},d=Date.now()+n;let l=!1;for(;!l;){if(void 0===u()){try{e.setItem(a,JSON.stringify({owner:c,expires:Date.now()+r}))}catch{return o()}if(await Ne(i),l=u()===c,l)continue}if(Date.now()>=d)throw new Error(`[thamyr] the ${t} lock was not granted within ${n} ms`);await Ne(s)}try{return await o()}finally{u()===c&&e.removeItem(a)}}}function Ke(){const e=globalThis.navigator?.locks;if("function"==typeof e?.request)return async(t,n)=>{const r=De(ue);return e.request(t,r?{signal:r}:{},async()=>n())}}function Me(){return Ue(je())}function ze(e){const t=Ue(e.storage??je()),n=e.lock??Ke()??Le(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(!be(t)||!we(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=>be(e)&&we(e.id)&&we(e.merchandiseId)&&"number"==typeof e.quantity)}}catch{return}}(t.getItem(s));function c(e){return t.setItem(s,JSON.stringify({id:e.id,lines:Oe(e)})),e}function u(e){a()?.id===e&&t.removeItem(s)}async function d(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/${ae}/graphql.json`,{method:"POST",headers:s,body:JSON.stringify({query:t,variables:{...n,country:e.country??null}}),redirect:"manual",signal:De(1e4)});return await _e(i)}catch(e){const t=e instanceof Error&&"TimeoutError"===e.name;return Te("network",t?"The store did not answer in time.":"Could not reach the store. Check your connection and try again.")}}async function l(e){return d(he,{id:e})}async function h(e,t,n){const r=await d(t,n);if("error"in r)return o&&r.isRefusedAccess?{refusedAccess:r.error}:{error:r.error,warnings:[]};const s=r.data[e];if(!be(s))return ke("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(Ae(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}:Re(u,a)}function y(e,t){return"isGone"in e?(u(t),ke("no_cart","The cart is no longer there.")):"refusedAccess"in e?{error:e.refusedAccess,warnings:[]}:e}async function f(t,r,s){let o,d=!1;try{o=await n(i,async()=>{d=!0;const n=a();return void 0!==n&&n.id!==s?n:0===t.length?(void 0!==s&&u(s),Re(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",ye,{input:n});return"isGone"in r?ke("graphql","The store created no cart."):"refusedAccess"in r?{error:r.refusedAccess,warnings:[]}:r}(t)})}catch(e){return d?ke("cart_unavailable",qe(e)):ke("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",fe,{cartId:o.id,lines:r}),o.id);const f=await l(o.id);return"error"in f?{error:f.error,warnings:[]}:Re(f.data.cart?c(Ae(f.data.cart)):void 0)}return{hasToken:o,read:a,keep:c,drop:u,query:l,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 ke("cart_unavailable",qe(e))}if(!n.cartEnabled)return ke("cart_disabled","The cart is off on this site.");const{storeDomain:r}=n;if(void 0===r)return ke("cart_unavailable","No Shopify store is set up for this site.");try{return await t(i({...n,storeDomain:r}))}catch(e){return ke("cart_unavailable",qe(e))}}(t));return o=n.catch(()=>{}),n}async function c(){return a(async e=>{const t=e.read();if(void 0===t)return Re(void 0);const n=await e.query(t.id);return"error"in n?n.isRefusedAccess&&e.hasToken?e.createOnce(xe(t.lines),[],t.id):{error:n.error,warnings:[]}:n.data.cart?Re(e.keep(Ae(n.data.cart))):(e.drop(t.id),Re(void 0))})}const u={getCart:c,async addItem(e,t=1){const n=function(e){if("string"==typeof e)return Ee(e)?e:/^\d+$/v.test(e)?`gid://shopify/ProductVariant/${e}`:void 0}(e);if(void 0===n)return ke("invalid_input",`Not a Shopify product variant id: ${e}.`);if(!Ce(t,1))return ke("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:fe,variables:{lines:[r]}},{whenGone:[r],whenRefused:$e(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=>we(e)?a(async t=>{const n=t.read();return void 0===n?ke("no_cart","There is no cart yet."):t.change(n,{field:"cartLinesRemove",document:me,variables:{lineIds:[e]}},{whenRefused:xe(n.lines.filter(t=>t.id!==e))})}):ke("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>we(e)&&Ce(t,0)?a(async n=>{const r=n.read();if(void 0===r)return ke("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:pe,variables:{lines:[{id:e,quantity:t}]}},{whenRefused:xe(s)})}):ke("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 ke("no_cart","The cart is empty.");if(!function(e){try{return"https:"===new URL(e).protocol}catch{return!1}}(t.checkoutUrl))return ke("cart_unavailable","The store answered without a checkout link.");try{s(t.checkoutUrl)}catch(e){return ke("cart_unavailable",qe(e))}return Re(t.checkoutUrl,e.warnings)}};return u}const Pe=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Be=e=>"string"==typeof e&&""!==e.trim()?e.trim():void 0;function We(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 Ve=e=>void 0!==e&&/^[a-z]{2}$/iv.test(e)?e.toUpperCase():void 0;const He=(e,t)=>We(e?.storeDomain)??t;function Ge(e,t){const n=We(e?.domain??t?.storeDomain),r=e?.storefrontToken??Be(t?.storefrontToken),s=e?.sourceName??void 0,i=Ve(t?.country);return{cartEnabled:e?.cartEnabled??!0,...void 0!==n&&{storeDomain:n,cartKey:He(t,n)},...void 0!==r&&{storefrontToken:r},...void 0!==s&&{sourceName:s},countries:e?.countries??{},...void 0!==i&&{country:i}}}async function Je(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 Ge(200===s?.status?function(e){if(!Pe(e)||"boolean"!=typeof e.cartEnabled)return;const t=Pe(e.countries)?Object.fromEntries(Object.entries(e.countries).filter(e=>"string"==typeof e[1])):{};return{domain:Be(e.domain)??null,storefrontToken:Be(e.storefrontToken)??null,sourceName:Be(e.sourceName)??null,countries:t,cartEnabled:e.cartEnabled}}(r):void 0,t)}catch{return Ge(void 0,t)}}function Fe(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 Ve(i?.[1])}(n,t)??r;return{...s,...void 0!==i&&{country:i}}}const Ye="callimacus:woocommerce-cart",Qe=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Xe=e=>"string"==typeof e&&""!==e,Ze=(e,t,n={})=>({error:{code:e,message:t,...n}}),et=e=>({data:e}),tt=e=>e instanceof Error?e.message:String(e),nt=(e,t)=>Number.isSafeInteger(e)&&e>=t;function rt(e){try{return"string"==typeof e&&"https:"===new URL(e).protocol}catch{return!1}}const st={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ldquo:"“",rdquo:"”",lsquo:"‘",rsquo:"’",hellip:"…",ndash:"–",mdash:"—"};async function it(e){const{status:t}=e;if(0===t||"opaqueredirect"===e.type||t>=300&&t<400)return Ze("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 Qe(n)&&Array.isArray(n.items)?et(n):Ze("cart_unavailable","The store answered without the cart.",{status:t});if(429===t)return Ze("throttled","The store is busy. Try again in a moment.",{status:t});if(401===t||403===t)return Ze("cart_unavailable","The store refused the cart request.",{status:t});const r=Qe(n)&&Xe(n.code)?n.code:void 0,s=Qe(n)&&Xe(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 st[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?Ze("refused",s,{status:t,storeCode:r}):Ze("http",s,{status:t})}function ot(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 Qe(t)&&rt(t.store)&&rt(t.storeApi)&&Xe(t.token)?{store:t.store,storeApi:t.storeApi,token:t.token}:void 0}catch{return}}(t.getItem(Ye));if(void 0===e)return;const n=function(e){try{const[,t=""]=e.split(".",2),n=JSON.parse(atob(t.replaceAll("-","+").replaceAll("_","/")));return Qe(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(Ye)}function o(e){t.setItem(Ye,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 Ze("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 Xe(u)&&i()?.token===e.token&&o({...e,token:u}),it(a)}let c=Promise.resolve();async function u(e){const t=c.then(async()=>{try{return await e()}catch(e){return Ze("cart_unavailable",tt(e))}});return c=t.catch(()=>{}),t}async function d(e,t){return u(async()=>{const n=i();return void 0===n?Ze("no_cart","There is no cart yet."):a(n,e,t)})}async function l(){return u(async()=>{const e=i();return void 0===e?et(void 0):a(e,"/cart")})}return{getCart:l,async addItem(t,r=1){const s=Number(t);return nt(s,1)&&String(t).trim()===String(s)?nt(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(!rt(r?.store)||!rt(r.storeApi)||!Xe(r.cartToken))return Ze("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?Ze("cart_unavailable",tt(e)):Ze("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})}):Ze("invalid_input",`Not a quantity to add: ${r}.`):Ze("invalid_input",`Not a WooCommerce product id: ${t}.`)},removeItem:async e=>Xe(e)?d("/cart/remove-item",{key:e}):Ze("invalid_input","No cart line to remove."),updateQuantity:async(e,t)=>Xe(e)&&nt(t,0)?0===t?d("/cart/remove-item",{key:e}):d("/cart/update-item",{key:e,quantity:t}):Ze("invalid_input",`Not a cart line and quantity: ${e} × ${t}.`),async checkout(){const e=i(),n=await l();if(void 0!==n.error)return n;if(void 0===e||void 0===n.data||0===n.data.items.length)return Ze("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 Ze("cart_unavailable",tt(e))}return t.removeItem(Ye),et(r)}}}const at=new Set;function ct(e){at.has(e)||(at.add(e),l.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 ut(e){ct("setConsent")}function dt(e){ct("setGeo")}function lt(e){ct("setDebug")}function ht(e){ct("setDebugPanel")}function yt(e={}){ct("initIntent")}function ft(){ct("getIntentSessionId")}function pt(){ct("ensureIntentSessionId")}function mt(){ct("clearIntentSessionId")}function gt(e){ct("setIntentSessionMaxAge")}const vt={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},bt=Object.entries({$body_:"body",$headers_:"headers",$path_:"path",$query_:"query"});function wt(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&&wt(n.args,t);return t}function kt(e,t){const n={headers:Object.create(null),path:Object.create(null),query:Object.create(null)},r=wt(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=bt.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 Rt=({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):Tt({allowReserved:e,name:n,value:t})).join(i);return"label"===r||"matrix"===r?i+o:o},Tt=({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)}`},St=({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])=>Tt({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+a:a},It=/\{[^{}]+\}/g,Et=({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(It);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,Rt({explode:r,name:s,style:i,value:o}));continue}if("object"==typeof o){n=n.replace(t,St({explode:r,name:s,style:i,value:o,valueOnly:!0}));continue}if("matrix"===i){n=n.replace(t,`;${Tt({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 Ct(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 At=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},Ot=({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=Rt({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:i,...o.array});e&&r.push(e)}else if("object"==typeof i){const e=St({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:i,...o.object});e&&r.push(e)}else{const e=Tt({allowReserved:o.allowReserved,name:s,value:i});e&&r.push(e)}}return r.join("&")},xt=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`));const $t=e=>Et({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Ot(e.querySerializer),url:e.url}),_t=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=Nt(e.headers,t.headers),n},qt=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},Nt=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?qt(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 Dt{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 jt=Ot({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Ut={"Content-Type":"application/json"},Lt=(e={})=>({...vt,headers:Ut,parseAs:"auto",querySerializer:jt,...e}),Kt=(e={})=>{let t=_t(Lt(),e);const n=()=>({...t}),r={error:new Dt,request:new Dt,response:new Dt},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:Nt(t.headers,e.headers),serializedBody:void 0};n.security&&await async function(e){for(const t of e.security??[]){if(xt(e,t.name))continue;const n=await At(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:$t(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:Ct(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 d=await a.text();let l;try{l=JSON.parse(d)}catch{}throw l??d}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,...d}){let l;const h=c??(e=>new Promise(t=>setTimeout(t,e))),y=async function*(){let c=i??3e3,y=0;const f=d.signal??(new AbortController).signal;for(;!f.aborted;){y++;const i=d.headers instanceof Headers?d.headers:new Headers(d.headers);void 0!==l&&i.set("Last-Event-ID",l);try{const t={redirect:"follow",...d,body:d.serializedBody,headers:i,signal:f};let o=new Request(u,t);e&&(o=await e(u,t));const a=d.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:"))l=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:l,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:Ct(n),url:i})};return{buildUrl:e=>$t({...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=_t(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 Mt{client;constructor(e){this.client=e.client}}class zt{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 Pt extends Mt{getPage(e,t){const n=kt([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=kt([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=kt([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=kt([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=kt([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=kt([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=kt([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 Bt extends Mt{getShared(e,t){const n=kt([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=kt([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 Wt extends Mt{getSimilar(e,t){const n=kt([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=kt([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 Vt extends Mt{getLast(e,t){const n=kt([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 Ht extends Mt{trackEvent(e,t){const n=kt([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 Gt extends Mt{getCart(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/cart",...e})}addItemToCart(e,t){const n=kt([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=kt([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=kt([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 Jt extends Mt{getStorefrontSettings(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/shopify/storefront",...e})}}class Ft extends Mt{get(e){return(e?.client??this.client).get({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/evaluation",...e})}}class Yt extends Mt{startCart(e){return(e?.client??this.client).post({security:[{name:"x-sl-access-token",type:"apiKey"}],url:"/woocommerce/cart",...e})}}class Qt extends Mt{similar(e,t){const n=kt([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=kt([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=kt([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 Xt extends Mt{static __registry=new zt;constructor(e){super(e),Xt.__registry.set(this,e.key)}_content;get content(){return this._content??=new Pt({client:this.client})}_stories;get stories(){return this._stories??=new Bt({client:this.client})}_products;get products(){return this._products??=new Wt({client:this.client})}_whisper;get whisper(){return this._whisper??=new Vt({client:this.client})}_analytics;get analytics(){return this._analytics??=new Ht({client:this.client})}_cart;get cart(){return this._cart??=new Gt({client:this.client})}_shopify;get shopify(){return this._shopify??=new Jt({client:this.client})}_evaluation;get evaluation(){return this._evaluation??=new Ft({client:this.client})}_woocommerce;get woocommerce(){return this._woocommerce??=new Yt({client:this.client})}_skesis;get skesis(){return this._skesis??=new Qt({client:this.client})}}class Zt 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 en(e){const t=Kt(Lt({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 Zt(""===e?{}:e??{},n,r)}),t}export{B as ACTION_TYPES,O as ADD_TO_CART_RESULT_BLOCK,Xt 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,k as MAX_HANDSHAKE_RETRIES,s as SLInputEventType,ae as STOREFRONT_API_VERSION,n as ServerEvents,Zt as ThamyrHttpError,t as ThamyrResponseType,f as UserInteractionType,F as actionOf,q as addToCartResultOf,j as applyBlockPatch,A as blockKeyOf,K as callimacusService,ie as cartNoticeOf,Fe as cartSettingsFor,T as classifyConnectError,mt as clearIntentSessionId,oe as createCartCommandRunner,en as createContractClient,Me as createPageStorage,ze as createShopifyCart,ot as createWooCommerceCart,ne as deliverResultOf,pt as ensureIntentSessionId,g as extractTtsAudio,Y as fieldsOf,ft as getIntentSessionId,yt as initIntent,E as interactionRound,a as isCustomBlock,u as isMasterProduct,c as isSetProduct,Ee as isVariantGid,I as landingRound,Le as leaseLock,l as logger,Ge as mergeShopifySettings,U as newRoundWarnings,w as parseConnectRejection,M as parseMapPath,y as randomUuid,Je as readShopifySettings,C as receptorsOf,P as resolveMapPage,ut as setConsent,lt as setDebug,ht as setDebugPanel,dt as setGeo,gt as setIntentSessionMaxAge,R as shouldRetryHandshake,h as transformImageUrl,Ke as webLocks};
|
|
9
9
|
//# sourceMappingURL=index.native.js.map
|