import{Ft as e,Ht as t,It as n,Jt as s,Lt as i,Pt as o,Ut as r,Vt as a,Wt as c,Xt as d,ct as l,l as h,lt as u,zt as p}from"./630ba094.L_X-5TXi.js";import{h as g,m as x}from"./4509beb0.BguNH--m.js";import{AE as m,Gd as f,Kn as y,Lv as b,QD as w,Qa as v,Yd as I,ZD as k,as as E,bO as C,cO as S,e_ as A,eh as T,gO as P,hw as R,jr as M,kE as N,lO as L,m_ as _,mx as D,n_ as O,os as j,pO as U,qn as $,t_ as B,vO as q,vS as F,xO as V}from"./6ec9a0fa.rdcQt2v8.js";import{a as z,o as H}from"./f1384cc2.BX1JbjgR.js";import{i as K}from"./c328865d.BCB1O5to.js";import{r as W}from"./071c0ba4.B9zTdxJO.js";import{C as G,E as Q,I as J,O as X,P as Y,R as Z,T as ee,a as te,b as ne,c as se,g as ie,i as oe,l as re,m as ae,o as ce,p as de,r as le,s as he,u as ue,v as pe,w as ge,x as xe,y as me,z as fe}from"./8d9b1fe6.DS8AsfPU.js";import{n as ye,t as be}from"./4431ba3a.D8c41620.js";import{C as we,D as ve,O as Ie,S as ke,T as Ee,V as Ce,_ as Se,b as Ae,d as Te,f as Pe,g as Re,h as Me,i as Ne,k as Le,r as _e,v as De,w as Oe,x as je,y as Ue,z as $e}from"./53feb4a7.Cc6JRiPi.js";import{t as Be}from"./8d7e1337.D1SAQfdV.js";import{a as qe,n as Fe}from"./ee4d5c67.YGTDljOG.js";import{a as Ve,i as ze,n as He,o as Ke,r as We,s as Ge,t as Qe}from"./3c7ea602.cDmY7fUC.js";import{n as Je,r as Xe,t as Ye}from"./565bff04.DsKYpUCB.js";import{n as Ze}from"./c1adaf81.Cx57sSL5.js";import{t as et}from"./33cd60c3.LstUQUHF.js";function tt(){const t=e(!1),{shell:n}=V().checkout.configuration.branding;c(()=>{const{announcement:e}=n.configuration;"dismissed"!==e.visibility&&(t.value?"hidden"===e.visibility&&n.set("announcement",{...e,visibility:"visible"}):"visible"===e.visibility&&n.set("announcement",{...e,visibility:"hidden"}))},[t.value,n]),c(()=>()=>{const{announcement:e}=n.configuration;"visible"===e.visibility&&n.set("announcement",{...e,visibility:"hidden"})},[n]);const s=d(e=>{t.value=e},[t]);return{announcementHasChildren:t.value,setAnnouncementHasChildren:s}}function nt(e){if("function"==typeof e||e instanceof AbortSignal)return;if("object"!=typeof e||null==e)return e;const t={};for(const n in e)t[n]=nt(e[n]);return t}var st=class extends Error{constructor(...e){super(...e),this.name="ExtensionUsageError"}},it=/^\/api\/.+\/graphql\.json$/,ot=/^(\/\/)?(\/)?storefront\/api\/(.+\/)?graphql\.json$/;function rt({appId:e,extensionType:t,storefrontTokens:n,storefrontUrl:s,myshopifyDomain:i,allowApiAccess:o,apiVersion:r}){return async function(a){const c=y(a.url,{storefront:$(s,r)});if(!function(e,t,n){const s=new URL(e);if("shopify:"===s.protocol)return ot.test(s.pathname);const i=new URL(t),o=new URL(`https://${n}`);return(s.host===i.host||s.host===o.host)&&it.test(s.pathname)}(c,s,i))return async function(){throw new st("invalid request URL for storefront API. View the docs for more information:\n\nhttps://shopify.dev/docs/api/storefront#endpoints")}();let d;try{d=new Request(function(e,t){const n=new URL(e),s=new URL(`https://${new URL(t).host}`);return s.pathname=n.pathname,s.search=n.search,s.href}(c,s),a)}catch(l){throw new P(`Invalid API request: ${l}`)}if(o){const s=await n.get(e,t,"apiFetch");let i;s&&d.headers.set("Shopify-Storefront-Extension-Token",s);try{i=await fetch(d)}catch(l){if(l instanceof TypeError&&l.message.includes("Failed to fetch"))throw new C("Failed to query Storefront API",{cause:l});throw l}const o=await i.text();return{...nt(i),headers:i.headers?Array.from(i.headers.entries()):[],body:o}}return async function(){throw new st('permission to access the storefront API must be specified under [capabilities] with flag "api_access = true"; this can be done within your extension\'s configuration. View the docs for more information:\n\nhttps://shopify.dev/docs/api/checkout-ui-extensions/configuration#api-access')}()}}new Proxy({},{get:(e,t)=>Promise.reject(new Error(`Called ${String(t)} on dummyWorker. Methods are not executable in dummyWorker.`))});var at=Ve("/cdn/shopifycloud/checkout-web/assets/c1/sandbox.BG0usfBQ.worker.js"),ct=Ve("/cdn/shopifycloud/checkout-web/assets/c1/sandbox-runtime-upgrade.B8Z4THoD.worker.js"),dt=Ve("/cdn/shopifycloud/checkout-web/assets/c1/sandbox-2025-07.BnqKNptV.worker.js"),lt=Ve("/cdn/shopifycloud/checkout-web/assets/c1/sandbox-2023-04.2Bmj7QQo.worker.js");function ht(e){const t=new Set;return e.aborted?{aborted:!0}:(e.addEventListener("abort",()=>{for(const s of t){try{s(e.aborted)}catch(n){if(!fe(n))throw n}z(s)}t.clear()},{once:!0}),{aborted:!1,start(n){e.aborted?n(!0):(H(n),t.add(n))}})}function ut(e,t){const n=!e.assets.isBaselineBrowser,s="treatment"===e.unstable_getSerialization("experiments")?.find(({clientHandle:e})=>e===F)?.variant,i=n?"/cdn/shopifycloud/checkout-web/assets/c1/polyfills-entry-modern.qLDcQEZF.worker.js":"/cdn/shopifycloud/checkout-web/assets/c1/polyfills-entry-legacy.Ba_5OrSr.worker.js",o=Qe({extensionsPublicPath:e.assets.extensionsBase,isPostPurchase:!1,isolateNetworkAccess:s,observability:t.observability,getPolyfills:()=>async function(e){const t=ze(e);let n=0;Ye.markStarted(Xe,{type:"sandbox-fetch"});try{const{response:s,text:i}=await l(async()=>{n++;const s=await fetch(e,{...t?{integrity:t}:{},...n>1?{cache:"reload"}:{}});if(!s.ok)throw new U(`Failed to fetch sandbox polyfills: ${s.status}`);return{response:s,text:await s.text()}},{maxAttempts:2,initialRetryDelay:.5});return Ye.markFinished(Xe,{type:"sandbox-fetch",transferredBundleSize:Number(s.headers.get("content-length")),bundleSize:i.length}),i}catch(s){if(s instanceof U)throw s;throw new U(s instanceof Error&&s.message.length>0?s.message:"Failed to fetch sandbox polyfills",{cause:s})}}(We(i,e.assets.extensionsBase)),appSandboxPermissions:t.appSandboxPermissions}),r=new Map,a=new Map,c=new Set,d=[],h=[];let u=!1;const p=f(function(){u=!0;const e=h.splice(0);for(const t of e)requestIdleCallback(()=>x(t))},500);function g(e){const{worker:t}=e;e.worker=null,e.renderCallbacksInProgress.clear(),Ge(t),e.extensionPreloads.clear(),e.loadedExtensions.clear()}return{get:e=>r.get(e),on(e,t){c.add(t);for(const n of d.splice(0))t(n);return()=>{c.delete(t)}},getOrCreate({extension:e,storefrontUrl:n,myshopifyDomain:s}){const i=x({extension:e,storefrontUrl:n,myshopifyDomain:s,appSandboxPermissions:t.appSandboxPermissions});return a.get(i).userCount+=1,i},release(e){const t=a.get(e);return null==t?Promise.reject(new q("Could not release the provided sandbox, which usually means the sandbox has already been destroyed.")):(t.userCount-=1,t.userCount>0||(t.listeners.clear(),g(t),a.delete(e),r.delete(t.id)),Promise.resolve())},preload({extensions:e,storefrontUrl:n,myshopifyDomain:s}){const i=e=>t.deferThankYouPreloads&&!_(e.extensionPoint.target)&&!u;for(const o of e)i(o)?h.push({extension:o,storefrontUrl:n,myshopifyDomain:s,appSandboxPermissions:t.appSandboxPermissions}):x({extension:o,storefrontUrl:n,myshopifyDomain:s,appSandboxPermissions:t.appSandboxPermissions});e.length>0&&e.every(i)&&p()}};function x({extension:e,storefrontUrl:n,myshopifyDomain:i,appSandboxPermissions:l}){const{capabilities:h,scriptUrl:u,id:x,extensionPoint:m,apiVersion:f}=e,y=He({extension:e,appSandboxPermissions:l,observability:t.observability,isolateNetworkAccess:s}),b=function({target:e,publicId:t,apiVersion:n,sandboxConfig:s}){return s.isShared?s.cacheKey():`${t}:${e}:${n}`}({target:m.target,publicId:x,apiVersion:f,sandboxConfig:y});if(r.has(b)){const n=r.get(b);return y.isShared&&(n.loadExtension(e),t.observability.log("extension_loaded_in_shared_sandbox","Extension loaded into shared sandbox",{appId:e.appId,extensionId:e.id,sandboxCacheKey:b})),n}const w=new Map,v={id:b,userCount:0,scriptUrl:u,extensionPreloads:new Map,loadedExtensions:new Map,listeners:w,worker:null,scriptDownloadsInProgress:new Map,renderCallbacksInProgress:new Map,workerReady:void 0},I={allowNetworkAccess:y.isShared?y.hasSharedNetworkAccess:A(e)};async function k(e){const t=v.loadedExtensions.get(e.id);if(t&&t.scriptUrl===e.scriptUrl)return;Ye.markStarted("js-loading",{extension:e,instanceId:null,type:"extension"}),v.loadedExtensions.set(e.id,e);const n=async function(e){const{scriptUrl:t}=e;try{Ye.markStarted("partner-js-fetch",{extension:e,instanceId:null,type:"extension"});const n=await fetch(t);if(!n.ok)throw new S(`Failed to fetch extension asset, received http status ${n.status}`);const s=await n.text();return Ye.markFinished("partner-js-fetch",{extension:e,instanceId:null,type:"extension",transferredBundleSize:Number(n.headers.get("content-length")),bundleSize:s.length}),{scriptBody:s,scriptUrl:t,extensionId:e.id}}catch(n){const e=n instanceof Error&&"string"==typeof n.message&&n.message.length>0?n.message:"Failed to fetch extension asset";throw new S(e,{cause:n})}}(e);v.scriptDownloadsInProgress.set(e.id,n);const s=()=>{v.scriptDownloadsInProgress.get(e.id)===n&&v.scriptDownloadsInProgress.delete(e.id)};n.then(s).catch(s);const i=(async()=>{let t;await v.workerReady;try{t=await n}catch(s){throw v.loadedExtensions.delete(e.id),v.extensionPreloads.delete(e.id),Ye.markFinished("js-loading",{extension:e,instanceId:null,type:"extension"}),s}null!=v.worker?(await v.worker.load(t),Ye.markFinished("js-loading",{extension:e,instanceId:null,type:"extension"})):Ye.markFinished("js-loading",{extension:e,instanceId:null,type:"extension"})})();v.extensionPreloads.set(e.id,i)}async function E(){let s=null;function r(e){const n=w.get("error");n?.size?n.forEach(t=>t(e)):e instanceof L&&v.worker===s&&t.observability.error(e,{severity:"error",metadata:{sandbox:T()}})}s="2023-04"===f?lt({createMessenger:o(r,I,e)}):W(f)?(t.useUpgradedRemoteDomRuntime?ct:at)({createMessenger:o(r,I,e)}):dt({createMessenger:o(r,I,e)}),v.worker=s,Ke(s,{reload:()=>{},extensionPerformanceMarkStarted:(e,t)=>{e in Je&&Ye.markStarted(e,{type:"extension",extension:C(t.extensionId),...t})},extensionPerformanceMarkFinished:(e,t)=>{e in Je&&Ye.markFinished(e,{type:"extension",extension:C(t.extensionId),...t})},reportSandboxError:(e,n)=>{const s=new je(`${e?.name??"Error"}: ${e?.message??"Unknown sandbox error"}`);e?.stack&&(s.stack=e.stack),t.observability.error(s,{severity:"error",metadata:{sandbox:T(n?.scriptUrl)}})},reportApiRead:(t,n)=>{if(!Array.isArray(t))return;const s="string"==typeof n?.extensionId?n.extensionId:void 0,i=null==s?e:C(s);if("local"===i.type)return;const o=[];for(const e of t)"string"==typeof e&&""!==e&&o.push(e);o.length>0&&function(e){if(c.size>0)for(const t of c)t(e);else d.push(e),d.length>200&&d.shift()}({apiPropertyNames:o,extension:i,initialLoad:Ye.initialLoad,timestamp:new Date})},reportPolicyViolation:(n,s)=>{if("local"===e.type)return;const i=String(n?.effectiveDirective);t.observability.log("extension_sandbox_policy_violation",`Extension sandbox blocked a ${i} request`,{effectiveDirective:i,blockedOrigin:String(n?.blockedOrigin),apiVersion:e.apiVersion,sandbox:T(s?.scriptUrl)})}}),W(f)||await s.sandbox({allowNetworkAccess:I.allowNetworkAccess,allowApiAccess:h.apiAccess,storefrontUrl:n,myshopifyDomain:i})}function C(t){return v.loadedExtensions.get(t)??e}function T(t){const{appId:n,appName:s}=e,i=null==t?!y.isShared&&e||void 0:[...v.loadedExtensions.values()].find(e=>e.scriptUrl===t);return{appId:n,appName:s,extensionId:i?.extensionId,extensionName:i?.name}}function P(){const e=v.worker;if(null==e)throw new q("You attempted to call a function on a terminated web worker after its extension sandbox was released.");return e}v.workerReady=E(),k(e);const R={async render(e,t,s,o,r,a,c,d,l){const h=C(c);Ke(P(),{apiFetch:rt({appId:y.isShared?y.appId:h.appId,storefrontTokens:r,storefrontUrl:n,myshopifyDomain:i,extensionType:y.isShared?y.extensionType:h.type,allowApiAccess:y.isShared?y.hasSharedApiAccess:h.capabilities.apiAccess,apiVersion:f})}),await v.extensionPreloads.get(h.id),p(),Ye.markStarted("execution",{extension:h,instanceId:a,type:"extension"});const u=Symbol(a);v.renderCallbacksInProgress.set(a,u);try{return W(f)?await P().render({connection:t,target:h.extensionPoint.target,translations:h.translations,extensionType:h.type,scriptUrl:h.scriptUrl,api:o,instanceId:a,extensionId:h.id,allowNetworkAccess:A(h),allowApiAccess:h.capabilities.apiAccess,storefrontUrl:n,myshopifyDomain:i,initialValues:d,relayApi:l}).then(({output:e,teardown:t})=>({output:e,teardown:t})):await P().render(e,t,s,o,h.translations,h.type,a).then(({output:e,teardown:t})=>({output:e,teardown:t}))}finally{v.renderCallbacksInProgress.get(a)===u&&v.renderCallbacksInProgress.delete(a)}},async run(e,t,s,o,r){const a=C(o);return function(e){"signal"in e&&Object.assign(e,{signal:ht(e.signal)})}(t),await v.extensionPreloads.get(a.id),p(),W(f)?P().run({target:a.extensionPoint.target,translations:a.translations,extensionType:a.type,scriptUrl:a.scriptUrl,api:t,instanceId:s,extensionId:a.id,allowNetworkAccess:A(a),allowApiAccess:a.capabilities.apiAccess,storefrontUrl:n,myshopifyDomain:i,initialValues:r}).then(({output:e,teardown:t})=>({output:e,teardown:t})):P().run(e,t,a.translations,a.type,s).then(({output:e,teardown:t})=>({output:e,teardown:t}))},async restart(){const e=[...v.loadedExtensions.values()];g(v),v.workerReady=E();for(const t of e)k(t);w.get("restart")?.forEach(e=>e())},on:(e,t)=>(w.has(e)?w.get(e)?.add(t):w.set(e,new Set([t])),()=>{w.get(e)?.delete(t)}),getUserCount:()=>v.userCount,isWorkerAvailable:()=>null!==v.worker,isWaitingOnExtension:(e,t)=>v.scriptDownloadsInProgress.has(t)||v.renderCallbacksInProgress.has(e),loadExtension(e){k(e)}};return r.set(b,R),a.set(R,v),R}}var pt={id:"19a6a28598862a756fd845752b04b4eed5d189eed0b08c3a5033847732004301",type:"query",name:"ExtensionTokens",source:""};function gt(){const e=T(),{i18n:t}=V();return o(()=>e.value?{id:"cart",label:t.translate("general.cart"),route:"",features:[]}:void 0)}function xt(e,t){const n=h(e?.translations[e.defaultLocale]??{}),s=ft(t),i=h(e?.translations[s]??{}),o=h(e?.translations[t]??{});return function(e){const t={};for(const[n,s]of e)t[n]=s;return t}(new Map([...n,...i,...o]))}function mt(e,t){if(!e)return t;const n=new Set(Object.keys(e.translations));if(0===n.size)return t;if(n.has(t))return t;const s=ft(t);return n.has(s)?s:e.defaultLocale}function ft(e){const t=e.indexOf("-");return-1===t?e:e.slice(0,t)}function yt(e,t){let n=!0;const s=new WebSocket(e),i=({data:s})=>{try{const{type:e}=JSON.parse(s);if("ok"===e||"warnings"===e){if(n)return void(n=!1);t()}}catch(i){console.log(`error parsing update message from ${e} : ${i}`)}};return s.addEventListener("message",i),()=>{s.removeEventListener("message",i),s.close()}}function bt(e){let t,n;return"local"!==e.type&&(t="targetPublicIdentifier"in e?e.targetPublicIdentifier:void 0,n=e.publicIdentifier),{extensionId:j(e),extensionPoint:{target:e.extensionPoint.target,metafields:e.extensionPoint.metafields},placementReference:e.placementReference,type:e.type,appId:e.appId,appApiKey:e.appApiKey??null,apiVersion:e.apiVersion,version:e.version,registrationId:e&&"registrationId"in e?e.registrationId:"",targetPublicIdentifier:t,publicIdentifier:n}}function wt(e){const t=b(),{checkout:{journey:i}}=V(),o=s(i.currentPage.peek()),r=s(i.currentDetour.peek());n(()=>{o.current=i.currentPage.value}),n(()=>{r.current=i.currentDetour.value}),c(()=>{if(e)return e.on("apiRead",e=>{const n=r.current?.type??o.current?.id??"";for(const s of e.apiPropertyNames)t("extensionLifecycle",{apiPropertyName:s,extension:bt(e.extension),initialPageLoad:e.initialLoad,page:n,phase:"apiRead",section:"extension",timestamp:e.timestamp})})},[t,e])}function vt(){const{shop:e,checkout:{negotiator:t}}=V(),n=t.current.fields.buyerIdentity;return o(()=>({isoCode:n.value?.presentmentCurrency??e.currencyCode}))}function It({renderManager:e}){const{client:t,observability:i,checkout:{journey:o}}=V(),r=b(),a=t.unstable_legacyNavigationPerformance,d=s(o.currentPage.peek()),l=s(o.currentDetour.peek()),h=s(e);n(()=>{d.current=o.currentPage.value}),n(()=>{l.current=o.currentDetour.value}),c(()=>{h.current=e},[e]),c(()=>{if(!a)return;const e=a.on("navigation",()=>{Ye.setEndOfInitialLoad()});return()=>{e()}},[a]),c(()=>Ye.subscribe(e=>{e.forEach(e=>{const t=l.current?.type??d.current?.id??"";switch(e.type){case"iframe-loader-metric":case"sandbox-fetch-metric":{const{mark:n,duration:s,timestamp:i,initialLoad:o}=e;r("extensionLifecycle",{duration:s,extension:null,phase:n,section:"extension",page:t,timestamp:i,initialPageLoad:Boolean(o),transferredBundleSize:"sandbox-fetch-metric"===e.type?e.transferredBundleSize:void 0,bundleSize:"sandbox-fetch-metric"===e.type?e.bundleSize:void 0});break}case"query-cache-opportunity-metric":try{i.histogram({name:"extension_cache_opportunity_duration",value:e.duration,unit:"ms",attributes:{api:"storefront",source:"query",outcome:e.outcome}})}catch{}break;case"extension-fetch-call-metric":{const{duration:t,timestamp:n,httpStatus:s,httpMethod:i,errorType:o,destination:a,extension:c,origin:d,requestUrl:l}=e;r("extensionFetchCall",{duration:t,destination:a,httpStatus:s,httpMethod:i,errorType:o,timestamp:n,extension:{extensionId:c.extensionId,extensionPoint:{target:c.extensionPoint.target,metafields:c.extensionPoint.metafields},placementReference:c.placementReference,type:c.type,appId:c.appId,appApiKey:c.appApiKey??null,apiVersion:c.apiVersion,version:c.version,registrationId:"registrationId"in c?c.registrationId:void 0,publicIdentifier:"publicIdentifier"in c?c.publicIdentifier:void 0,targetPublicIdentifier:"targetPublicIdentifier"in c?c.targetPublicIdentifier:void 0},section:"extension",origin:d,requestUrl:l});break}case"extension-metric":{const{mark:n,extension:s,duration:i,timestamp:o,instanceId:a,transferredBundleSize:c,bundleSize:d,initialLoad:l,ttsCompletionReason:h,ttsRenderObserved:u,ttsRequestCount:p}=e;r("extensionLifecycle",{duration:i,instanceId:a,extensionVersionId:s.extensionId,extension:bt(s),phase:n,section:"extension",page:t,timestamp:o,initialPageLoad:Boolean(l),transferredBundleSize:c,bundleSize:d,ttsCompletionReason:h,ttsRenderObserved:u,ttsRequestCount:p});break}}})}),[r,i])}function kt(){const{checkout:{negotiator:e}}=V(),{extensionSkeletonBatchStateSignal:t,extensionSkeletonBatchReleaseIdSignal:i,extensionSkeletonPendingCountSignal:o}=e.context,r=s(null);return n(()=>{const e=t.value,n=o.value;return p(()=>{if("collecting"!==e)return void(r.current=null);const s=r.current??Date.now();r.current=s;const o=()=>{r.current=null,a(()=>{i.value+=1,t.value="idle"})};if(0===n)return void o();const c=setTimeout(o,Math.max(0,250-(Date.now()-s)));return()=>clearTimeout(c)})}),null}var Et=class{#e;constructor(e){this.domain=e.domain,this.action=e.action,this.#e=[e.domain,e.action,D()].join(":"),Object.freeze(this)}get eventId(){return this.#e}},Ct=class{constructor({proposal:e,observability:t,negotiationRateLimiter:n}){this.queue=[],this.isProcessingQueue=!1,this.debounceTimer=null,this.debouncedNegotiations=[],this.negotiate=async({options:e,extension:t,validateCanNegotiate:n})=>(this.throwIfThrottled(t),e.customizeNegotiation?this.enqueue({options:e,extension:t,validateCanNegotiate:n}):this.debounceNegotiation({options:e,extension:t,validateCanNegotiate:n})),this.throwIfThrottled=e=>{if(this.negotiationRateLimiter.isThrottled(e.id))throw new $e(this.negotiationRateLimiter.reason)},this.recordAndCheckThrottle=(e,t)=>{const{isThrottled:n,isFirstThrottled:s}=this.negotiationRateLimiter.record(e.id,t);if(s){if("local"!==e.type){const t=pe(e),n=!0;this.observability.log("extension_sliding_window_throttle_exceeded","[Extensions::Negotiator] Extension exceeded the sliding window throttle (enforced=true)",{reason:this.negotiationRateLimiter.reason,requestCount:this.negotiationRateLimiter.maxRequests,windowMs:this.negotiationRateLimiter.windowMs,enforced:!0,isHighValueExtension:t.isHighValueExtension,extension:t,eventIds:this.negotiationRateLimiter.eventIds(e.id)},{exportImmediately:n}),this.observability.counter({name:"extension_sliding_window_throttle_exceeded",value:1,attributes:{enforced:!0,isHighValueExtension:t.isHighValueExtension},exportImmediately:n})}const t=e.appName?`${e.appName} (${e.name})`:e.name;console.warn(`Checkout UI extension ${t} has exceeded the maximum number of allowed API requests and has been blocked for this session.`)}return n?new $e(this.negotiationRateLimiter.reason):null},this.enqueue=async({options:e,extension:t,validateCanNegotiate:n})=>{if(this.queue.length>=100)throw new Re("There are too many negotiations waiting to be processed. Please wait and try again.");return new Promise((s,i)=>{this.queue.push({options:e,extension:t,resolve:s,reject:i,retryCount:0,validateCanNegotiate:n}),this.processQueue()})},this.processQueue=async()=>{if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.queue.length>0;){const t=this.queue.shift();try{this.observability.debug("extensions_negotiator_negotiation_processed","[Extensions::Negotiator] Performing queued negotiation",{...pe(t.extension),queueLength:this.queue.length});const e=await this.executeSingleNegotiation({options:t.options,extension:t.extension,validateCanNegotiate:t.validateCanNegotiate});t.resolve(e)}catch(e){if(e instanceof ke&&t.retryCount<3){const e=200*2**t.retryCount;this.observability.debug("extensions_negotiator_negotiation_processed","[Extensions::Negotiator] Retrying stale negotiation",{...pe(t.extension),retryCount:t.retryCount,delayMs:e}),await u(e),t.retryCount++,this.queue.unshift(t)}else t.reject(e)}}this.isProcessingQueue=!1}},this.debounceNegotiation=({options:e,extension:t,validateCanNegotiate:n})=>{if(null!==this.debounceTimer){const s=this.debouncedNegotiations.length+1;return this.observability.debug("extension_negotiation_debounced",`[Extensions::Negotiator] Debounce: collapsing call ${s} into open window`,{callNumber:s,newOptions:e}),this.observability.log("extension_negotiation_debounced","[Extensions::Negotiator] Extension negotiation debounced — collapsing into pending window",{callNumber:s}),new Promise((s,i)=>{this.debouncedNegotiations.push({resolve:s,reject:i,extension:t,options:e,validateCanNegotiate:n})})}return this.observability.debug("extension_negotiation_debounced","[Extensions::Negotiator] Debounce: opening window",{options:e,delayMs:100}),new Promise((s,i)=>{this.debouncedNegotiations.push({resolve:s,reject:i,extension:t,options:e,validateCanNegotiate:n}),this.debounceTimer=setTimeout(async()=>{const e=[...this.debouncedNegotiations];this.debouncedNegotiations=[],this.debounceTimer=null,await this.executeDebouncedNegotiations(e)},100)})},this.executeDebouncedNegotiations=async e=>{this.observability.debug("extension_negotiation_debounced",`[Extensions::Negotiator] Debounce: firing for ${e.length} collapsed call(s)`),this.observability.histogram({name:"extension_negotiation_debounce_window_size",value:e.length});const t=this.rejectInvalidNegotiations(e),n=this.rejectThrottledExtensions(t);await Promise.all(n.map(async e=>{try{const t=await this.executeNegotiation({options:e.options});e.resolve(t)}catch(t){e.reject(t)}}))},this.rejectInvalidNegotiations=e=>{const t=[];for(const s of e)try{s.validateCanNegotiate(),t.push(s)}catch(n){s.reject(n)}return t},this.rejectThrottledExtensions=e=>{const t=new Map,n=[];for(const s of e){t.has(s.extension.id)||t.set(s.extension.id,this.recordAndCheckThrottle(s.extension,s.options.reason?.eventId));const e=t.get(s.extension.id);e?s.reject(e):n.push(s)}return n},this.executeSingleNegotiation=({options:e,extension:t,validateCanNegotiate:n})=>{n();const s=this.recordAndCheckThrottle(t,e.reason?.eventId);if(null!==s)throw s;return this.executeNegotiation({options:e})},this.executeNegotiation=async({options:e})=>{const{runListenersOnError:t=!0,...n}=e,s=await this.proposal.negotiate({...n,negotiationStage:"negotiation",runListenersOnError:t,quiet:e=>"invalid"===e.status||"error"===e.status&&!t});switch(s.status){case"success":case"error":return s;case"invalid":if(s.reasons.includes(R.SubmittedForCompletion))throw new Se("The buyer has already submitted the checkout.",{cause:{code:R.SubmittedForCompletion}});throw new Me(`Negotiation was invalid. Reasons: ${s.reasons.join(", ")}`,{cause:{code:"INVALID_NEGOTIATION"}});case"stale":throw new ke("Negotiation was stale.",{cause:{code:"STALE_NEGOTIATION"}});case"denied":throw new Me("A checkpoint was denied during negotiation.",{cause:{code:"DENIED_NEGOTIATION"}});case"throttled":throw new Me("The negotiation was throttled.",{cause:{code:"THROTTLED_NEGOTIATION"}});case"tooManyRequests":throw new Se("The negotiation was halted due to too many requests.",{cause:{code:"TOO_MANY_REQUESTS_IN_NEGOTIATION"}});case"alreadyCompleted":throw new Se("Negotiation was already completed.",{cause:{code:"ALREADY_COMPLETED_NEGOTIATION"}});case"fetch_failed":throw new Se("The negotiation fetch failed.",{cause:{code:"NEGOTIATION_FETCH_FAILED"}});default:return(()=>{throw new Oe("Unknown negotiation result.",{cause:{code:"UNKNOWN_NEGOTIATION_RESULT"}})})()}},this.proposal=e,this.observability=t,this.negotiationRateLimiter=n}};function St({captureEvent:e,journeyCompletedSignal:t,wallets:n,proposal:s,observability:i,extensionPerformance:o,negotiationRateLimiter:r}){const{negotiate:a}=new Ct({proposal:s,observability:i,negotiationRateLimiter:r});function c(t,{error:n,changeTypeName:s,startTimestamp:i,extension:o,extensionInstanceId:a,initialLoad:c,eventId:d}){e("extensionInteraction",{interaction:`${s}${t}`,error:n,duration:"Start"===t||void 0===i?void 0:performance.now()-i,extension:o,section:"extension",extensionInstanceId:a??"",timestamp:new Date,initialLoad:c,eventId:d,throttleCounter:r.count(o.id)})}function d({changeTypeName:e,message:t,extension:n,eventId:s,changeIsNoOp:o}){i.leaveErrorBreadcrumb(`Extensions::API::${e}`,{message:t,eventId:s,throttleCounter:r.count(n.id),extension:{appId:n.appId,id:n.id,registrationId:"local"===n.type?void 0:n.registrationId},...void 0!==o&&{changeIsNoOp:o}})}function l({changeTypeName:e,change:t,result:n,error:s,extension:o,extensionInstanceId:r,initialLoad:a,changeIsNoOp:c}){const d=s?"failed":"successful",l={...pe(o),change:t,result:n,...s&&{error:s},...void 0!==c&&{changeIsNoOp:c},extensionInstanceId:r,initialLoad:a};i.debug("extenstions_change_applied",`[Extensions::ApplyChange::${e}] ${d}`,l)}return async function({unknownChange:e,extension:s,allowChangeAfterJourneyCompletion:h=!1,allowChangeDuringAcceleratedWallet:u=!1,handlers:p,errorResult:m,extensionInstanceId:f}){const y=At(e)?e.type:"unknownChange",b=E(s),w=o.initialLoad,v=new Et({domain:"extensibility",action:y}),I=v.eventId;c("Start",{changeTypeName:y,extension:s,extensionInstanceId:f,initialLoad:w,eventId:I});const k=performance.now();try{!function(e,t){if(!At(e)||!Object.keys(t).includes(e.type))throw new _e(`Unknown change type "${e?.type}". Valid change types include: ${Object.keys(t).map(e=>`"${e}"`).join(", ")}.`)}(e,p);const i=e;Tt({journeyCompletedSignal:t,wallets:n,allowChangeAfterJourneyCompletion:h,allowChangeDuringAcceleratedWallet:u}),function({negotiationRateLimiter:e,extension:t}){if(e.isThrottled(t.id))throw new $e(e.reason)}({negotiationRateLimiter:r,extension:s});const o=p[i.type];let g=!1;const x=await o({change:i,negotiate:e=>a({options:{...e,reason:v},extension:s,validateCanNegotiate:()=>Tt({journeyCompletedSignal:t,wallets:n,allowChangeAfterJourneyCompletion:h,allowChangeDuringAcceleratedWallet:u})}),markChangeAsNoOp(){g=!0}});return c("Success",{changeTypeName:y,extension:s,extensionInstanceId:f,startTimestamp:k,initialLoad:w,eventId:I}),d({changeTypeName:y,message:`Applied change ${y} successfully`,extension:s,eventId:I,changeIsNoOp:g}),l({changeTypeName:y,change:i,result:x,extension:s,extensionInstanceId:f,initialLoad:w,changeIsNoOp:g}),x}catch(S){const t=function(e){return e instanceof Error?e:new Ne("string"==typeof e?e:"unknown")}(S);M((C=t).name)||x(C)||g(C)?c("Success",{error:t,changeTypeName:y,extension:s,startTimestamp:k,extensionInstanceId:f,initialLoad:w,eventId:I}):c("Error",{error:t,changeTypeName:y,extension:s,startTimestamp:k,extensionInstanceId:f,initialLoad:w,eventId:I}),i.error(t,{metadata:{extension:b,change:{type:y}}}),d({changeTypeName:y,message:`Could not apply change ${y}. Error: ${t.message}`,extension:s,eventId:I});const n=m(t);return l({changeTypeName:y,change:e,result:n,error:{name:t.name,message:t.message,cause:t.cause},extension:s,extensionInstanceId:f,initialLoad:w}),n}var C}}function At(e){return function(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type}(e)&&(t=e.type,I.includes(t));var t}function Tt({journeyCompletedSignal:e,wallets:t,allowChangeAfterJourneyCompletion:n,allowChangeDuringAcceleratedWallet:s}){if(!n&&e.value)throw new _e("The buyer journey is completed");if(!s&&Boolean(t.activeSession.value))throw new _e("The buyer is using an accelerated wallet")}function Pt(e){const{shop:t,extension:n}=e,{attributes:s}=X(e),{billingAddress:i,shippingAddress:o}=ge(e),{metafields:r}=ee(e),{appMetafields:a}=me(e);return{...G(e),...xe(n.apiVersion)?ne(e):{},...de(e),...re(e),...se(e),...J(e),appMetafields:a,attributes:s,billingAddress:i,extension:ue(e),...Q(n.apiVersion)?{metafields:r}:{},settings:he(e),shippingAddress:o,shop:ce(t),storage:te(e),version:n.apiVersion}}var Rt=oe({name:"purchase.address-autocomplete.suggest",api:e=>({signal:void 0,target:{},...Pt(e)})}),Mt=oe({name:"purchase.address-autocomplete.format-suggestion",api:e=>({target:{},...Pt(e)})}),Nt={[Rt.name]:Rt,[Mt.name]:Mt},Lt={...le,...Nt};function _t(e,n,s){const i={extensionInstance:e,createSubscribableFromSignal:function(s){return o in Nt?s.value:et({get current(){return s.value},subscribe:i=>{if(e.isDestroyed)return()=>{};const o=t(function(){const t=s.value;try{i(t)}catch(o){if(!fe(o))throw o;this.dispose(),n.observability.log("extension_subscriber_revoked","[Extensions::Subscription] Disposed a subscription whose sandbox endpoint was terminated",{...pe(n.extension),extensionInstanceId:e.id,isDestroyed:e.isDestroyed})}}),r=e.on("restart",()=>{c()}),a=e.on("destroy",()=>{c()}),c=()=>{o(),r(),a()};return c}})},...n},o=w(i.extensionInstance.target);return function(e){return Lt[o].api(e,s)}(i)}var Dt=class{#t;#n=new Set;constructor(e){this.#t=e}register(e){this.#n.has(e)||H(e),this.#n.add(e)}unregister(e){this.#n.has(e)&&(z(e),this.#n.delete(e))}emit(e){this.#n.forEach(t=>{try{t(e)}catch(n){throw new P(`ChatMessageRelay listener threw: ${n}`)}})}postMessage(e){this.#t()?.postMessage(e)}destroy(){this.#n.forEach(e=>{z(e)}),this.#n.clear()}get relayApi(){return{register:e=>this.register(e),unregister:e=>this.unregister(e),emit:e=>this.emit(e),postMessage:e=>this.postMessage(e),destroy:()=>this.destroy()}}},Ot=class e{static#s=3e4;static#i=5e3;static#o=2;#r;#a;#c;#d=null;#l;#h=()=>{};#u=()=>{};#p=[];#g=!1;constructor(e){this.#a=new MessageChannel,this.#c=this.#a.port2,this.#l=new Promise((e,t)=>{this.#h=e,this.#u=t}),this.#r=K({id:e.id,url:e.sandboxUrl,privileges:["allow-scripts","allow-same-origin"],name:e.name,referrerPolicy:"strict-origin"}),this.#x(e.sandboxUrl,e.appUrl)}get rpcPort(){return this.#c}get portReady(){return this.#l}onMessage(e){let t=!1;return this.#d?this.#d.addEventListener("message",e):this.#l.then(n=>{t||n.addEventListener("message",e)}).catch(()=>{}),()=>{t=!0,this.#d?.removeEventListener("message",e)}}postMessage(e){this.#d?.postMessage(e)}destroy(){this.#g||(this.#g=!0,this.#p.forEach(e=>e()),this.#d?.close(),this.#c.close(),this.#r.remove())}#m(e){return e.source===this.#r.contentWindow}#f(e,t){return"object"==typeof e.data&&null!==e.data&&e.data.eventName===t}#x(t,n){const s=this.#y(t);if(!s)return;const i=this.#b(n),o=this.#a.port1;let r,a=!1,c=!1;const d=e=>{if(!this.#f(e,"app-bridge-checkout::handshake")||e.origin!==s||!this.#m(e))return;const{originalOrigin:t}=e.data;if(i&&"string"==typeof t&&Z(t,i)&&!c){try{e.source?.postMessage({eventName:"checkout-web::rpc-host-port",originalOrigin:t},{targetOrigin:s,transfer:[o]}),a=!0,r=t}catch(n){if(n instanceof Error&&n.message.includes("already neutered"))return;throw n}window.removeEventListener("message",d),g(),a&&window.addEventListener("message",l)}},l=e=>{const[t,...n]=e.ports??[];this.#f(e,"app-bridge-checkout::port-transfer")&&e.origin===s&&this.#m(e)&&e.data.originalOrigin===r&&t&&!(n.length>0)&&(e.source?.postMessage({eventName:"checkout-web::port-received"},{targetOrigin:s}),this.#d=t,t.start(),this.#h(t),clearTimeout(x),window.removeEventListener("message",l))};let h,u=0;const p=()=>{c=!1,clearTimeout(h),u>=e.#o||(h=setTimeout(()=>{const e=this.#r.contentWindow;e&&(u++,c=!0,e.location.replace(t))},e.#i))},g=()=>{clearTimeout(h),this.#r.removeEventListener("load",p)};this.#r.addEventListener("load",p);const x=setTimeout(()=>{g(),window.removeEventListener("message",d),window.removeEventListener("message",l),this.#u(new Ee("HostedIframe handshake timed out"))},e.#s);window.addEventListener("message",d),this.#p.push(()=>{clearTimeout(x),g(),window.removeEventListener("message",d),window.removeEventListener("message",l)})}#y(e){return this.#b(e)?.origin??null}#b(e){if(!e)return null;try{return new URL(e)}catch{return null}}},jt=class{#w;constructor({context:e,extension:t,id:n,extensionInstanceCache:s,options:o}){this.#w=r(new Set),this.teardowns=[],this.sandboxListenerCleanups=[],this.id=n,this.target=t.extensionPoint.target,this.extension=t,this.options=o,this.extensionInstanceCache=s;const{defaultCacheDuration:a,sandboxCache:c,...d}={...e};this.sandboxCache=c,this.createApiContext=d,this.eventMap=new Map,this.blocking=i(()=>this.#w.value.size>0)}get apiOptions(){return this.options}markBlocking(e){if(this.isDestroyed)return;const t=this.#w.value;if(!t.has(e)){const n=new Set(t);n.add(e),this.#w.value=n}this.emit("block")}markNotBlocking(e){if(this.isDestroyed)return;const t=this.#w.value;if(!t.has(e))return;const n=new Set(t);n.delete(e),this.#w.value=n,0===n.size&&this.emit("unblock")}on(e,t){const n=this.eventMap.get(e),s=n??new Set;return null==n&&this.eventMap.set(e,s),s.add(t),()=>{s.delete(t)}}emit(e){const t=this.eventMap.get(e);if(null!=t)for(const n of t)n()}initializeSandbox(){if(!this.sandboxCache)throw new Le("Attempted to create a sandbox in an environment that does not support them");this.sandbox=this.sandboxCache.getOrCreate({extension:this.extension,storefrontUrl:this.createApiContext.shop.storefrontUrl,myshopifyDomain:this.createApiContext.shop.myshopifyDomain}),this.sandboxListenerCleanups=this.installSandboxListeners(this.sandbox)}notifyError({error:e,isDeactivated:t=!1}){this.createApiContext.observability.error(e,{severity:"error",metadata:{...t?{deactivatedExtension:{id:this.extension.id}}:{},extension:{...E(this.extension),extensionInstanceId:this.id},source:{type:this.createApiContext.sourceType}}})}performCleanup(e){this.createApiContext.observability.leaveErrorBreadcrumb("ExtensionInstance: Destroy set to true",{isDestroyed:this.isDestroyed,rendered:this.rendered,extensionId:this.id,reason:e.reason}),this.#w.value.size>0&&(this.#w.value=new Set,this.emit("unblock"));for(const n of this.sandboxListenerCleanups)n();this.sandboxListenerCleanups=[];const t=this.teardowns;this.teardowns=[],this.extensionInstanceCache.delete(this.id),this.executeTeardowns(t),this.sandbox&&this.sandboxCache?.release(this.sandbox),this.emit("destroy"),this.eventMap.clear(),this.createApiContext.observability.leaveErrorBreadcrumb("ExtensionInstance: Destroy event emitted",{isDestroyed:this.isDestroyed,rendered:this.rendered,extensionId:this.id,reason:e.reason})}addTeardown(e){this.isDestroyed?this.executeTeardowns([e]):(this.teardowns.length>=100&&(this.teardowns.shift(),this.createApiContext.observability.log("extension_teardown_queue_overflow","[Extensions::Teardown] Teardown queue exceeded 100, dropping oldest",{appId:this.extension.appId,extensionId:this.extension.extensionId,registrationId:"registrationId"in this.extension?this.extension.registrationId:void 0})),this.teardowns.push(e))}executeTeardowns(e){Promise.allSettled(e.map(e=>{try{return e()}catch(t){return Promise.reject(t)}})).then(e=>{for(const t of e){if("rejected"!==t.status)continue;const e=t.reason;fe(e)||Ce(e)||this.createApiContext.observability.log("extension_teardown_error","[Extensions::Teardown] Teardown failed",{errorClass:e instanceof Error?e.constructor.name:typeof e,errorMessage:String(e),errorStack:e instanceof Error?e.stack??"":""})}})}};function Ut({createApiContext:e,extension:t,phase:n,instanceId:s,mountId:i,mountStartTime:o,page:r="",error:a}){const{captureEvent:c,observability:d}=e,l="mountStart"===n||null==o?void 0:Date.now()-o,h=a instanceof Error?a:void 0;if(c("extensionLifecycle",{duration:l,extension:t,phase:n,section:"extension",page:r,timestamp:new Date,instanceId:s,...i&&{mountId:i},...h&&{error:h},initialPageLoad:Ye.initialLoad}),"mountSuccess"===n||"mountError"===n){const e={...pe(t),duration:l,...i&&{mountId:i},...h&&{error:{...h,message:h?.message??String(h)}}};"persisted"!==t.type&&"global"!==t.type||d.log("extensions_lifecycle_event_phase_captured",`[Extensions::Lifecycle] ${n}`,e),d.debug("extensions_lifecycle_event_phase_captured",`[Extensions::Lifecycle] ${n}`,e)}}var $t=Y(),Bt=class extends jt{constructor({context:e,extension:t,id:n,options:s,extensionInstanceCache:i}){super({context:e,extension:t,id:n,options:s,extensionInstanceCache:i});const{defaultCacheDuration:o,sandboxCache:r,mountRateLimiter:a}=e;var c;this.receiver=new ye(t),this.addDeactivatedExtension=t=>{this.deactivated=!0,e.checkout.extensibility.ui.deactivatedExtensions.add(t)},this.deactivated=!1,this.defaultCacheDuration=o,this.mountRateLimiter=a,this.sandboxCache=r,this.sandboxAppBridgeUrl=e.sandboxAppBridgeUrl,this.isMounted=!1,this.destroyed=!1,this.renderCount=0,"purchase.checkout.chat.render"!==(c=t.extensionPoint.target)&&"purchase.thank-you.chat.render"!==c||"undefined"==typeof document||(this.messageRelay=new Dt(()=>this.currentHostedIframe))}createHostedIframe(){if(this.messageRelay&&!this.destroyed)return this.currentHostedIframe?.destroy(),this.currentHostedIframe=new Ot({sandboxUrl:this.sandboxAppBridgeUrl,appUrl:this.extension.extensionPoint.preloads?.chat,id:`checkout.shopify.com-${this.id}-${D()}`,name:"checkout.shopify.com/app-bridge-checkout"}),this.currentHostedIframe}releaseHostedIframe(e){e.destroy(),this.currentHostedIframe===e&&(this.currentHostedIframe=void 0)}get mounted(){return this.isMounted}get rendered(){return this.renderCount>0}get isDestroyed(){return this.destroyed}async initialize(e){try{await this.mount(e)}catch(t){this.notifyError({error:t,isDeactivated:this.deactivated})}this.leaveBreadcrumbForMountedExtension()}render(){if(this.destroyed)throw new Pe(`Can't render extension ${this.extension.id} because it has already been destroyed`);if(this.destroyTimeout&&(clearTimeout(this.destroyTimeout),this.destroyTimeout=void 0),this.renderCount+=1,"local"!==this.extension.type){const e=this.mountRateLimiter.checkRate(this.id);if(!e.allowed){const t=null!=this.extension.registrationId&&Ze.has(this.extension.registrationId);this.createApiContext.observability.counter({name:"extension_mount_rate_exceeded",value:1,attributes:{reason:"rapid_mounting_detected",isHighValueExtension:t}}),this.createApiContext.observability.leaveErrorBreadcrumb("RenderExtensionInstance: Mount rate limit exceeded - possible infinite reload loop",{reason:e.reason,extensionId:this.extension.id,extensionType:this.extension.type,extensionPoint:this.extension.extensionPoint.target,appId:this.extension.appId,renderCount:this.renderCount}),this.createApiContext.observability.log("extension_mount_rate_exceeded","Extension mount rate limit exceeded - possible infinite reload loop",{...pe(this.extension),renderCount:this.renderCount,retryAfterSeconds:e.retryAfterSeconds,reason:e.reason})}}return this.mount().catch(e=>{this.notifyError({error:e,isDeactivated:this.deactivated})}),this.emit("render"),({cache:e=this.defaultCacheDuration}={})=>{this.destroyWithCache({cache:e,reason:"render_timeout"})}}destroy(e){this.destroyed||(this.destroyTimeout&&(clearTimeout(this.destroyTimeout),this.destroyTimeout=void 0),this.currentHostedIframe?.destroy(),this.currentHostedIframe=void 0,this.messageRelay?.destroy(),this.destroyed=!0,this.performCleanup(e),"checkout_profile_change"===e.reason&&this.captureExtensionLifecycleEvent("checkoutProfileChangeDestroy"))}installSandboxListeners(e){return[e.on("error",e=>{if(this.destroyed)return;if(e instanceof L)return void this.notifyError({error:e});const t="ExtensionSandboxError"===e.name?new je(String(e)):new P(String(e));this.notifyError({error:t})}),e.on("restart",()=>{this.isMounted=!1,this.receiver=new ye(this.extension),this.mountPromise=this.renderAndMountExtension(this.api),this.emit("restart")})]}destroyWithCache(e){this.renderCount>0&&(this.renderCount-=1);const t=e.cache??this.defaultCacheDuration,n=Date.now(),s=Math.max(this.cacheUntil??n,n+t);if(this.cacheUntil=s,this.emit("remove"),this.createApiContext.observability.debug("extensions_lifecycle_event_phase_captured","[Extensions::Lifecycle] Remove event emitted",{...pe(this.extension),isDestroyed:this.destroyed,rendered:this.rendered,extensionInstanceId:this.id,extensionDestroyedReason:e.reason}),this.destroyTimeout||this.destroyed)return;if(this.renderCount>0)return;const i=Math.max(0,this.cacheUntil-n);i<=0?this.destroy(e):this.destroyTimeout=setTimeout(()=>{this.destroy(e)},i)}async mount(e){return this.destroyed?Promise.reject(new Pe(`Can't mount extension ${this.extension.id} because it has already been destroyed`)):(null!=this.mountPromise||(this.initializeSandbox(),Ye.markStarted("api-object",{extension:this.extension,instanceId:this.id,type:"extension"}),this.api=_t(this,{...this.createApiContext,extension:this.extension,storefrontTokens:this.createApiContext.storefrontTokens},this.options),Ye.markFinished("api-object",{extension:this.extension,instanceId:this.id,type:"extension"}),this.stepOnMount=e?.currentStep,this.mountPromise=this.renderAndMountExtension(this.api)),this.mountPromise)}async renderAndMountExtension(e){const t=D();this.deactivated=!1;const n=this.receiver,s=()=>this.receiver===n;let i,o=!1;const r=(async()=>{try{const i=this.extension.extensionPoint.target,r=k(i),a=i===r?i:[i,r];if(this.mountStartTime=Date.now(),this.captureExtensionLifecycleEvent("mountStart",void 0,t),!this.destroyed){let t;if(W(this.extension.apiVersion))t=n.connection;else{const e=be(n.connection);t=(...t)=>{o||this.destroyed||!s()||e(...t)}}const{acceptSmsMarketing:i,smsMarketingPhone:r}=this.createApiContext.proposal.parts,c=await(this.sandbox?.render(a,t,$t,e,this.createApiContext.storefrontTokens,this.id,this.extension.id,{acceptSmsMarketing:!!B(this.extension)&&i.peek(),smsMarketingPhone:O(this.extension)?r.peek():""},this.messageRelay?.relayApi));c?.teardown&&this.addTeardown(c.teardown)}}catch(r){if(!this.destroyed||!r?.message?.includes("terminated web worker")){let e;switch(this.addDeactivatedExtension(this.extension.id),r?.name){case"ExtensionUsageError":case"ExtensionAssetFetchError":case"ExtensionSandboxAssetFetchError":e=r;break;case"DataCloneError":e=new P("DataCloneError occurred: failed to render extension",{cause:r});break;default:e=new De(String(r),{cause:r,groupingHash:`ExtensionRenderError::${r.name??"Unknown"}`})}throw"ExtensionUsageError"!==e.name||"persisted"!==this.extension.type&&"global"!==this.extension.type||this.createApiContext.observability.log("render_extension_instance_usage_error_occurred","Extension usage error occurred: failed to render extension",{...pe(this.extension),errorMessage:r.message}),e}i=r}if(this.destroyed){const e=`${this.extension.extensionPoint.target}:${this.extension.placementReference}`,t=i?{cause:i}:void 0;if("local"===this.extension.type)throw new ve(`Local extension ${this.extension.id} was destroyed before it finished mounting at ${e}`,t);if(this.sandbox?.isWorkerAvailable())throw new Te(`Extension ${this.extension.id} was destroyed before it finished mounting at ${e}`,t);throw new Pe(`Extension ${this.extension.id} was destroyed before it finished mounting at ${e}`,t)}if(!s()){if("local"===this.extension.type)throw new Ie(`Local extension ${this.extension.id} was restarted before it finished mounting`);throw new Ue(`Extension ${this.extension.id} was restarted before it finished mounting`)}o||(this.isMounted=!0),Ye.markFinished("execution",{instanceId:this.id,extension:this.extension,type:"extension"}),Ye.markStarted("wait-time-after-execution",{instanceId:this.id,extension:this.extension,type:"extension"})})(),a=this.getExtensionMountTimeout(this.extension),c=new Promise((e,t)=>setTimeout(()=>{0!==a&&(this.destroyed||this.isMounted||!s()?e():(o=!0,this.addDeactivatedExtension(this.extension.id),t(new we(`Extension ${this.extension.id} timed out while mounting`,{causeOfTimeout:this.sandbox?.isWaitingOnExtension(this.id,this.extension.id)?"extension":"host"}))))},a));try{await Promise.race([r,c]),!this.destroyed&&s()&&this.captureExtensionLifecycleEvent("mountSuccess",void 0,t),this.emit("mount")}catch(d){throw this.captureExtensionLifecycleEvent("mountError",d,t),d}}captureExtensionLifecycleEvent(e,t,n){Ut({createApiContext:this.createApiContext,extension:this.extension,phase:e,instanceId:this.id,mountId:n,mountStartTime:this.mountStartTime,page:this.stepOnMount||"",error:t})}leaveBreadcrumbForMountedExtension(){const{id:e,extensionId:t,extensionPoint:{target:n},placementReference:s,appId:i,apiVersion:o}=this.extension;this.createApiContext.observability.leaveErrorBreadcrumb("Extensions:mountExtension",{id:e,extensionId:t,extensionPoint:n,placementReference:s,appId:i,apiVersion:o,currentStep:this.stepOnMount??""})}getExtensionMountTimeout(e){return this.createApiContext.shop.extendedExtensionTimeout?0:e.capabilities?.blockProgress?3e4:0}},qt=class extends jt{constructor({context:e,extension:t,extensionInstanceCache:n,id:s,options:i}){super({context:e,id:s,extension:t,extensionInstanceCache:n,options:i}),this.rendered=!1,this.destroyed=!1,this.initialized=!1,this.hasAttemptedMount=!1,this.hasMounted=!1,this.hasReportedMountError=!1}get isDestroyed(){return this.destroyed}async initialize(){this.initialized||(this.initializeSandbox(),this.createStaticApi(),this.initialized=!0)}async run(e){const{target:t}=this.extension.extensionPoint;if(this.initialize(),this.destroyed)return;const n=!this.hasAttemptedMount;n&&(this.hasAttemptedMount=!0,this.mountId=D(),this.mountStartTime=Date.now(),this.firstRunSignal=e?.signal,this.captureExtensionLifecycleEvent("mountStart"));try{const{output:n,teardown:s}=await this.sandbox.run(t,{...this.createStaticApi(),...e},this.id,this.extension.id);return this.addTeardown(s),this.hasMounted||this.destroyed||(this.hasMounted=!0,this.captureExtensionLifecycleEvent("mountSuccess")),n}catch(s){if(this.destroyed&&s?.message?.includes("terminated web worker"))return;if(function(e,t,n){return"purchase.address-autocomplete.suggest"===e&&!0===n?.aborted&&"AbortError"===t?.name}(t,s,e?.signal))return;const i="ExtensionUsageError"===s?.name||"ExtensionAssetFetchError"===s?.name?s:new Ae(String(s));!n&&!this.firstRunSignal?.aborted||this.hasReportedMountError||this.hasMounted||this.destroyed||(this.hasReportedMountError=!0,this.captureExtensionLifecycleEvent("mountError",i)),this.notifyError({error:i})}}destroy(e){this.destroyed=!0,this.performCleanup(e)}installSandboxListeners(e){return[e.on("error",e=>{if(this.destroyed)return;if(e instanceof L)return void this.notifyError({error:e});const t="ExtensionSandboxError"===e.name?new je(String(e),{cause:e}):new P(String(e),{cause:e});this.notifyError({error:t})})]}captureExtensionLifecycleEvent(e,t){try{Ut({createApiContext:this.createApiContext,extension:this.extension,phase:e,instanceId:this.id,mountId:"mountStart"===e||"mountSuccess"===e||"mountError"===e?this.mountId:void 0,mountStartTime:this.mountStartTime,error:t})}catch(n){this.createApiContext.observability.leaveErrorBreadcrumb("RunnableExtensionInstance: failed to capture lifecycle event",{phase:e,extensionId:this.id,error:n instanceof Error?n.message:String(n)})}}createStaticApi(){return _t(this,{...this.createApiContext,extension:this.extension,storefrontTokens:this.createApiContext.storefrontTokens},this.options)}};function Ft(e){return new Vt(e)}var Vt=class{#v;#I;constructor(e){this.context=e,this.cache=new Map,this.#v=new Map,this.#I=r([]),this.context.checkout.extensibility.ui.unstable_registerExtensionsManager(this),this.blockingExtensions=this.#I}get(e,t){const n=this.createFullIdentifier({id:e.id,target:e.extensionPoint.target,options:t}),s=this.cache.get(n);if(s)return s;const i=this.context.interceptorRegistrationResolversSignal.peek(),o=ae(i,e.id),r=ae(i,n),a=this.createExtensionInstance({context:this.context,extension:e,id:n,options:t,extensionInstanceCache:this.cache});return a.on("block",()=>{this.#v.set(a.id,e),this.#k()}),a.on("unblock",()=>{this.#v.delete(a.id),this.#k()}),a.on("destroy",()=>{ie(i,n,r),this.#v.delete(a.id),this.#k();for(const t of this.cache.values())if(t.extension.id===e.id)return;ie(i,e.id,o)}),this.cache.set(n,a),a}findAll(e){const t=this.createFullIdentifier(e);return Array.from(this.cache.values()).filter(({id:e})=>e===t||e.startsWith(`${t}?`))}#k(){const e=new Map;for(const t of this.#v.values())e.has(t.id)||e.set(t.id,t);this.#I.value=[...e.values()]}createExtensionInstance(e){const{extension:t}=e;return w(t.extensionPoint.target)in Nt?function(e){return new qt(e)}(e):function(e){return new Bt(e)}(e)}createFullIdentifier({id:e,target:t,options:n}){const s=`${e}:${t}`;if(null==n)return s;const i=Object.keys(n);if(0===i.length)return s;let o="";for(const r of i.sort((e,t)=>e.localeCompare(t)))o.length>0&&(o+="&"),o+=`${r}=${JSON.stringify(n[r])}`;return`${s}?${o}`}};function zt(e,t,n=()=>{}){const s=[],i=t.merchandiseLines?.lines?.filter(e=>e.variantId)?.flatMap(e=>e.lineAllocations)?.flatMap(({stableId:e})=>e?[e]:[])??[],o=e=>i.map(t=>({extension:e,options:{stableId:t}}));for(const r of e){const e=n(r);if(e&&"purchase.checkout.block.render"===k(r.extensionPoint.target)){if(e.has("purchase.checkout.cart-line-item.render-after")&&s.push(...o(r)),[...e].some(m)){const{hasMultipleDeliveryGroups:e,onlyDeliveryGroupType:n}=Fe(t.deliveryNext,{current:void 0}),i=t.deliveryNext;let o=[n];e&&(o=[],qe(r.apiVersion)&&i&&"lines"in i&&(o=i.lines.filter(v).map(({type:e})=>e))),s.push(...o.map(e=>({extension:r,options:{groupType:e&&Be(e),includeDeliverySelectionGroups:!1}})))}if([...e].every(e=>N(e)||m(e)))continue}switch(w(r.extensionPoint.target)){case"Checkout::ThankYou::CartLineDetails::RenderAfter":case"Checkout::CartLineDetails::RenderLineComponents":case"Checkout::CartLineDetails::RenderAfter":s.push(...o(r));break;case"Checkout::GiftCard::Render":case"Checkout::PickupPoints::RenderBefore":case"Checkout::PickupPoints::RenderAfter":case"Checkout::PickupLocations::RenderBefore":case"Checkout::PickupLocations::RenderAfter":case"Checkout::PaymentMethod::Render":case"Checkout::PaymentMethod::HostedFields::RenderAfter":case"Checkout::ShippingMethodDetails::RenderAfter":case"Checkout::ShippingMethodDetails::RenderExpanded":break;case"Checkout::ShippingMethods::RenderBefore":case"Checkout::ShippingMethods::RenderAfter":["2023-04","2023-07","2023-10"].includes(r.apiVersion)&&s.push({extension:r});break;default:s.push({extension:r})}}return s}function Ht(){return new Kt({maxRequests:20,windowMs:6e4,reason:"Too many checkout changes. See https://shopify.dev/docs/api/checkout-ui-extensions/latest#apply-changes-update-the-cart-and-checkout for details"})}var Kt=class{#E=new Map;#C=new Set;constructor(e){this.maxRequests=e.maxRequests,this.windowMs=e.windowMs,this.reason=e.reason}isThrottled(e){return this.#C.has(e)}record(e,t){if(this.#C.has(e))return{isThrottled:!0,isFirstThrottled:!1};const n=Date.now();let s=this.#E.get(e);s||(s=[],this.#E.set(e,s));const i=n-this.windowMs,o=s.filter(e=>e.timestamp>i);return this.#E.set(e,o),o.length>=this.maxRequests?(this.#C.add(e),{isThrottled:!0,isFirstThrottled:!0}):(o.push({timestamp:n,eventId:t}),{isThrottled:!1,isFirstThrottled:!1})}eventIds(e){return this.#S(e).map(e=>e.eventId).filter(e=>null!=e)}count(e){return this.#S(e).length}#S(e){const t=this.#E.get(e)??[];if(this.#C.has(e))return t;const n=Date.now()-this.windowMs;return t.filter(e=>e.timestamp>n)}},Wt=class{#A=new Map;#T;constructor(e){this.#T=e}checkRate(e){const t=Date.now();let n=this.#A.get(e);n||(n={tokens:this.#T.maxTokens,lastCheck:t},this.#A.set(e,n));const s=(t-n.lastCheck)/1e3*this.#T.refillRate;if(n.tokens=Math.min(this.#T.maxTokens,n.tokens+s),n.lastCheck=t,n.tokens<1){const e=(1-n.tokens)/this.#T.refillRate;return{allowed:!1,reason:this.#T.reason,retryAfterSeconds:Math.ceil(e)}}return n.tokens-=1,{allowed:!0,tokensRemaining:Math.floor(n.tokens)}}};function Gt(){return new Wt({maxTokens:20,refillRate:2,reason:"Exceeded emission rate limit."})}var Qt=class{#P=new Map;get(e){return this.#P.get(e)}record(e,t){this.#P.set(e,t)}};function Jt(){const{checkout:{journey:t}}=V(),s=e(void 0),i=d(e=>{if(e){const[n,s]=e;t.detour(n,s)}},[t]);return n(()=>{const e=s.value;return p(()=>i(e))}),s}export{pt as _,Ht as a,St as c,vt as d,wt as f,gt as g,mt as h,Gt as i,kt as l,xt as m,Qt as n,zt as o,yt as p,Wt as r,Ft as s,Jt as t,It as u,ut as v,tt as y};