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