@tinkerlandai/indiana-sdk 0.10.1 → 0.10.2

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +28 -28
  3. package/README.zh-CN.md +22 -22
  4. package/dist/{chunk-ABNSU3ZG.js → chunk-CWHJKWOD.js} +1 -1
  5. package/dist/chunk-EARSGITJ.js +1 -0
  6. package/dist/{chunk-WYZI3TNB.js → chunk-FYGXGMRB.js} +1 -1
  7. package/dist/chunk-GHJ65ILJ.js +1 -0
  8. package/dist/chunk-JPV7F5XI.js +1 -0
  9. package/dist/{chunk-QUWPPZHH.js → chunk-LCLCG2I2.js} +1 -1
  10. package/dist/{chunk-2Y4G5364.js → chunk-Q64VNSPV.js} +3 -3
  11. package/dist/{chunk-CCPNMQHZ.js → chunk-V3RAOCVQ.js} +1 -1
  12. package/dist/{chunk-EDQCH2QS.js → chunk-VZVUZWP2.js} +1 -1
  13. package/dist/{chunk-AHXYGGAA.js → chunk-XO42OH3M.js} +1 -1
  14. package/dist/{configuration-sync-CXe9Zcng.d.ts → configuration-sync-CywDxRkX.d.ts} +1 -1
  15. package/dist/{content-ZRWZ26PF.js → content-QM75T7JO.js} +1 -1
  16. package/dist/{funnel-local-client-BQsdOjQ7.d.ts → funnel-local-client-DXamAj1-.d.ts} +2 -2
  17. package/dist/{funnel-resource-client-Zof1WLgA.d.ts → funnel-resource-client-md62M8Rv.d.ts} +2 -2
  18. package/dist/funnel-runtime-host-BJZUVJAI.js +1 -0
  19. package/dist/index.d.ts +5 -5
  20. package/dist/index.js +1 -1
  21. package/dist/native-shell.js +1 -1
  22. package/dist/openrouter.js +1 -1
  23. package/dist/page.d.ts +2 -2
  24. package/dist/page.js +1 -1
  25. package/dist/{paywall-DR65VN2G.js → paywall-527RPFAX.js} +1 -1
  26. package/dist/react-native.d.ts +5 -5
  27. package/dist/react-native.js +1 -1
  28. package/dist/server.d.ts +5 -5
  29. package/dist/server.js +1 -1
  30. package/dist/visual.js +1 -1
  31. package/package.json +2 -2
  32. package/dist/chunk-6ZZUNGNE.js +0 -1
  33. package/dist/chunk-IWWKVNEX.js +0 -1
  34. package/dist/chunk-Y46ALAKP.js +0 -1
  35. package/dist/funnel-runtime-host-N7TX3LWI.js +0 -1
@@ -1 +1 @@
1
- import{b as dn,c as mn,d as fn,e as pn}from"./chunk-SBPTOOYB.js";import{$ as Ke,Aa as rn,Ba as on,Ea as an,Fa as sn,Ia as un,M as Ge,Na as ln,O as Je,Oa as cn,P as Be,Pa as te,Q as je,Qa as Q,Y as H,Z as ze,_ as q,aa as Ee,ba as L,ca as Qe,da as Ye,ea as $e,fa as We,ga as Ze,ha as Xe,j as ie,na as ne,oa as en,qa as we,ra as nn,sa as tn}from"./chunk-2Y4G5364.js";import{oa as He,qa as l}from"./chunk-ACF2FBUB.js";import{a as Me,e as ye}from"./chunk-G56XGVMS.js";import{b as ae}from"./chunk-IWWKVNEX.js";import{b as ge}from"./chunk-7DXL3LHT.js";import{e as Ue,h as qe}from"./chunk-3PZ4Y6UD.js";function Un(e){let n=null,t=null,f=0,u=0,g=!1,c=new Set,r=null,o=null,a=new Set,w=()=>{for(let m of a)try{m()}catch{}},d={attributes:ge.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(m,v)=>{!c.has(m)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(m,structuredClone(v),structuredClone(d.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(m,v)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(m),structuredClone(v),structuredClone(d.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?m=>e.saveStickyBucketAssignmentDoc(structuredClone(m)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},C=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function _(m,v=new Set){return c.has(m)?!r||!r.features[m]||["unknownFeature","cyclicPrerequisite"].includes(r.features[m].source):v.has(m)?!1:(v.add(m),(n?.features[m]?.rules??[]).some(S=>[...S.parentConditions??[],...(S.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>_(R.id,v))))}let E=m=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,d.features=n.features),c.has(m)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?C():structuredClone(r.features[m]??C()):e.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!g||_(m)?C():structuredClone(qe(m,d))};async function F(){if(!n||!c.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(c.size)throw new Error("Remote Feature evaluation requires a server loader");return}let m=u;if(o?.revision===m)return o.loading;let v=f,S=n,R=[...c],P=(async()=>{let T=je.parse(await e.evaluateRemote({attributes:structuredClone(d.attributes),features:R}));if(!(v!==f||m!==u||S!==n)){if(e.assertUsable?.(S.generation),T.generation!==S.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(O=>!Object.hasOwn(T.features,O))||Object.keys(T.features).some(O=>!c.has(O)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=ge.parse({...d.attributes,...T.merchandiseContext}),g=!0}r=structuredClone(T),d.features={...S.features,...Object.fromEntries(Object.entries(r.features).map(([O,k])=>[O,{defaultValue:k.value}]))},w()}})();o={revision:m,loading:P};try{await P}finally{o?.loading===P&&(o=null)}}function i(){F().catch(m=>{try{e.onError?.(m)}catch{}})}async function s(){if(t)return t;let m=f,v=(async()=>{let S=await e.load(),R="remoteFeatures"in S?Je.parse(S):null,P=R??ye.parse(S);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(m!==f)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===P.generation){let{evaluatedAt:O,expiresAt:k,...G}=n,{evaluatedAt:W,expiresAt:J,...Z}=P;if(L(G)!==L(Z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=P.evaluatedAt,n.expiresAt=P.expiresAt,w(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&i(),structuredClone(n)}let T=new Set(R?.remoteFeatures??[]);if([...T].some(O=>Object.hasOwn(P.features,O)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in P&&!n.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),n=structuredClone(P),c=T,r=null,o=null,u++,d.features=n.features,d.savedGroups=Ue(n.savedGroups),d.trackedFeatureUsage={},w(),i(),structuredClone(n)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:s,refresh:s,refreshRemote:F,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(m){return a.add(m),()=>{a.delete(m)}},setAttributes(m){let v=ge.parse(m);(d.attributes?.merchandise||d.attributes?.merchandiseId||m.merchandise||m.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=v,u++,g=!1,r=null,o=null,d.features=n?.features??{},d.trackedFeatureUsage={},w(),i()},evalFeature:E,isOn(m){return E(m).on},isOff(m){return E(m).off},getFeatureValue(m,v){let S=E(m).value;return structuredClone(S===null?v:S)},reset(){f++,u++,t=null,o=null,n=null,r=null,c.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),w()}}}function gn(e){let n,t,f=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw f();let r=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ae).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function g(r){try{let o=await u;return await t.request(o,{mode:"exclusive"},()=>r(o))}catch(o){throw o instanceof l?o:f()}}function c(r){let o=n.getItem(r);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw f();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw f();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(c),write:(r,o)=>g(a=>{if(c(a).revision!==r)return null;if(!Number.isSafeInteger(r+1))throw f();return n.setItem(a,JSON.stringify({revision:r+1,entry:o})),r+1})}}async function he(e,n){let t=nn.safeParse(n);if(!t.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return f}async function Ae(e,n,t){if(Number(e.headers.get("content-length"))>n)throw t.error("limit");let f=e.body?.getReader();if(!f)throw t.error("missing");let u=[],g=0;try{for(;;){t.signal?.throwIfAborted();let o=await f.read();if(o.done)break;if(g+=o.value.length,g>n)throw t.error("limit");u.push(o.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let c=new Uint8Array(g),r=0;for(let o of u)c.set(o,r),r+=o.length;return c}async function yn(e,n,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ae(e,n,t))}function Ie(e,n){let t=typeof e=="string"?new TextEncoder().encode(e):e;return t.byteLength===n.byteLength&&Qe(t)===n.sha256}async function ve(e,n){let t=Ze.parse(n),{artifact:f,environmentId:u}=t.content,g=new te(e.baseUrl??ae).origin,c=new te(f.url,g);if(c.origin!==g||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let r=new AbortController,o=setTimeout(()=>r.abort(),q.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:r.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>f.byteLength)throw new l("INVALID_RESPONSE","Public Paywall is unavailable");let w=await Ae(a,f.byteLength,{signal:r.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ie(w,f))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return Xe(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(w)))}finally{clearTimeout(o)}}var Fe=(e,n)=>new l(e,n);function rt(e){return sn(e,Fe)}async function Ne(e,n,{predict:t=!0}={}){let f=n.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==f.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let u=null,g;if(t)try{let c=await e.funnel(n.source.id,n.source.versionId);g=c.manifest.generation,u=Tn(e,n,c)}catch{u=null}return g??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:g},prediction:u}}function Tn(e,n,t){let f=n.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:g,...c}=t.growth,r=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:ye.parse(c)}),o=On(r,t.document,{...n,...f}),a=o.steps.at(-1),w=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return w?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:w.nodeId,visit:w.visit,terminal:!o.boundary}:null}function On(e,n,t){return un(e,n,t,Fe)}import{z as B}from"zod";var wn=H.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=B.strictObject({schemaVersion:B.literal(1),scope:Me,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),M=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Re=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,t=null,f=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),u=Promise.resolve();async function g(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:hn.parse(o.entry)}}function c(o){let a=u.then(o);return u=a.catch(()=>{}),a}async function r(o){for(let a=0;a<4;a++){let w=await g();if(w.entry&&t!==null&&f(w.entry)!==t)throw M();let d=o(w.entry,w.revision);if(Re(w.entry,d)){n=w.revision;return}let C=await e.write(w.revision,d);if(C!==null){if(!Number.isSafeInteger(C)||C<=w.revision)throw M();n=C;return}}throw M()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(t!==null&&t!==a)throw M();t=a},async load(){let o=await g();return n=o.revision,t=o.entry?f(o.entry):null,o.entry},retain(o){let a=hn.parse(o),w=a.command;return!w||t!==null&&f(a)!==t?Promise.reject(M()):(t??=f(a),c(()=>r((d,C)=>{if(d&&!Re(f(d),f(a)))throw M();if(!d){if(C!==n&&w.operation!=="close")throw M();return a}if(!d.command)return{...d,command:w,...w.operation==="close"?{closed:!0}:{}};if(w.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===w.requestId||d.closeCommand&&!Re(d.closeCommand,w))throw M();return{...d,closeCommand:w,closed:!0}}if(!Re(d.command,w))throw M();return d})))},observePurchase(o,a,w){return c(()=>r((d,C)=>{if(!d&&C!==n||d&&f(d)!==f({...o,schemaVersion:1}))throw M();if(d?.purchase&&d.purchase.generation>a.generation)return d;if(d?.purchase&&d.purchase.generation===a.generation&&d.purchase.operationId!==a.operationId)throw M();return w?!d?.purchase||d.purchase.operationId!==a.operationId?d:d.command?{...d,purchase:void 0}:null:{schemaVersion:1,...o,...d,purchase:a}}))},settle(o){return c(()=>r(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function ft(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function se(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((u,g)=>se(u,n[g]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),f=Object.entries(n);return t.length===f.length&&t.every(([u,g])=>Object.hasOwn(n,u)&&se(g,Reflect.get(n,u)))}function vn(e){let n=null,t=0,f=!1,u,g=0,c=new Set;return{get view(){return n},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return g},nextRead(){return++g},assertCurrent(r,o="Run identity changed during the request"){if(r!==t||f)throw new l("IDENTITY_CHANGED",o)},assertRun(r){if(n&&(r.id!==n.id||r.source.type!==n.source.type||r.source.id!==n.source.id||r.source.versionId!==n.source.versionId||r.locale!==n.locale||!se(r.parameters,n.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&r.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(r,o,a,w,d){if(!(r.operation==="review"&&n&&n!==a&&o.run.revision<=n.revision)&&!(n&&o.run.revision===n.revision&&w!==void 0&&w<g)&&(r.operation==="review"&&!o.run.stopped&&["running","waiting"].includes(o.run.status)&&n&&o.run.nodeId===n.nodeId&&o.run.visit===n.visit&&o.run.revision===n.revision&&(o.run.screen=n.screen,(n.paywall?.quote?.operationId===o.review?.activeOperationId||!n.paywall?.quote&&o.review?.activeOperationId===null)&&(o.run.paywall=n.paywall)),!(n?.paywall&&o.run.paywall&&n.paywall.receiptId===o.run.paywall.receiptId&&(o.run.paywall.selectionGeneration??0)<(n.paywall.selectionGeneration??0)))){if(!n||o.run.revision>=n.revision)n=o.run;else if(!d)return;if(n)for(let C of c)try{C(structuredClone(n))}catch{}}},identify(r){if(!ie.test(r))throw new l("INVALID_TOKEN","Customer credential required");t++,u=r},subscribe(r){return c.add(r),()=>c.delete(r)},reset(){f=!0,t++,u=void 0,n=null,c.clear()}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vt(e,n,t="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!re.test(e))throw new l("INVALID_TOKEN",t)}function Rt(e){let n=Q(e);return n.identify(e.apiKey),n}function Y(e){let{customerToken:n,...t}=e;return t}var _n=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Rn({options:e,journal:n,state:t,call:f}){let u=null,g=null,c=!1,r={command:null,close:null},o=!1,a,w=null,d=n?n.load().then(i=>{if(t.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(w=i,!i)return;if(e.scope&&(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=i.purchase,c=i.closed===!0,!i.command)return;let s=H.parse(i.command);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");u=s,i.closeCommand&&(g=i.closeCommand,c=!0),s.operation==="close"&&(c=!0),o=!0}):Promise.resolve();d.catch(()=>{});async function C(i=u){if(n&&await d,!i)throw new l("INVALID_REQUEST","No command is pending");let s=i,m=t.generation;if(n){if(!t.view||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await n.retain({schemaVersion:1,scope:e.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:Y(s)})}if(m!==t.generation||u!==s&&g!==s)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let v={...s,...t.customerToken?{customerToken:t.customerToken}:{}},S=o;o=!0;try{return await f(v,R=>{if(!R.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==s.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(m===t.generation&&(u===s||g===s)&&R.run.pendingRequest?.requestId!==s.requestId&&R.settlement.state==="settled"&&(!c||s.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let P=()=>m!==t.generation||u!==s&&g!==s?!1:(u===s&&(u=null),g===s&&(g=null),o=u!==null,w=null,!0);return n?n.settle(s.requestId).then(P):P()}return!1})}catch(R){throw m===t.generation&&u===s&&!S&&!_n(R)&&(n&&await n.settle(s.requestId),m===t.generation&&u===s&&(u=null,o=!1,w=null)),R}}function _(i){let s=H.parse(i);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(c&&s.operation!=="close"){if(u?.requestId===s.requestId)return F(s.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(s.operation==="close"&&u?.operation!=="close"){if(c=!0,g&&JSON.stringify(Y(g))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original Close");return g??=s,r.close?r.close:E(g,"close")}if(u){if(JSON.stringify(Y(u))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(r.command)return r.command}else u=s,o=!1;return E(u,"command")}function E(i,s){let m=C(i);r[s]=m;let v=()=>{r[s]===m&&(r[s]=null)};return m.then(v,v),m}async function F(i){let s=await f({operation:"get",settlementRequestId:i,...t.customerToken?{customerToken:t.customerToken}:{}});if(s.settlement?.requestId!==i)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return s.settlement.state==="settled"&&(n&&await n.settle(i),u?.requestId===i&&(u=null,o=!1),g?.requestId===i&&(g=null)),s}return{ready:d,get pending(){return u},get closing(){return g},get closeRequested(){return c},get inFlight(){return r.command},get closeFlight(){return r.close},get purchase(){return a},assertBinding(i){if(w&&(i.run.id!==w.runId||i.run.source.id!==w.funnelId||i.run.source.versionId!==w.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(i,s,m,v){n?.bind({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId}),n&&!e.scope&&(e.scope=s.scope);let S=s.run.paywall,R=S??s.purchase,P=R?.operation,T=s.settlement&&(!S||S.purchaseRequestId===s.settlement.requestId)&&(!a||a.operationId===s.settlement.operationId)?s.settlement:void 0,O=P?.operationId??R?.quote?.operationId??T?.operationId,k=R?.receiptId??T?.receiptId,G=S?.selectionGeneration??a?.generation??0;if(n&&O&&k&&i.operation!=="review"&&(!t.view||s.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!a||G>=a.generation)){let W={receiptId:k,operationId:O,generation:G},J=P?.status==="complete"||R?.canReselect===!0;return n.observePurchase({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId},W,J).then(()=>{t.assertCurrent(m),J?a?.operationId===W.operationId&&(a=void 0):a=W})}},stop(){c=!0},submit:_,executePending:C,settle:F,reset(){u=null,g=null,r.close=null,o=!1,r.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Q({...e,session:void 0,...e.serverKey?{fetch:(i,s)=>{let m=new Headers(s?.headers),v=typeof s?.body=="string"?JSON.parse(s.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||m.set(tn,e.serverKey),(e.fetch??globalThis.fetch)(i,{...s,headers:m})}}:{},...e.session?{fetch:async(i,s)=>{let m=await e.session.access(),v=typeof s?.body=="string"?JSON.parse(s.body):{};if(!v||typeof v!="object"||Array.isArray(v))throw new l("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(i,{...s,body:JSON.stringify({...v,customerToken:m})})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let t=vn(e.funnelId),f=e.session?.subscribeIdentity(()=>{t.reset(),n.reset()}),u=null,g=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),c=g&&In(g),r=Rn({options:e,journal:c,state:t,call:o});async function o(i,s,m){let v=t.generation,S=()=>t.assertCurrent(v);c&&await r.ready,S();let R=t.view,P=we.parse(await he(e,await n.request("funnels",H.parse(i))));if(i.operation==="review"&&!P.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(S(),P.runToken&&P.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let T=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(T&&P.settlement?.requestId!==T)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(P),t.assertRun(P.run);let O=r.observePurchase(i,P,v,m);if(O&&await O,!P.run.stopped&&["running","waiting"].includes(P.run.status)&&i.operation==="get"&&i.settlementRequestId)return P;let k=s?.(P),G=typeof k=="boolean"?k:k?await k:!1;return S(),["running","waiting"].includes(P.run.status)||r.stop(),t.publish(i,P,R,m,G),P}let a=r.submit,w=null,d=new WeakMap;function C(i){let s=d.get(i);if(s)return s;let m=E(i);return d.set(i,m),m}let _=!1;async function E(i){let s=await i;if(s.run.instruction?.type!=="evaluate_segment")return s;if(w)return w;_=!0;let m=t.generation,v=(async()=>{for(let S=0;S<32&&s.run.instruction?.type==="evaluate_segment";S++){if(r.pending||r.closeRequested)return s;let R=s.run;if(s.run.instruction?.type==="evaluate_segment"){let{advance:T}=await Ne(e.configuration,R,{predict:!1});if(m!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return s;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return o({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});let O=!0;Ne(e.configuration,R).then(({prediction:k})=>{O&&m===t.generation&&!r.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(u=k)}).catch(()=>{});try{s=await a({operation:"commit_segment",requestId:en(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...T})}finally{O=!1,u=null}}}return s})();w=v;try{return await v}finally{w===v&&(w=null)}}let F={get configuration(){return _?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let i=r.closing??r.pending;return i?structuredClone(Y(i)):null},get pendingCommands(){return[r.pending,r.closing].filter(i=>i!==null).map(i=>structuredClone(Y(i)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get prediction(){let i=t.view;return u&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===u.runId&&i.nodeId===u.from.nodeId&&i.visit===u.from.visit&&i.revision===u.from.revision&&!r.closeRequested?structuredClone(u):null},settle:r.settle,get webViewUrl(){return"bundled"},resolvePaywall(i){return ve(e,i)},async pageExperiments(i,s=[]){let m=t.generation;t.assertCurrent(m);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let S=cn.parse(await n.request("funnels",ln.parse({operation:"page_experiments",release:i,usedReceiptIds:s,...t.customerToken?{customerToken:t.customerToken}:{}})));if(t.assertCurrent(m),S.runId!==v||S.scope.projectId!==e.scope?.projectId||S.scope.environment!==e.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return S},review(i){return o({operation:"review",...i?{receiptId:i}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(i,s){c&&await r.ready,s??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let m=t.nextRead();return C(o({operation:"get",...i?{data:i}:{},...s?{purchase:s}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,m))},resume(i=t.view?.pendingRequest?.requestId){return i?r.closeRequested?F.settle(i):r.pending?.requestId===i?C(a(r.pending)):C(a({operation:"resume",requestId:i})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(i){return C(a(i))},retry(){return r.closeFlight?r.closeFlight:r.closing?r.executePending(r.closing):r.closeRequested&&r.pending?F.settle(r.pending.requestId):r.inFlight?C(r.inFlight):r.pending?C(a(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(i){t.identify(i),u=null,n.identify(e.runToken)},subscribe:t.subscribe,reset(){f?.(),t.reset(),r.reset(),u=null,n.reset()}};return F}import{ZodError as Dn}from"zod";function Sn(e,n,t,f){try{return e.parse(n)}catch(u){throw f&&u instanceof Dn?new l(t,f):u}}async function Pe(e,n,t,f={},u){let g=typeof f=="function"?{}:f,c=Sn(n.request,t,"INVALID_REQUEST",g.request),r=await e(n.path,c,n.method,u),o=typeof f=="function"?f:f.parseResponse;return o?o(n.response,r):Sn(n.response,r,"INVALID_RESPONSE",g.response)}async function Kt(e,n){if(!ie.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let t=Q(e);if(!e.session)t.identify(n.customerToken);else if(e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let f=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),u=null,g=!1,c=null,r=null,o=null,a=null,w=e.session?.subscribeIdentity(()=>{g=!0,t.dispose(),u=null,c=null,r=null,o=null});async function d(){if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");let E=ne.resolvePaywall,F=await Pe(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),i={paywall:await ve(e,F.paywall)};if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?i.paywall.id!==n.paywallVersionId:i.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!dn(i.paywall,u)||i.paywall.paywallId!==u.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=i.paywall,structuredClone(u)}async function C(E){if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let F=E==="read"?ne.readSubscriptionOperation:ne.attach,i=await Pe(t.request,F,{operationId:c.operationId,...E==="read"?{}:{intent:E}});return mn(i.operation,{operationId:c.operationId,currency:f.commerce.currency},"The purchase operation changed"),r=pn(r,i.operation),structuredClone(r)}let _={get view(){return u?structuredClone(u):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},refresh:d,async preview(E){if(!u)throw new l("INVALID_REQUEST","Load the Paywall first");let F=u.document.buttons[E.actionId];if(F?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let i=Ge(F.product,E.selection,u.capabilities);if(!i)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let s=He(u.document.screen,i,E.selection,u.capabilities),m=ne.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:i,...Object.keys(s).length?{featureQuantities:s}:{}}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),v=JSON.stringify(m);if(o&&o!==v&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===v){if(a)return a;if(c)return structuredClone(c)}o=v;let S=(async()=>{let R=ne.previewAttach,P=await Pe(t.request,R,m);return fn(P.quote,{productVersionId:i,featureQuantities:s,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=P.quote,r=null,structuredClone(c)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>C("confirm"),cancel:()=>C("cancel"),read:()=>C("read"),destroy(){w?.(),g=!0,t.dispose(),u=null,c=null,r=null,o=null}};return await d(),_}import{z as kn}from"zod";import{z as ce}from"zod";var xn=ce.record(ce.string().regex(/^[a-f0-9]{64}$/),ce.strictObject({at:ce.number(),text:ce.string()})),bn=2*1048576,Ln=100;function Vn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Cn(e,n){let t=n===void 0?Vn():n,f=Promise.resolve();async function u(c){if(!t)return null;let r;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(c)),new Promise(o=>{r=setTimeout(()=>o(null),Ln)})])}catch{return null}finally{clearTimeout(r)}}async function g(){try{let c=await u(`${e}:artifacts`);if(c&&c.length<=bn)return xn.parse(JSON.parse(c))}catch{}return{}}return{async readManifest(){return u(e)},writeManifest(c){Promise.resolve().then(()=>t?.setItem(e,c)).catch(()=>{})},async readArtifact(c){let r=(await g())[c];return r&&Date.now()>=r.at&&Date.now()-r.at<=q.retentionMs?r.text:void 0},writeArtifact(c,r){t&&(f=f.catch(()=>{}).then(async()=>{let o=await g(),a=Date.now();o[c]={at:a,text:r};let w={},d=2,C=0;for(let[_,E]of Object.entries(o).sort(([,F],[,i])=>i.at-F.at)){if(E.at>a||a-E.at>q.retentionMs)continue;let F=new TextEncoder().encode(JSON.stringify({[_]:E})).byteLength;d+F>bn||C>=128||(w[_]=E,d+=F,C++)}await t.setItem(`${e}:artifacts`,JSON.stringify(w))}).catch(()=>{}))}}}var b=(e,n)=>new l(e,n),$=()=>performance.now(),En=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function ir(e){let n=Ke.parse(e.scope),t=new te(e.origin??ae);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(e.assetOrigins??[]).map(y=>{let p=new te(y);if(p.protocol!=="https:"||p.username||p.password||p.search||p.hash||p.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return p.origin})]),u=e.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${n.environmentId}`,c=`indiana:configuration:1:${t.origin}:${L(n)}`,r=Cn(c,e.storage),o,a=0,w=0,d=!1,C=!1,_=0,E=0,F,i,s,m,v=0,S=new Set,R=new Set,P=new Map,T=new Map,O=0,k=!1;function G(){for(let y of S)try{y()}catch{}}function W(y){try{e.onError?.(y)}catch{}}let J=()=>!C&&!d&&!!o&&$()<a&&Date.now()<w;function Z(){if(!J())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Te(y,p){let h=new TextEncoder().encode(p).byteLength;if(!P.has(y)){for(;P.size&&(P.size>=128||O+h>q.maxCacheBytes);){let I=P.entries().next().value;O-=new TextEncoder().encode(I[1]).byteLength,P.delete(I[0])}P.set(y,p),O+=h}}function Oe(y,p,h){return yn(y,p,{signal:h,error:I=>b("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _e(y){let p=new te(y,t);if(!f.has(p.origin)||p.username||p.password||p.hash||p.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return p.href}async function Se(y,p,h=!1){let I=await u(_e(y),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:p,headers:{}});if(I.status===429){let A=I.headers.get("retry-after")??"";v=/^\d+$/.test(A)?Number(A)*1e3:Math.max(0,Date.parse(A)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw b(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Fn(y,p,h){let I=Date.parse(y.headers.get("x-indiana-config-validated-at")??""),A=Date.parse(y.headers.get("x-indiana-config-valid-until")??""),D=Date.parse(y.headers.get("date")??""),N=y.headers.get("age"),U=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,A,D,U].every(Number.isFinite)||A<=I||A-I>q.maxControlAgeMs||I>D+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(A-I,h.maxControlAgeSeconds*1e3,q.maxControlAgeMs)-Math.max(U,D-I,0)-($()-p);if(x<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return $()+x}function be(){if(clearTimeout(s),clearTimeout(m),C||!S.size)return;J()&&(m=setTimeout(()=>{J()?be():G()},Math.max(1,a-$())),En(m));let y=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{oe().catch(W)},Math.max(v,y*(.8+Math.random()*.2))),En(s)}async function oe(){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let y=_,p=new AbortController;i=p;let h=(async()=>{if(!k){k=!0;try{let pe=await r.readManifest();if(pe&&!o){let j=Ee.parse(JSON.parse(pe));L(j.scope)===L(n)&&(o=j)}}catch{}}p.signal.throwIfAborted();let N=o,U=$(),V=await Se(g,p.signal);V.status===304&&(!N||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await Se(g,p.signal));let x=V.status===304?N:Ee.parse(JSON.parse(await Oe(V,q.maxManifestBytes,p.signal))),{generation:z,...K}=x,X=V.headers.get("etag");if(L(x.scope)!==L(n)||Ye(K)!==z||X!==`"${z}"`&&X!==`W/"${z}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[pe,j]of Object.entries(N?.funnels??{})){let ee=x.funnels[pe];if(ee&&(ee.controlRevision<j.controlRevision||ee.evaluationRevision<j.evaluationRevision||ee.controlRevision===j.controlRevision&&ee.state!==j.state||ee.evaluationRevision===j.evaluationRevision&&ee.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let ke=Fn(V,U,x.policy);if(p.signal.throwIfAborted(),y!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return o=x,a=ke,w=Date.now()+Math.max(0,ke-$()),d=!1,E=0,v=0,r.writeManifest(L(x)),G(),structuredClone(x)})(),I=setTimeout(()=>p.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs),A=new Promise((N,U)=>p.signal.addEventListener("abort",()=>U(p.signal.reason),{once:!0})),D=Promise.race([h,A]).catch(N=>{throw E++,(N instanceof kn.ZodError||N instanceof SyntaxError||N instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,d=!0,G()),N}).finally(()=>{clearTimeout(I),F===D&&(F=void 0),be()});return F=D,D}async function de(y){let p=y.sha256,h=z=>Ie(z,y);_e(y.url);let I=P.get(p);if(I&&h(I))return P.delete(p),P.set(p,I),I;if(T.has(p))return T.get(p);let A=new AbortController;R.add(A);let D=_,N=(async()=>{try{let X=await r.readArtifact(p);if(X&&h(X))return Te(p,X),X}catch{}A.signal.throwIfAborted();let z=await Se(y.url,A.signal,!0),K=await Oe(z,y.byteLength,A.signal);if(!h(K))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(C||D!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Te(p,K),r.writeArtifact(p,K),K})(),U=setTimeout(()=>A.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),q.initializationMs),V=new Promise((z,K)=>A.signal.addEventListener("abort",()=>K(A.signal.reason),{once:!0})),x=Promise.race([N,V]).finally(()=>{clearTimeout(U),R.delete(A),T.delete(p)});return T.set(p,x),x}async function me(){return J()||await oe(),Z(),o}async function ue(y){let p,h=new Promise((I,A)=>{p=setTimeout(()=>A(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs)});try{return await Promise.race([y(),h])}finally{clearTimeout(p)}}function le(y,p){if(Z(),o?.generation!==y.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(p&&o.funnels[p]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function De(y){let p=y.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Be.parse(JSON.parse(await de(h)));if(L(I.scope)!==L({projectId:n.projectId,environment:n.environment})||I.generation!==h.generation||I.remoteFeatures.some(A=>Object.hasOwn(I.features,A)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return le(y),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-$())).toISOString()}}async function xe(y,p){let h=await me(),I=h.funnels[y];p&&(!I||I.evaluationMode==="local"&&!I.versions[p])&&(F&&await F,h=await oe()),le(h,y);let A=h.funnels[y];if(A.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let D=p??A.currentVersionId,N=A.versions[D];if(!N)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[N.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[U,V]=await Promise.all([de(h.artifacts[N.artifact]).then(x=>We(JSON.parse(x))),A.evaluationMode==="local"?De(h):void 0]);if(V&&L($e(U,V))!==L(N.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return le(h,y),{document:U,growth:V,versionId:D,control:structuredClone(A),manifest:structuredClone(h)}}async function Le(y,p){try{return await xe(y,p)}catch(h){if(!(h instanceof l)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&J()))throw h;let I=o?.generation;if(F&&await F,await oe(),h.code!=="CONFIGURATION_CHANGED"&&o?.generation===I)throw h;return xe(y,p)}}function Ce(){d=!0,G(),oe().catch(W)}let fe=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Nn(y){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(y),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),be()),()=>{S.delete(y),S.size||(clearTimeout(s),clearTimeout(m),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:oe,subscribe:Nn,assertFresh:Z,assertFeatures(y){Z();let p=o.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(y!==void 0&&o.artifacts[p].generation!==y)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return J()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return J()?Math.max(0,a-$()):0},async features(){return ue(async()=>De(await me()))},pageExperiments:()=>ue(async()=>{let y=await me(),p=y.gb.pageExperiments;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=an.parse(JSON.parse(await de(h)));if(I.environmentId!==n.environmentId||I.generation!==h.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return le(y),I}),funnel:(y,p)=>ue(()=>Le(y,p)),paywall:(y,p)=>ue(async()=>{let h=await me(),I=h.paywalls?.[y];if(!I||!p&&I.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let A=p??I.currentVersionId,D=I.versions[A],N=D&&h.artifacts[D.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let U=ze.parse(JSON.parse(await de(N)));return le(h),{document:U,versionId:A,version:D.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(y,p){let h=await ue(()=>Le(y,p));if(!h.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:A,...D}=h.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:y,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:D})},assertFunnel(y,p,h){Z();let I=o.funnels[y];if(!I||I.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Indiana");if(p!==void 0&&I.controlRevision!==p)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!C){C=!0,_++,a=0,i?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(m),Ve(),G(),S.clear();for(let y of R)y.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),O=0}}}}function An(e){let n=ie.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let t=Q({...e,timeoutMs:e.timeoutMs??35e3});return e.session||t.identify(e.apiKey),{async start(f){let u=H.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(n?u.data.customer!==void 0:u.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let g=u.data,c=we.safeParse(await he(e,await t.request("funnels",g)));if(!c.success||!c.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let r=c.data;if(r.run.source.id!==g.funnelId||r.run.locale!==(g.locale??"en")||!se(r.run.parameters,g.parameters??{})||(g.customer?!r.customerId||g.customer.type==="id"&&r.customerId!==g.customer.value:r.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...r,runToken:r.runToken}}}}async function hr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(t)!==L(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=re.test(e.credential);if(u?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=An({...e,scope:t,apiKey:e.credential}),c=r=>{let o=Pn({...e,scope:t,runToken:r,...u?{serverKey:e.credential}:{}});return u||o.identify(e.credential),o};return{async start(r){let o=await g.start({...r,funnelId:e.funnelId,...u?{customer:{type:"id",value:e.customerId}}:{}}),a=c(o.runToken),w=await a.get();return{...o,...w,controller:a}},async restore(r){let o=c(r),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:r,controller:o}}}}export{Pe as a,Un as b,he as c,Fe as d,rt as e,On as f,gn as g,ft as h,se as i,vt as j,Rt as k,Pn as l,Kt as m,ir as n,An as o,hr as p};
1
+ import{b as dn,c as mn,d as fn,e as pn}from"./chunk-SBPTOOYB.js";import{$ as Ke,Aa as rn,Ba as on,Ea as an,Fa as sn,Ia as un,M as Ge,Na as ln,O as Je,Oa as cn,P as Be,Pa as te,Q as je,Qa as Q,Y as H,Z as ze,_ as q,aa as Ee,ba as L,ca as Qe,da as Ye,ea as $e,fa as We,ga as Ze,ha as Xe,j as ie,na as ne,oa as en,qa as we,ra as nn,sa as tn}from"./chunk-Q64VNSPV.js";import{oa as He,qa as l}from"./chunk-ACF2FBUB.js";import{a as Me,e as ye}from"./chunk-G56XGVMS.js";import{b as ae}from"./chunk-GHJ65ILJ.js";import{b as ge}from"./chunk-7DXL3LHT.js";import{e as Ue,h as qe}from"./chunk-3PZ4Y6UD.js";function Un(e){let n=null,t=null,f=0,u=0,g=!1,c=new Set,r=null,o=null,a=new Set,w=()=>{for(let m of a)try{m()}catch{}},d={attributes:ge.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(m,v)=>{!c.has(m)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(m,structuredClone(v),structuredClone(d.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(m,v)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(m),structuredClone(v),structuredClone(d.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?m=>e.saveStickyBucketAssignmentDoc(structuredClone(m)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},C=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function _(m,v=new Set){return c.has(m)?!r||!r.features[m]||["unknownFeature","cyclicPrerequisite"].includes(r.features[m].source):v.has(m)?!1:(v.add(m),(n?.features[m]?.rules??[]).some(S=>[...S.parentConditions??[],...(S.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>_(R.id,v))))}let E=m=>{if(e.assertUsable?.(n?.generation),!n)throw new Error("Initialize the Feature client before evaluation");if(n.expiresAt&&Date.parse(n.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return r?.expiresAt&&Date.parse(r.expiresAt)<=Date.now()&&(r=null,d.features=n.features),c.has(m)?!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now()?C():structuredClone(r.features[m]??C()):e.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!g||_(m)?C():structuredClone(qe(m,d))};async function F(){if(!n||!c.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(c.size)throw new Error("Remote Feature evaluation requires a server loader");return}let m=u;if(o?.revision===m)return o.loading;let v=f,S=n,R=[...c],P=(async()=>{let T=je.parse(await e.evaluateRemote({attributes:structuredClone(d.attributes),features:R}));if(!(v!==f||m!==u||S!==n)){if(e.assertUsable?.(S.generation),T.generation!==S.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(O=>!Object.hasOwn(T.features,O))||Object.keys(T.features).some(O=>!c.has(O)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!T.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=ge.parse({...d.attributes,...T.merchandiseContext}),g=!0}r=structuredClone(T),d.features={...S.features,...Object.fromEntries(Object.entries(r.features).map(([O,k])=>[O,{defaultValue:k.value}]))},w()}})();o={revision:m,loading:P};try{await P}finally{o?.loading===P&&(o=null)}}function i(){F().catch(m=>{try{e.onError?.(m)}catch{}})}async function s(){if(t)return t;let m=f,v=(async()=>{let S=await e.load(),R="remoteFeatures"in S?Je.parse(S):null,P=R??ye.parse(S);if(P.scope.projectId!==e.scope.projectId||P.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(m!==f)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===P.generation){let{evaluatedAt:O,expiresAt:k,...G}=n,{evaluatedAt:W,expiresAt:J,...Z}=P;if(L(G)!==L(Z))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=P.evaluatedAt,n.expiresAt=P.expiresAt,w(),(!r||r.expiresAt&&Date.parse(r.expiresAt)<=Date.now())&&i(),structuredClone(n)}let T=new Set(R?.remoteFeatures??[]);if([...T].some(O=>Object.hasOwn(P.features,O)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in P&&!n.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),n=structuredClone(P),c=T,r=null,o=null,u++,d.features=n.features,d.savedGroups=Ue(n.savedGroups),d.trackedFeatureUsage={},w(),i(),structuredClone(n)})();t=v;try{return await v}finally{t===v&&(t=null)}}return{init:s,refresh:s,refreshRemote:F,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(m){return a.add(m),()=>{a.delete(m)}},setAttributes(m){let v=ge.parse(m);(d.attributes?.merchandise||d.attributes?.merchandiseId||m.merchandise||m.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=v,u++,g=!1,r=null,o=null,d.features=n?.features??{},d.trackedFeatureUsage={},w(),i()},evalFeature:E,isOn(m){return E(m).on},isOff(m){return E(m).off},getFeatureValue(m,v){let S=E(m).value;return structuredClone(S===null?v:S)},reset(){f++,u++,t=null,o=null,n=null,r=null,c.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),w()}}}function gn(e){let n,t,f=()=>new l("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),u=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw f();let r=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??ae).href,e.runToken])),o=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return"indiana.funnel.commands.v1."+Array.from(o,a=>a.toString(16).padStart(2,"0")).join("")});u.catch(()=>{});async function g(r){try{let o=await u;return await t.request(o,{mode:"exclusive"},()=>r(o))}catch(o){throw o instanceof l?o:f()}}function c(r){let o=n.getItem(r);if(o===null)return{revision:0,entry:null};if(o.length>1048576)throw f();let a=JSON.parse(o);if(!a||typeof a!="object"||!("revision"in a)||!("entry"in a)||!Number.isSafeInteger(a.revision)||Number(a.revision)<0)throw f();return{revision:Number(a.revision),entry:a.entry}}return{read:()=>g(c),write:(r,o)=>g(a=>{if(c(a).revision!==r)return null;if(!Number.isSafeInteger(r+1))throw f();return n.setItem(a,JSON.stringify({revision:r+1,entry:o})),r+1})}}async function he(e,n){let t=nn.safeParse(n);if(!t.success)throw new l("INVALID_RESPONSE","Funnel response contract changed");let f=t.data;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Funnel scope changed");return f}async function Ae(e,n,t){if(Number(e.headers.get("content-length"))>n)throw t.error("limit");let f=e.body?.getReader();if(!f)throw t.error("missing");let u=[],g=0;try{for(;;){t.signal?.throwIfAborted();let o=await f.read();if(o.done)break;if(g+=o.value.length,g>n)throw t.error("limit");u.push(o.value)}}finally{await f.cancel().catch(()=>{})}t.signal?.throwIfAborted();let c=new Uint8Array(g),r=0;for(let o of u)c.set(o,r),r+=o.length;return c}async function yn(e,n,t){return new TextDecoder("utf-8",{fatal:!0}).decode(await Ae(e,n,t))}function Ie(e,n){let t=typeof e=="string"?new TextEncoder().encode(e):e;return t.byteLength===n.byteLength&&Qe(t)===n.sha256}async function ve(e,n){let t=Ze.parse(n),{artifact:f,environmentId:u}=t.content,g=new te(e.baseUrl??ae).origin,c=new te(f.url,g);if(c.origin!==g||c.username||c.password||c.search||c.hash||c.pathname!==`/api/v1/configuration/${u}/artifacts/${f.sha256}`)throw new l("INVALID_RESPONSE","Public Paywall locator is not trusted");let r=new AbortController,o=setTimeout(()=>r.abort(),q.initializationMs);try{let a=await(e.fetch??globalThis.fetch)(c,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:r.signal});if(!a.ok||!a.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(a.headers.get("content-length"))>f.byteLength)throw new l("INVALID_RESPONSE","Public Paywall is unavailable");let w=await Ae(a,f.byteLength,{signal:r.signal,error:d=>new l("INVALID_RESPONSE",d==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ie(w,f))throw new l("INVALID_RESPONSE","Public Paywall digest or size changed");return Xe(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(w)))}finally{clearTimeout(o)}}var Fe=(e,n)=>new l(e,n);function rt(e){return sn(e,Fe)}async function Ne(e,n,{predict:t=!0}={}){let f=n.instruction;if(f?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new l("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==f.environmentId)throw new l("SCOPE_MISMATCH","Evaluation environment changed");let u=null,g;if(t)try{let c=await e.funnel(n.source.id,n.source.versionId);g=c.manifest.generation,u=Tn(e,n,c)}catch{u=null}return g??=e.snapshot?.generation??(await e.refresh()).generation,{advance:{policyRevision:f.policyRevision,generation:g},prediction:u}}function Tn(e,n,t){let f=n.instruction;if(f?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==f.policyRevision)return null;let{analyticsConfig:u,remoteFeatures:g,...c}=t.growth,r=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:f.policyRevision,document:t.document,payload:ye.parse(c)}),o=On(r,t.document,{...n,...f}),a=o.steps.at(-1),w=o.boundary??(a?.result.port==="value"?{nodeId:a.nodeId,visit:n.visit+o.steps.length-1}:null);return w?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:w.nodeId,visit:w.visit,terminal:!o.boundary}:null}function On(e,n,t){return un(e,n,t,Fe)}import{z as B}from"zod";var wn=H.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),hn=B.strictObject({schemaVersion:B.literal(1),scope:Me,runId:B.uuid(),funnelId:B.uuid(),versionId:B.uuid(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:B.strictObject({receiptId:B.uuid(),operationId:B.uuid(),generation:B.number().int().nonnegative()}).optional(),closed:B.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),M=()=>new l("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Re=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function In(e){let n=0,t=null,f=o=>JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]),u=Promise.resolve();async function g(){let o=await e.read();if(!Number.isSafeInteger(o.revision)||o.revision<0)throw new l("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:o.revision,entry:o.entry===null?null:hn.parse(o.entry)}}function c(o){let a=u.then(o);return u=a.catch(()=>{}),a}async function r(o){for(let a=0;a<4;a++){let w=await g();if(w.entry&&t!==null&&f(w.entry)!==t)throw M();let d=o(w.entry,w.revision);if(Re(w.entry,d)){n=w.revision;return}let C=await e.write(w.revision,d);if(C!==null){if(!Number.isSafeInteger(C)||C<=w.revision)throw M();n=C;return}}throw M()}return{bind(o){let a=JSON.stringify([o.scope,o.runId,o.funnelId,o.versionId]);if(t!==null&&t!==a)throw M();t=a},async load(){let o=await g();return n=o.revision,t=o.entry?f(o.entry):null,o.entry},retain(o){let a=hn.parse(o),w=a.command;return!w||t!==null&&f(a)!==t?Promise.reject(M()):(t??=f(a),c(()=>r((d,C)=>{if(d&&!Re(f(d),f(a)))throw M();if(!d){if(C!==n&&w.operation!=="close")throw M();return a}if(!d.command)return{...d,command:w,...w.operation==="close"?{closed:!0}:{}};if(w.operation==="close"&&d.command.operation!=="close"){if(d.command.requestId===w.requestId||d.closeCommand&&!Re(d.closeCommand,w))throw M();return{...d,closeCommand:w,closed:!0}}if(!Re(d.command,w))throw M();return d})))},observePurchase(o,a,w){return c(()=>r((d,C)=>{if(!d&&C!==n||d&&f(d)!==f({...o,schemaVersion:1}))throw M();if(d?.purchase&&d.purchase.generation>a.generation)return d;if(d?.purchase&&d.purchase.generation===a.generation&&d.purchase.operationId!==a.operationId)throw M();return w?!d?.purchase||d.purchase.operationId!==a.operationId?d:d.command?{...d,purchase:void 0}:null:{schemaVersion:1,...o,...d,purchase:a}}))},settle(o){return c(()=>r(a=>a?a.command&&"requestId"in a.command&&a.command.requestId===o?a.closeCommand?{...a,command:a.closeCommand,closeCommand:void 0}:a.purchase?{...a,command:void 0}:null:a.closeCommand&&"requestId"in a.closeCommand&&a.closeCommand.requestId===o?{...a,closeCommand:void 0}:a:null))}}}function ft(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function se(e,n){if(e===n)return!0;if(Array.isArray(e)||Array.isArray(n))return Array.isArray(e)&&Array.isArray(n)&&e.length===n.length&&e.every((u,g)=>se(u,n[g]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),f=Object.entries(n);return t.length===f.length&&t.every(([u,g])=>Object.hasOwn(n,u)&&se(g,Reflect.get(n,u)))}function vn(e){let n=null,t=0,f=!1,u,g=0,c=new Set;return{get view(){return n},get generation(){return t},get disposed(){return f},get customerToken(){return u},get readSequence(){return g},nextRead(){return++g},assertCurrent(r,o="Run identity changed during the request"){if(r!==t||f)throw new l("IDENTITY_CHANGED",o)},assertRun(r){if(n&&(r.id!==n.id||r.source.type!==n.source.type||r.source.id!==n.source.id||r.source.versionId!==n.source.versionId||r.locale!==n.locale||!se(r.parameters,n.parameters)))throw new l("INVALID_RESPONSE","Run version changed");if(e&&r.source.id!==e)throw new l("INVALID_RESPONSE","Run belongs to another Funnel")},publish(r,o,a,w,d){if(!(r.operation==="review"&&n&&n!==a&&o.run.revision<=n.revision)&&!(n&&o.run.revision===n.revision&&w!==void 0&&w<g)&&(r.operation==="review"&&!o.run.stopped&&["running","waiting"].includes(o.run.status)&&n&&o.run.nodeId===n.nodeId&&o.run.visit===n.visit&&o.run.revision===n.revision&&(o.run.screen=n.screen,(n.paywall?.quote?.operationId===o.review?.activeOperationId||!n.paywall?.quote&&o.review?.activeOperationId===null)&&(o.run.paywall=n.paywall)),!(n?.paywall&&o.run.paywall&&n.paywall.receiptId===o.run.paywall.receiptId&&(o.run.paywall.selectionGeneration??0)<(n.paywall.selectionGeneration??0)))){if(!n||o.run.revision>=n.revision)n=o.run;else if(!d)return;if(n)for(let C of c)try{C(structuredClone(n))}catch{}}},identify(r){if(!ie.test(r))throw new l("INVALID_TOKEN","Customer credential required");t++,u=r},subscribe(r){return c.add(r),()=>c.delete(r)},reset(){f=!0,t++,u=void 0,n=null,c.clear()}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function vt(e,n,t="A server API key is required"){if(typeof window<"u")throw new l("SERVER_ONLY",n);if(!re.test(e))throw new l("INVALID_TOKEN",t)}function Rt(e){let n=Q(e);return n.identify(e.apiKey),n}function Y(e){let{customerToken:n,...t}=e;return t}var _n=e=>!(e instanceof l)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Rn({options:e,journal:n,state:t,call:f}){let u=null,g=null,c=!1,r={command:null,close:null},o=!1,a,w=null,d=n?n.load().then(i=>{if(t.disposed)throw new l("IDENTITY_CHANGED","Controller was reset during command restoration");if(w=i,!i)return;if(e.scope&&(i.scope.projectId!==e.scope.projectId||i.scope.environment!==e.scope.environment))throw new l("SCOPE_MISMATCH","Pending command belongs to another scope");if(a=i.purchase,c=i.closed===!0,!i.command)return;let s=H.parse(i.command);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("COMMAND_STORAGE_INVALID","Stored mutation required");u=s,i.closeCommand&&(g=i.closeCommand,c=!0),s.operation==="close"&&(c=!0),o=!0}):Promise.resolve();d.catch(()=>{});async function C(i=u){if(n&&await d,!i)throw new l("INVALID_REQUEST","No command is pending");let s=i,m=t.generation;if(n){if(!t.view||!e.scope)throw new l("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await n.retain({schemaVersion:1,scope:e.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:Y(s)})}if(m!==t.generation||u!==s&&g!==s)throw new l("IDENTITY_CHANGED","Run changed before command dispatch");let v={...s,...t.customerToken?{customerToken:t.customerToken}:{}},S=o;o=!0;try{return await f(v,R=>{if(!R.settlement)throw new l("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==s.requestId)throw new l("INVALID_RESPONSE","Command settlement identity changed");if(m===t.generation&&(u===s||g===s)&&R.run.pendingRequest?.requestId!==s.requestId&&R.settlement.state==="settled"&&(!c||s.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let P=()=>m!==t.generation||u!==s&&g!==s?!1:(u===s&&(u=null),g===s&&(g=null),o=u!==null,w=null,!0);return n?n.settle(s.requestId).then(P):P()}return!1})}catch(R){throw m===t.generation&&u===s&&!S&&!_n(R)&&(n&&await n.settle(s.requestId),m===t.generation&&u===s&&(u=null,o=!1,w=null)),R}}function _(i){let s=H.parse(i);if(s.operation==="start"||s.operation==="get"||s.operation==="review")throw new l("INVALID_REQUEST","Mutation required");if(c&&s.operation!=="close"){if(u?.requestId===s.requestId)return F(s.requestId);throw new l("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(s.operation==="close"&&u?.operation!=="close"){if(c=!0,g&&JSON.stringify(Y(g))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original Close");return g??=s,r.close?r.close:E(g,"close")}if(u){if(JSON.stringify(Y(u))!==JSON.stringify(Y(s)))throw new l("COMMAND_PENDING","Retry the original command before sending another");if(r.command)return r.command}else u=s,o=!1;return E(u,"command")}function E(i,s){let m=C(i);r[s]=m;let v=()=>{r[s]===m&&(r[s]=null)};return m.then(v,v),m}async function F(i){let s=await f({operation:"get",settlementRequestId:i,...t.customerToken?{customerToken:t.customerToken}:{}});if(s.settlement?.requestId!==i)throw new l("INVALID_RESPONSE","Exact command settlement is missing");return s.settlement.state==="settled"&&(n&&await n.settle(i),u?.requestId===i&&(u=null,o=!1),g?.requestId===i&&(g=null)),s}return{ready:d,get pending(){return u},get closing(){return g},get closeRequested(){return c},get inFlight(){return r.command},get closeFlight(){return r.close},get purchase(){return a},assertBinding(i){if(w&&(i.run.id!==w.runId||i.run.source.id!==w.funnelId||i.run.source.versionId!==w.versionId))throw new l("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(i,s,m,v){n?.bind({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId}),n&&!e.scope&&(e.scope=s.scope);let S=s.run.paywall,R=S??s.purchase,P=R?.operation,T=s.settlement&&(!S||S.purchaseRequestId===s.settlement.requestId)&&(!a||a.operationId===s.settlement.operationId)?s.settlement:void 0,O=P?.operationId??R?.quote?.operationId??T?.operationId,k=R?.receiptId??T?.receiptId,G=S?.selectionGeneration??a?.generation??0;if(n&&O&&k&&i.operation!=="review"&&(!t.view||s.run.revision>=t.view.revision)&&(v===void 0||v>=t.readSequence)&&(!a||G>=a.generation)){let W={receiptId:k,operationId:O,generation:G},J=P?.status==="complete"||R?.canReselect===!0;return n.observePurchase({scope:s.scope,runId:s.run.id,funnelId:s.run.source.id,versionId:s.run.source.versionId},W,J).then(()=>{t.assertCurrent(m),J?a?.operationId===W.operationId&&(a=void 0):a=W})}},stop(){c=!0},submit:_,executePending:C,settle:F,reset(){u=null,g=null,r.close=null,o=!1,r.command=null}}}function Pn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new l("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new l("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new l("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Q({...e,session:void 0,...e.serverKey?{fetch:(i,s)=>{let m=new Headers(s?.headers),v=typeof s?.body=="string"?JSON.parse(s.body):null;return v!==null&&typeof v=="object"&&"customerToken"in v&&typeof v.customerToken=="string"&&v.customerToken.length>0||m.set(tn,e.serverKey),(e.fetch??globalThis.fetch)(i,{...s,headers:m})}}:{},...e.session?{fetch:async(i,s)=>{let m=await e.session.access(),v=typeof s?.body=="string"?JSON.parse(s.body):{};if(!v||typeof v!="object"||Array.isArray(v))throw new l("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(i,{...s,body:JSON.stringify({...v,customerToken:m})})}}:{},timeoutMs:e.timeoutMs??35e3});n.identify(e.runToken);let t=vn(e.funnelId),f=e.session?.subscribeIdentity(()=>{t.reset(),n.reset()}),u=null,g=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?gn(e):void 0),c=g&&In(g),r=Rn({options:e,journal:c,state:t,call:o});async function o(i,s,m){let v=t.generation,S=()=>t.assertCurrent(v);c&&await r.ready,S();let R=t.view,P=we.parse(await he(e,await n.request("funnels",H.parse(i))));if(i.operation==="review"&&!P.review)throw new l("INVALID_RESPONSE","Historical projection is missing");if(S(),P.runToken&&P.runToken!==e.runToken)throw new l("INVALID_RESPONSE","Run credential changed");let T=i.operation==="get"?i.settlementRequestId:"requestId"in i&&i.operation!=="start"?i.requestId:void 0;if(T&&P.settlement?.requestId!==T)throw new l("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");r.assertBinding(P),t.assertRun(P.run);let O=r.observePurchase(i,P,v,m);if(O&&await O,!P.run.stopped&&["running","waiting"].includes(P.run.status)&&i.operation==="get"&&i.settlementRequestId)return P;let k=s?.(P),G=typeof k=="boolean"?k:k?await k:!1;return S(),["running","waiting"].includes(P.run.status)||r.stop(),t.publish(i,P,R,m,G),P}let a=r.submit,w=null,d=new WeakMap;function C(i){let s=d.get(i);if(s)return s;let m=E(i);return d.set(i,m),m}let _=!1;async function E(i){let s=await i;if(s.run.instruction?.type!=="evaluate_segment")return s;if(w)return w;_=!0;let m=t.generation,v=(async()=>{for(let S=0;S<32&&s.run.instruction?.type==="evaluate_segment";S++){if(r.pending||r.closeRequested)return s;let R=s.run;if(s.run.instruction?.type==="evaluate_segment"){let{advance:T}=await Ne(e.configuration,R,{predict:!1});if(m!==t.generation)throw new l("IDENTITY_CHANGED","Run identity changed during segment calculation");if(r.pending||r.closeRequested)return s;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return o({operation:"get",...t.customerToken?{customerToken:t.customerToken}:{}});let O=!0;Ne(e.configuration,R).then(({prediction:k})=>{O&&m===t.generation&&!r.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(u=k)}).catch(()=>{});try{s=await a({operation:"commit_segment",requestId:en(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...T})}finally{O=!1,u=null}}}return s})();w=v;try{return await v}finally{w===v&&(w=null)}}let F={get configuration(){return _?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let i=r.closing??r.pending;return i?structuredClone(Y(i)):null},get pendingCommands(){return[r.pending,r.closing].filter(i=>i!==null).map(i=>structuredClone(Y(i)))},get pendingPurchase(){return r.purchase?structuredClone(r.purchase):null},get prediction(){let i=t.view;return u&&i&&!i.stopped&&["running","waiting"].includes(i.status)&&i.id===u.runId&&i.nodeId===u.from.nodeId&&i.visit===u.from.visit&&i.revision===u.from.revision&&!r.closeRequested?structuredClone(u):null},settle:r.settle,get webViewUrl(){return"bundled"},resolvePaywall(i){return ve(e,i)},async pageExperiments(i,s=[]){let m=t.generation;t.assertCurrent(m);let v=t.view?.id;if(!v)throw new l("INVALID_REQUEST","Read the Run before its page experiments");let S=cn.parse(await n.request("funnels",ln.parse({operation:"page_experiments",release:i,usedReceiptIds:s,...t.customerToken?{customerToken:t.customerToken}:{}})));if(t.assertCurrent(m),S.runId!==v||S.scope.projectId!==e.scope?.projectId||S.scope.environment!==e.scope?.environment)throw new l("SCOPE_MISMATCH","Page experiment Run changed");return S},review(i){return o({operation:"review",...i?{receiptId:i}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,t.nextRead())},async get(i,s){c&&await r.ready,s??=r.purchase&&{receiptId:r.purchase.receiptId,operationId:r.purchase.operationId};let m=t.nextRead();return C(o({operation:"get",...i?{data:i}:{},...s?{purchase:s}:{},...t.customerToken?{customerToken:t.customerToken}:{}},void 0,m))},resume(i=t.view?.pendingRequest?.requestId){return i?r.closeRequested?F.settle(i):r.pending?.requestId===i?C(a(r.pending)):C(a({operation:"resume",requestId:i})):Promise.reject(new l("INVALID_REQUEST","No interrupted command is available"))},submit(i){return C(a(i))},retry(){return r.closeFlight?r.closeFlight:r.closing?r.executePending(r.closing):r.closeRequested&&r.pending?F.settle(r.pending.requestId):r.inFlight?C(r.inFlight):r.pending?C(a(r.pending)):Promise.reject(new l("INVALID_REQUEST","No command is pending"))},identify(i){t.identify(i),u=null,n.identify(e.runToken)},subscribe:t.subscribe,reset(){f?.(),t.reset(),r.reset(),u=null,n.reset()}};return F}import{ZodError as Dn}from"zod";function Sn(e,n,t,f){try{return e.parse(n)}catch(u){throw f&&u instanceof Dn?new l(t,f):u}}async function Pe(e,n,t,f={},u){let g=typeof f=="function"?{}:f,c=Sn(n.request,t,"INVALID_REQUEST",g.request),r=await e(n.path,c,n.method,u),o=typeof f=="function"?f:f.parseResponse;return o?o(n.response,r):Sn(n.response,r,"INVALID_RESPONSE",g.response)}async function Kt(e,n){if(!ie.test(n.customerToken))throw new l("INVALID_TOKEN","A verified Customer credential is required");let t=Q(e);if(!e.session)t.identify(n.customerToken);else if(e.session.peek()!==n.customerToken)throw new l("SCOPE_MISMATCH","Paywall credential does not match the shared session");let f=ne.resolvePaywall.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,selector:n.paywallVersionId?{type:"version",versionId:n.paywallVersionId}:{type:"paywall",paywallId:n.paywallId},commerce:n.commerce,locale:n.locale,...n.requirement?{requirement:n.requirement}:{}}),u=null,g=!1,c=null,r=null,o=null,a=null,w=e.session?.subscribeIdentity(()=>{g=!0,t.dispose(),u=null,c=null,r=null,o=null});async function d(){if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");let E=ne.resolvePaywall,F=await Pe(t.request,E,{...f,selector:u?{type:"version",versionId:u.id}:f.selector}),i={paywall:await ve(e,F.paywall)};if(g)throw new l("IDENTITY_CHANGED","Paywall is closed");if(n.paywallVersionId?i.paywall.id!==n.paywallVersionId:i.paywall.paywallId!==n.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");if(u&&(!dn(i.paywall,u)||i.paywall.paywallId!==u.paywallId))throw new l("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return u=i.paywall,structuredClone(u)}async function C(E){if(!c)throw new l("INVALID_REQUEST","A quoted purchase is required");let F=E==="read"?ne.readSubscriptionOperation:ne.attach,i=await Pe(t.request,F,{operationId:c.operationId,...E==="read"?{}:{intent:E}});return mn(i.operation,{operationId:c.operationId,currency:f.commerce.currency},"The purchase operation changed"),r=pn(r,i.operation),structuredClone(r)}let _={get view(){return u?structuredClone(u):null},get quote(){return c?structuredClone(c):null},get operation(){return r?structuredClone(r):null},get webViewUrl(){return"bundled"},refresh:d,async preview(E){if(!u)throw new l("INVALID_REQUEST","Load the Paywall first");let F=u.document.buttons[E.actionId];if(F?.type!=="checkout")throw new l("INVALID_REQUEST","Choose an authored purchase action");let i=Ge(F.product,E.selection,u.capabilities);if(!i)throw new l("PRODUCT_UNAVAILABLE","Choose an available Product");let s=He(u.document.screen,i,E.selection,u.capabilities),m=ne.previewAttach.request.parse({funnelId:f.funnelId,funnelVersionId:f.funnelVersionId,requestId:E.requestId,plans:[{productVersionId:i,...Object.keys(s).length?{featureQuantities:s}:{}}],provider:f.commerce.provider,currency:f.commerce.currency,...E.offerId?{offerId:E.offerId}:{},...E.nativeOffer?{nativeOffer:E.nativeOffer}:{}}),v=JSON.stringify(m);if(o&&o!==v&&(!r||r.status==="pending"))throw new l("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(o===v){if(a)return a;if(c)return structuredClone(c)}o=v;let S=(async()=>{let R=ne.previewAttach,P=await Pe(t.request,R,m);return fn(P.quote,{productVersionId:i,featureQuantities:s,currency:f.commerce.currency,provider:f.commerce.provider},"The purchase quote changed its selected Product or presentment"),c=P.quote,r=null,structuredClone(c)})();a=S;try{return await S}finally{a===S&&(a=null)}},confirm:()=>C("confirm"),cancel:()=>C("cancel"),read:()=>C("read"),destroy(){w?.(),g=!0,t.dispose(),u=null,c=null,r=null,o=null}};return await d(),_}import{z as kn}from"zod";import{z as ce}from"zod";var xn=ce.record(ce.string().regex(/^[a-f0-9]{64}$/),ce.strictObject({at:ce.number(),text:ce.string()})),bn=2*1048576,Ln=100;function Vn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Cn(e,n){let t=n===void 0?Vn():n,f=Promise.resolve();async function u(c){if(!t)return null;let r;try{return await Promise.race([Promise.resolve().then(()=>t.getItem(c)),new Promise(o=>{r=setTimeout(()=>o(null),Ln)})])}catch{return null}finally{clearTimeout(r)}}async function g(){try{let c=await u(`${e}:artifacts`);if(c&&c.length<=bn)return xn.parse(JSON.parse(c))}catch{}return{}}return{async readManifest(){return u(e)},writeManifest(c){Promise.resolve().then(()=>t?.setItem(e,c)).catch(()=>{})},async readArtifact(c){let r=(await g())[c];return r&&Date.now()>=r.at&&Date.now()-r.at<=q.retentionMs?r.text:void 0},writeArtifact(c,r){t&&(f=f.catch(()=>{}).then(async()=>{let o=await g(),a=Date.now();o[c]={at:a,text:r};let w={},d=2,C=0;for(let[_,E]of Object.entries(o).sort(([,F],[,i])=>i.at-F.at)){if(E.at>a||a-E.at>q.retentionMs)continue;let F=new TextEncoder().encode(JSON.stringify({[_]:E})).byteLength;d+F>bn||C>=128||(w[_]=E,d+=F,C++)}await t.setItem(`${e}:artifacts`,JSON.stringify(w))}).catch(()=>{}))}}}var b=(e,n)=>new l(e,n),$=()=>performance.now(),En=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function ir(e){let n=Ke.parse(e.scope),t=new te(e.origin??ae);if(t.username||t.password||t.search||t.hash||t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(t.hostname)))throw b("INVALID_URL","Configuration requires a trusted HTTPS origin");let f=new Set([t.origin,...(e.assetOrigins??[]).map(y=>{let p=new te(y);if(p.protocol!=="https:"||p.username||p.password||p.search||p.hash||p.pathname!=="/")throw b("INVALID_URL","Invalid configuration asset origin");return p.origin})]),u=e.fetch??globalThis.fetch.bind(globalThis),g=`/api/v1/configuration/${n.environmentId}`,c=`indiana:configuration:1:${t.origin}:${L(n)}`,r=Cn(c,e.storage),o,a=0,w=0,d=!1,C=!1,_=0,E=0,F,i,s,m,v=0,S=new Set,R=new Set,P=new Map,T=new Map,O=0,k=!1;function G(){for(let y of S)try{y()}catch{}}function W(y){try{e.onError?.(y)}catch{}}let J=()=>!C&&!d&&!!o&&$()<a&&Date.now()<w;function Z(){if(!J())throw b("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Te(y,p){let h=new TextEncoder().encode(p).byteLength;if(!P.has(y)){for(;P.size&&(P.size>=128||O+h>q.maxCacheBytes);){let I=P.entries().next().value;O-=new TextEncoder().encode(I[1]).byteLength,P.delete(I[0])}P.set(y,p),O+=h}}function Oe(y,p,h){return yn(y,p,{signal:h,error:I=>b("INVALID_RESPONSE",I==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function _e(y){let p=new te(y,t);if(!f.has(p.origin)||p.username||p.password||p.hash||p.search)throw b("INVALID_URL","Configuration artifact origin is not trusted");return p.href}async function Se(y,p,h=!1){let I=await u(_e(y),{method:"GET",credentials:"omit",redirect:"error",cache:h?"default":"no-cache",signal:p,headers:{}});if(I.status===429){let A=I.headers.get("retry-after")??"";v=/^\d+$/.test(A)?Number(A)*1e3:Math.max(0,Date.parse(A)-Date.now())||15e3}if(!I.ok&&I.status!==304)throw b(`CONFIGURATION_HTTP_${I.status}`,"Configuration synchronization failed");return I}function Fn(y,p,h){let I=Date.parse(y.headers.get("x-indiana-config-validated-at")??""),A=Date.parse(y.headers.get("x-indiana-config-valid-until")??""),D=Date.parse(y.headers.get("date")??""),N=y.headers.get("age"),U=N!==null&&/^\d+(\.\d+)?$/.test(N)?Number(N)*1e3:NaN;if(![I,A,D,U].every(Number.isFinite)||A<=I||A-I>q.maxControlAgeMs||I>D+1e3)throw b("INVALID_RESPONSE","Configuration freshness evidence is invalid");let x=Math.min(A-I,h.maxControlAgeSeconds*1e3,q.maxControlAgeMs)-Math.max(U,D-I,0)-($()-p);if(x<=0)throw b("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return $()+x}function be(){if(clearTimeout(s),clearTimeout(m),C||!S.size)return;J()&&(m=setTimeout(()=>{J()?be():G()},Math.max(1,a-$())),En(m));let y=E?Math.min(15e3,1e3*2**Math.min(E-1,4)):Math.min(15e3,(o?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{oe().catch(W)},Math.max(v,y*(.8+Math.random()*.2))),En(s)}async function oe(){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(F)return F;let y=_,p=new AbortController;i=p;let h=(async()=>{if(!k){k=!0;try{let pe=await r.readManifest();if(pe&&!o){let j=Ee.parse(JSON.parse(pe));L(j.scope)===L(n)&&(o=j)}}catch{}}p.signal.throwIfAborted();let N=o,U=$(),V=await Se(g,p.signal);V.status===304&&(!N||!V.headers.has("x-indiana-config-validated-at")||!V.headers.has("x-indiana-config-valid-until")||!V.headers.has("age"))&&(V=await Se(g,p.signal));let x=V.status===304?N:Ee.parse(JSON.parse(await Oe(V,q.maxManifestBytes,p.signal))),{generation:z,...K}=x,X=V.headers.get("etag");if(L(x.scope)!==L(n)||Ye(K)!==z||X!==`"${z}"`&&X!==`W/"${z}"`)throw b("INVALID_RESPONSE","Configuration scope or content identity changed");if(N&&(x.revision<N.revision||x.revision===N.revision&&x.generation!==N.generation))throw b("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[pe,j]of Object.entries(N?.funnels??{})){let ee=x.funnels[pe];if(ee&&(ee.controlRevision<j.controlRevision||ee.evaluationRevision<j.evaluationRevision||ee.controlRevision===j.controlRevision&&ee.state!==j.state||ee.evaluationRevision===j.evaluationRevision&&ee.evaluationMode!==j.evaluationMode))throw b("INVALID_RESPONSE","Funnel control revision changed identity")}let ke=Fn(V,U,x.policy);if(p.signal.throwIfAborted(),y!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return o=x,a=ke,w=Date.now()+Math.max(0,ke-$()),d=!1,E=0,v=0,r.writeManifest(L(x)),G(),structuredClone(x)})(),I=setTimeout(()=>p.abort(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs),A=new Promise((N,U)=>p.signal.addEventListener("abort",()=>U(p.signal.reason),{once:!0})),D=Promise.race([h,A]).catch(N=>{throw E++,(N instanceof kn.ZodError||N instanceof SyntaxError||N instanceof l&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(N.code))&&(a=0,d=!0,G()),N}).finally(()=>{clearTimeout(I),F===D&&(F=void 0),be()});return F=D,D}async function de(y){let p=y.sha256,h=z=>Ie(z,y);_e(y.url);let I=P.get(p);if(I&&h(I))return P.delete(p),P.set(p,I),I;if(T.has(p))return T.get(p);let A=new AbortController;R.add(A);let D=_,N=(async()=>{try{let X=await r.readArtifact(p);if(X&&h(X))return Te(p,X),X}catch{}A.signal.throwIfAborted();let z=await Se(y.url,A.signal,!0),K=await Oe(z,y.byteLength,A.signal);if(!h(K))throw b("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(C||D!==_)throw b("CONFIGURATION_DISPOSED","Configuration scope changed");return Te(p,K),r.writeArtifact(p,K),K})(),U=setTimeout(()=>A.abort(b("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),q.initializationMs),V=new Promise((z,K)=>A.signal.addEventListener("abort",()=>K(A.signal.reason),{once:!0})),x=Promise.race([N,V]).finally(()=>{clearTimeout(U),R.delete(A),T.delete(p)});return T.set(p,x),x}async function me(){return J()||await oe(),Z(),o}async function ue(y){let p,h=new Promise((I,A)=>{p=setTimeout(()=>A(b("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),q.initializationMs)});try{return await Promise.race([y(),h])}finally{clearTimeout(p)}}function le(y,p){if(Z(),o?.generation!==y.generation)throw b("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(p&&o.funnels[p]?.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function De(y){let p=y.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let I=Be.parse(JSON.parse(await de(h)));if(L(I.scope)!==L({projectId:n.projectId,environment:n.environment})||I.generation!==h.generation||I.remoteFeatures.some(A=>Object.hasOwn(I.features,A)))throw b("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return le(y),{...I,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,a-$())).toISOString()}}async function xe(y,p){let h=await me(),I=h.funnels[y];p&&(!I||I.evaluationMode==="local"&&!I.versions[p])&&(F&&await F,h=await oe()),le(h,y);let A=h.funnels[y];if(A.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let D=p??A.currentVersionId,N=A.versions[D];if(!N)throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(h.artifacts[N.artifact].formatVersion!==3)throw b("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[U,V]=await Promise.all([de(h.artifacts[N.artifact]).then(x=>We(JSON.parse(x))),A.evaluationMode==="local"?De(h):void 0]);if(V&&L($e(U,V))!==L(N.dependencies))throw b("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return le(h,y),{document:U,growth:V,versionId:D,control:structuredClone(A),manifest:structuredClone(h)}}async function Le(y,p){try{return await xe(y,p)}catch(h){if(!(h instanceof l)||!(h.code==="CONFIGURATION_CHANGED"||h.code==="CONFIGURATION_HTTP_404"&&J()))throw h;let I=o?.generation;if(F&&await F,await oe(),h.code!=="CONFIGURATION_CHANGED"&&o?.generation===I)throw h;return xe(y,p)}}function Ce(){d=!0,G(),oe().catch(W)}let fe=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ce()};function Nn(y){if(C)throw b("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return S.add(y),S.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ce),window.addEventListener("focus",fe),document.addEventListener("visibilitychange",fe)),be()),()=>{S.delete(y),S.size||(clearTimeout(s),clearTimeout(m),Ve())}}function Ve(){typeof window<"u"&&(window.removeEventListener("online",Ce),window.removeEventListener("focus",fe),document.removeEventListener("visibilitychange",fe))}return{scope:Object.freeze({...n}),refresh:oe,subscribe:Nn,assertFresh:Z,assertFeatures(y){Z();let p=o.gb.features;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(y!==void 0&&o.artifacts[p].generation!==y)throw b("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return J()},get snapshot(){return o?structuredClone(o):null},get remainingMs(){return J()?Math.max(0,a-$()):0},async features(){return ue(async()=>De(await me()))},pageExperiments:()=>ue(async()=>{let y=await me(),p=y.gb.pageExperiments;if(!p)throw b("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let h=y.artifacts[p];if(h.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let I=an.parse(JSON.parse(await de(h)));if(I.environmentId!==n.environmentId||I.generation!==h.generation)throw b("INVALID_RESPONSE","Page experiment scope or generation changed");return le(y),I}),funnel:(y,p)=>ue(()=>Le(y,p)),paywall:(y,p)=>ue(async()=>{let h=await me(),I=h.paywalls?.[y];if(!I||!p&&I.state!=="published")throw b("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let A=p??I.currentVersionId,D=I.versions[A],N=D&&h.artifacts[D.artifact];if(!N||N.kind!=="paywall"||N.formatVersion!==1)throw b("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let U=ze.parse(JSON.parse(await de(N)));return le(h),{document:U,versionId:A,version:D.version,control:structuredClone(I),manifest:structuredClone(h)}}),async localFunnel(y,p){let h=await ue(()=>Le(y,p));if(!h.growth)throw b("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:I,remoteFeatures:A,...D}=h.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:y,versionId:h.versionId,evaluationMode:"local",evaluationRevision:h.control.evaluationRevision,document:h.document,payload:D})},assertFunnel(y,p,h){Z();let I=o.funnels[y];if(!I||I.state!=="active")throw b("FUNNEL_STOPPED","Funnel is paused or unavailable");if(I.evaluationMode!=="local")throw b("EVALUATION_MODE","This Funnel now executes at Longplay");if(p!==void 0&&I.controlRevision!==p)throw b("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(h!==void 0&&!I.versions[h])throw b("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!C){C=!0,_++,a=0,i?.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(m),Ve(),G(),S.clear();for(let y of R)y.abort(b("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));P.clear(),O=0}}}}function An(e){let n=ie.test(e.apiKey);if(typeof window<"u"&&!n)throw new l("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new l("INVALID_TOKEN","A customer credential or server API key is required");let t=Q({...e,timeoutMs:e.timeoutMs??35e3});return e.session||t.identify(e.apiKey),{async start(f){let u=H.safeParse({...f,operation:"start"});if(!u.success||u.data.operation!=="start"||(n?u.data.customer!==void 0:u.data.customer===void 0))throw new l("INVALID_REQUEST","Invalid current Funnel start");let g=u.data,c=we.safeParse(await he(e,await t.request("funnels",g)));if(!c.success||!c.data.runToken)throw new l("INVALID_RESPONSE","Funnel start credentials are missing");let r=c.data;if(r.run.source.id!==g.funnelId||r.run.locale!==(g.locale??"en")||!se(r.run.parameters,g.parameters??{})||(g.customer?!r.customerId||g.customer.type==="id"&&r.customerId!==g.customer.value:r.customerId!==void 0))throw new l("INVALID_RESPONSE","Funnel start contract changed");return{...r,runToken:r.runToken}}}}async function hr(e){e={...e};let n=e.configuration;if(!n)throw new l("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&L(t)!==L(e.scope))throw new l("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new l("EVALUATION_MODE","This Funnel uses Remote evaluation");let u=re.test(e.credential);if(u?!e.customerId:e.customerId!==void 0)throw new l("INVALID_REQUEST","Only Server-Key starts name their Customer");let g=An({...e,scope:t,apiKey:e.credential}),c=r=>{let o=Pn({...e,scope:t,runToken:r,...u?{serverKey:e.credential}:{}});return u||o.identify(e.credential),o};return{async start(r){let o=await g.start({...r,funnelId:e.funnelId,...u?{customer:{type:"id",value:e.customerId}}:{}}),a=c(o.runToken),w=await a.get();return{...o,...w,controller:a}},async restore(r){let o=c(r),a=await o.get();if(a.run.source.id!==e.funnelId)throw o.reset(),new l("SCOPE_MISMATCH","Run belongs to another Funnel");return{...a,runToken:r,controller:o}}}}export{Pe as a,Un as b,he as c,Fe as d,rt as e,On as f,gn as g,ft as h,se as i,vt as j,Rt as k,Pn as l,Kt as m,ir as n,An as o,hr as p};
@@ -0,0 +1 @@
1
+ var s={name:"@tinkerlandai/indiana-sdk",version:"0.10.2",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};var i="https://api.longplayai.com";export{s as a,i as b};
@@ -0,0 +1 @@
1
+ import{d as t}from"./chunk-FYGXGMRB.js";import{Ga as n}from"./chunk-Q64VNSPV.js";function r(e,o,a){return n(e,o,a,t)}export{r as a};
@@ -1 +1 @@
1
- import{a as ue,b as me,c as ye,d as ge,e as ve}from"./chunk-SBPTOOYB.js";import{M as fe,Y as le}from"./chunk-2Y4G5364.js";import{ea as pe,oa as we,qa as m}from"./chunk-ACF2FBUB.js";import{b as he,e as be}from"./chunk-6ZZUNGNE.js";import{d as Ie}from"./chunk-AHXYGGAA.js";import{a as z}from"./chunk-DSPLGTQI.js";import{b as de}from"./chunk-3PZ4Y6UD.js";function Ce(e){let b=e.view;if(!b?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let n=b.paywall.receiptId,P=b.nodeId,y=b.visit,p=b.paywall.resolution,u=p,f="document"in p?p:null;function s(t){if(!me(t,p))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let o=b.paywall.quote,D=b.paywall.operation,C=!1,$=new AbortController,d=b.paywall.purchaseRequestId,r=0,c=b.paywall.selectionGeneration??0,T=b.paywall.canReselect===!0,A=null,O=new Map,g=new Map,V=new Map;function L(t){if(t.purchase&&t.purchase.receiptId!==n)throw new m("INVALID_RESPONSE","Purchase receipt changed");let a=t.run.paywall;return t.purchase??(a?.receiptId===n?a:null)}function S(){if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(t,a,l){if(S(),a!==r||l!==void 0&&o?.operationId!==l)return!1;let I=c,w=t.run.paywall;if(w?.receiptId===n){if((w.selectionGeneration??0)<c)return!1;c=w.selectionGeneration??0,T=w.canReselect===!0,s(w.resolution)}let v=L(t),h=c>I,k=h?v?.quote??null:v?.quote??o,E=v?.operation??(k?.operationId===o?.operationId?D:null);return k&&E&&ye(E,{operationId:k.operationId},"Purchase operation changed"),w?.receiptId===n&&(u=w.resolution,f="document"in u?u:f?{...u,document:f.document,offering:f.offering,capabilities:ue(u.capabilities,f.capabilities)}:null),(h||k?.operationId!==o?.operationId)&&(r++,w?.receiptId===n&&(d=w.purchaseRequestId)),o=k,D=ve(D,E,!0),!0}function x(t,a,l){return new Promise((I,w)=>{let v=!1,h=()=>{clearTimeout(B),$.signal.removeEventListener("abort",H)},k=F=>{v||(v=!0,h(),I(F))},E=F=>{v||(v=!0,h(),w(F))},H=()=>E(new m("IDENTITY_CHANGED","Paywall presentation has closed")),B=setTimeout(()=>E(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,l)),Math.max(0,a-Date.now()));$.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted&&H(),t.then(k,E)})}function J(t){return new Promise(a=>{let l=()=>{clearTimeout(I),$.signal.removeEventListener("abort",l),a()},I=setTimeout(l,t);$.signal.addEventListener("abort",l,{once:!0}),$.signal.aborted&&l()})}async function j(t,a,l){S();let I=O.get(t);if(!I){let h=e.pendingCommands?.find(k=>k.requestId===t)??e.pendingCommand;if(h?.operation==="submit"&&h.requestId===t&&h.nodeId===P&&h.visit===y){a.type==="paywall_quote"&&h.input.type==="paywall_quote"&&h.input.predecessor&&!a.predecessor&&(a={...a,predecessor:h.input.predecessor});let k=le.parse(h),E=le.parse({...h,input:a});if(E.operation!=="submit"||k.operation!=="submit"||JSON.stringify(E.input)!==JSON.stringify(k.input))throw new m("CONFLICT","A restored purchase request cannot change its input");a=E.input,I=k,O.set(t,I)}}if(I){if(JSON.stringify(I.input)!==JSON.stringify(a))throw new m("CONFLICT","A purchase request cannot change its input")}else{let h=e.view;if(!h||h.nodeId!==P||h.visit!==y||h.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");I={operation:"submit",requestId:t,nodeId:P,visit:y,revision:h.revision,input:a},O.set(t,I)}let w=Date.now()+3e4,v=await x(e.submit(I),w,t);for(;v.run.pendingRequest?.requestId===t&&Date.now()<w&&!C&&(await J(Math.min(1e3,w-Date.now())),!(C||Date.now()>=w));)v=await x(e.resume(t),w,t);if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(v.run.pendingRequest?.requestId===t)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,t);if(!_(v,l,a.type==="paywall_confirm"||a.type==="paywall_cancel"?a.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed")}async function q(t){if(!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let a=`${t}:${o.operationId}`,l=g.get(a);if(!l){let I=t==="confirm"?"paywall_confirm":"paywall_cancel",w=e.pendingCommands?.find(v=>v.operation==="submit"&&v.input.type===I&&"operationId"in v.input&&v.input.operationId===o.operationId)??e.pendingCommand;l=w?.operation==="submit"&&w.input.type===I&&"operationId"in w.input&&w.input.operationId===o.operationId?w.requestId:crypto.randomUUID(),g.set(a,l)}if(await j(l,{type:t==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.operationId},r),!D)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(D)}return{get view(){return structuredClone(f)},get quote(){return o?structuredClone(o):null},get operation(){return D?structuredClone(D):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return T},async refresh(){S();let t=r,a=await e.get();if(_(a,t),a.run.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");if(!f){if("document"in u||!e.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let l=await e.resolvePaywall(u);S(),s(l),f={...u,document:l.document,offering:l.offering,capabilities:ue(u.capabilities,l.capabilities)}}return structuredClone(f)},preview(t){if(!f)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(d&&d!==t.requestId&&(A||!T))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=f.document.buttons[t.actionId],l=a?.type==="checkout"?fe(a.product,t.selection,f.capabilities):null;if(!l)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let I=we(f.document.screen,l,t.selection,f.capabilities),w=JSON.stringify({actionId:t.actionId,product:l,featureQuantities:I,offerId:t.offerId,nativeOffer:t.nativeOffer});if(V.has(t.requestId)&&V.get(t.requestId)!==w)return Promise.reject(new m("CONFLICT","A purchase request cannot change its quantities or Product"));if(V.set(t.requestId,w),d===t.requestId&&A)return A;let v=d!==t.requestId&&c>0?{operationId:o?.operationId??null,generation:c}:void 0;if(v&&(!T||c<=0))return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));d!==t.requestId&&r++;let h=r;d=t.requestId;let k=(async()=>{if(await j(t.requestId,{type:"paywall_quote",actionId:t.actionId,productVersionId:l,...Object.keys(I).length?{featureQuantities:I}:{},...v?{predecessor:v}:{},...t.offerId?{offerId:t.offerId}:{},...t.nativeOffer?{nativeOffer:t.nativeOffer}:{}},h),!o)throw new m("INVALID_RESPONSE","The accepted quote is missing");return ge(o,{productVersionId:l,featureQuantities:I},"The selected purchase changed"),structuredClone(o)})();return A=k,k.then(()=>{A===k&&(A=null)},E=>{A===k&&(A=null),d===t.requestId&&e.pendingCommand?.requestId!==t.requestId&&E instanceof m&&E.status!==void 0&&E.status<500&&![401,425].includes(E.status)&&(d=null)}),k},confirm:()=>q("confirm"),cancel:()=>q("cancel"),async read(){if(S(),!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let t=o.operationId,a=r,l=e.pendingCommands?.find(h=>h.operation==="submit"&&(h.input.type==="paywall_confirm"||h.input.type==="paywall_cancel")&&h.input.operationId===t)??e.pendingCommand;l?.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===t&&await e.settle?.(l.requestId);let I=await e.get(void 0,{receiptId:n,operationId:t});S();let w=L(I);if(w?.quote&&w.quote.operationId!==t||w?.operation&&w.operation.operationId!==t)throw new m("INVALID_RESPONSE","Purchase operation changed");let v=_(I,a,t)?D:w?.operation;if(!v)throw new m("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(v)},destroy(){C=!0,$.abort(),O.clear(),g.clear(),V.clear()}}}function Ee(e){let b=new Set,n=new Set,P=null;function y(p){if(e.reviewing||b.has(p)||n.has(p)||e.stopped)return;n.add(p);let u=async()=>{if(e.reviewing||e.stopped||e.key!==p){n.delete(p);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{u()},250);return}let f=(async()=>{let o=e.client.view,D=e.expected(),C=D.requestId,$=!1;try{await e.client.submit({operation:"shown",...D})}catch(d){if(!(d instanceof m)||d.code!=="CONFLICT"||d.status!==409||e.client.pendingCommand)throw d;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==p||!r||!o||r.id!==o.id||r.source.versionId!==o.source.versionId||r.nodeId!==D.nodeId||r.visit!==D.visit||r.revision<=D.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw d;let c=e.expected();C=c.requestId,await e.client.submit({operation:"shown",...c})}for(;!e.stopped&&e.key===p&&e.client.pendingCommand?.requestId===C;){if(!e.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(C),$=!0,e.client.pendingCommand?.requestId===C&&await new Promise(d=>setTimeout(d,1500))}e.stopped||e.key!==p||($&&await e.client.get(),!(e.stopped||e.key!==p)&&b.add(p))})();P=f;let s=()=>{P===f&&(P=null),n.delete(p)};f.then(s,o=>{s(),e.busy||e.fail(o)})};u()}return{report:y,get inFlight(){return P}}}function Pe(e){let b={},n=new Map;async function P(y){let p=e.client.view,u=p?.screen,f=u?.customerData.nodes[y.nodeId];if(e.stopped||e.busy||!p||!u||!f)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let r=e.document,c=r?pe(r,y.nodeId):null,T=c?.type==="customer_data"?c.data.outputs?.[y.action]:void 0;T&&u.outputs.includes(T)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:T,answers:e.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await e.onIntent?.(y,p);return}let o=y.action.startsWith("sources_")?f.resources.find(r=>r.key===y.value):null;if(y.action.startsWith("sources_")&&!o)throw new m("INVALID_REQUEST","Choose a current resource");let D=`${p.visit}:${y.nodeId}:${o?.key??""}`,C=n.get(D)??[null],d=b[y.nodeId]??{page:1,after:null,filter:"all",...o?{resourceKey:o.key}:{}};if(y.action==="filter"){let r=y.value;if(!r||!(f.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new m("INVALID_REQUEST","Unknown data filter");d={page:1,after:null,filter:r},C.splice(0,C.length,null)}else if(y.action==="next"||y.action==="sources_next"){let r=o?.sources.at(-1),c=o?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:u.dataCursors[y.nodeId];if(!c||!o&&!f.hasNext)return;C[d.page]=c,d={...d,page:d.page+1,after:c}}else if(y.action==="previous"||y.action==="sources_previous"){if(d.page<=1)return;d={...d,page:d.page-1,after:C[d.page-2]??null}}n.set(D,C),b={...b,[y.nodeId]:d},await e.perform(()=>e.client.get({nodeId:p.nodeId,visit:p.visit,revision:p.revision,components:b}))}return{get queries(){return b},intent:P,reset(){b={},n.clear()}}}function Re(e){let{doc:b,holder:n,reviewHolder:P,mountScreenPreview:y}=e,p=!1,u,f=0,s=null,o="",D=new Map,C=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function $(r){if(e.stopped||!e.client.review)return;p||(o=C(e.client.view),D.set(o,structuredClone(e.answers))),p=!0,u=r,n.hidden=!0,e.suspend(!0),P.hidden=!1;let c=++f;try{let T=await e.client.review(r);if(e.stopped||c!==f||!p)return;if(!T.review)throw new m("INVALID_RESPONSE","Historical projection is missing");s?.destroy(),s=null,P.replaceChildren();let A=T.run.locale.startsWith("zh"),O=b.createElement("p");O.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",P.append(O);for(let[L,S]of T.review.pages.entries()){let _=b.createElement("button");_.type="button",_.textContent=A?`\u7B2C ${L+1} \u9875`:`Page ${L+1}`,_.onclick=()=>{$(S.receiptId)},P.append(_)}if(T.review.page){let L=T.review.page,S=b.createElement("div");if(S.inert=!0,P.append(S),s=y(S,{mode:"live",rendererUrl:e.client.webViewUrl,title:L.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{d()}}),s.update(L.document,T.run.locale,{serverInput:{bindings:L.inputs,answers:L.answers,values:L.values}}),await s.ready,e.stopped||c!==f||!p)return}let g=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},V=A?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let L of[...T.review.coupons.map((S,_)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${g[S.status]}`),...T.review.purchases.map((S,_)=>`${A?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${V[S.status]}`)]){let S=b.createElement("p");S.textContent=L,P.append(S)}e.client.view&&await e.enqueue(e.client.view)}catch(T){if(c!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(T)}}async function d(){if(!p||e.stopped||!e.client.review)return;let r=++f;try{if(await e.client.review(),e.stopped||r!==f)return;p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1;let c=e.client.view;C(c)!==o?(D.set(o,structuredClone(e.answers)),e.resetScreen()):(D.delete(o),e.suspend(!1)),c&&await e.enqueue(c)}catch(c){if(r!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(c)}}return{get active(){return p},get receipt(){return u},open:$,exit:d,get drafts(){return new Map([...D].map(([r,c])=>[r,structuredClone(c)]))},stop(){p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1}}}function De(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let b=e.client.pageExperiments.bind(e.client),n=!1,P=!1,y=0,p=!1,u=!1,f,s=new Map,o=new Set,D={},C=new Map,$=he(e.appManifestRelease),d=()=>{for(let g of s.values())g.effect.revert();s.clear();for(let g of C.values())g();C.clear()};function r(g){n||o.has(g)||(o.add(g),b(e.appManifestRelease,[g]).catch(V=>{o.delete(g),z(e.onError,V)}))}async function c(){if(n)return;let g=e.client.view;if(!g||g.stopped||!["running","waiting"].includes(g.status)){y++,d();return}if(p){u=!0;return}p=!0;let V=++y,L=`${g.id}:${g.visit}:${g.revision}`,S=location.href;try{let[_,{applyVisualVariation:x}]=await Promise.all([b(e.appManifestRelease),import("./visual-dom-OFB7BFFB.js")]),J=e.client.view;if(n||V!==y||!J||J.stopped||!["running","waiting"].includes(J.status)||`${J.id}:${J.visit}:${J.revision}`!==L||location.href!==S)return;let j=new Set,q=new Set;for(let t of _.assignments){let a=`${_.payload.environmentId}:${t.experimentKey}`;if(q.add(a),C.has(a)||C.set(a,be(a,D)),!!t.inExperiment)for(let l of _.payload.experiments){if(l.key!==t.experimentKey||!de(location.href,l.urlPatterns??[]))continue;let I=l.meta?.findIndex(H=>H.key===t.variationKey)??-1,w=l.variations[I];if(!w?.renderGuard)continue;let v=t.receiptId+":"+l.changeId,h=JSON.stringify([t.variationKey,w]);j.add(v);let k=s.get(v);if(k?.signature===h){k.effect.applied&&r(t.receiptId);continue}s.get(v)?.effect.revert(),s.delete(v);let E=x(w,{requireUniqueTargets:!0,boundVariations:l.variations,allowJs:!1,onApplied:()=>r(t.receiptId),onError:H=>z(e.onError,H)});s.set(v,{signature:h,effect:E}),E.applied&&r(t.receiptId)}}for(let[t,a]of s)j.has(t)||(a.effect.revert(),s.delete(t));for(let[t,a]of C)q.has(t)||(a(),C.delete(t))}catch(_){V===y&&d(),z(e.onError,_)}finally{p=!1,u&&!n&&(u=!1,c())}}let T=e.client.subscribe(()=>{y++,c()}),A=Ie(()=>{y++,d(),c()}),O=async()=>{await c(),n||(f=setTimeout(()=>{O()},15e3))};return{async start(){P||n||(P=!0,await O())},refresh:c,destroy(){n=!0,y++,clearTimeout(f),T(),A(),d(),$.destroy()}}}async function rn(e,b){let n=b,{mountScreenPreview:P}=await import("./screen-renderer-ZSAR7LPS.js"),{showPaywall:y}=await import("./paywall-DR65VN2G.js"),p=n.appManifestRelease?De({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;p?.start();let u=e.ownerDocument,f=u.activeElement,s=u.createElement("section"),o=u.createElement("div"),D=u.createElement("div"),C=u.createElement("div"),$=u.createElement("button");C.hidden=!0,$.type="button";let d=u.createElement("p"),r=u.createElement("p"),c=u.createElement("button"),T=u.createElement("button"),A=u.createElement("button"),O=u.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",D.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",d.setAttribute("role","status"),r.setAttribute("role","alert"),r.hidden=!0,c.type=T.type=A.type="button",D.append(c,d,r,A,$,T),s.append(o,C,D),e.append(s);let g=null,V=null,L=null,S="",_="",x="",J="",j="",q=!1,t=0,a=!1,l="",I=null,w=Promise.resolve(),v=null,h=null,k=new Set,E={},H=(i,R=null)=>{q||(h=R,r.textContent=i instanceof Error?i.message:"Request failed",r.hidden=!1,A.hidden=n.client.pendingCommand===null,z(n.onError,i))};function B(){let i=n.client.view;if(!i)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:i.nodeId,visit:i.visit,revision:i.revision}}let F=Re({client:n.client,doc:u,holder:o,reviewHolder:C,mountScreenPreview:P,get stopped(){return q},get answers(){return E},suspend(i){V?.setSuspended(i)},resetScreen(){S="",_="",x=""},enqueue:Y,fail:H}),Z=Ee({client:n.client,expected:B,fail:H,get stopped(){return q},get reviewing(){return F.active},get key(){return S},get busy(){return t}}),ee=Pe({client:n.client,expected:B,perform:W,onIntent:n.onCustomerDataIntent,get stopped(){return q},get busy(){return t},get document(){return g?.document},get answers(){return E}}),oe=i=>i&&(i.screen||i.paywall)?`${i.id}:${i.nodeId}:${i.visit}`:"";function X(){let i=n.client.view;c.disabled=!F.active&&(t>0||!!n.client.pendingCommand||!i?.canBack||i.stopped||!["running","waiting"].includes(i.status)||!oe(i)||_!==oe(i))}async function W(i,R=!1){if(!(t&&!R||q||F.active&&!R)){t++,s.setAttribute("aria-busy","true"),X(),r.hidden=!0,h=null;try{if(!R&&Z.inFlight){let N=n.client.view;await Z.inFlight;let U=n.client.view;if(!N||!U||U.id!==N.id||U.nodeId!==N.nodeId||U.visit!==N.visit||U.stopped||!["running","waiting"].includes(U.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(q)return;let Q=await i();q||await Y(n.client.view??Q.run)}catch(Q){H(Q,n.client.pendingCommand?.requestId??null)}finally{t=Math.max(0,t-1),s.setAttribute("aria-busy",String(t>0)),q||(A.hidden=n.client.pendingCommand===null,X())}}}function ne(){I&&clearTimeout(I),!(q||!L||!["running","waiting"].includes(L.status)&&!n.client.pendingCommand)&&(I=setTimeout(()=>{I=null,ce().finally(ne)},L.pendingRequest||n.client.pendingCommand?1500:5e3))}async function ce(){if(!(q||a||t)){if(F.active){await F.open(F.receipt);return}a=!0;try{let i=n.client.pendingCommand;i&&n.client.settle&&await n.client.settle(i.requestId);let R=n.client.view,Q=ee.queries,N=await n.client.get(R?.screen&&Object.keys(Q).length?{nodeId:R.nodeId,visit:R.visit,revision:R.revision,components:Q}:void 0);!q&&Q===ee.queries&&await Y(n.client.view??N.run)}catch(i){H(i)}finally{a=!1}}}function Se(i){let R=i.screen?.presentation;if(!R||R.type==="inline"){O.open&&O.close(),s.parentElement!==e&&e.append(s);return}s.parentElement!==O&&(O.append(s),e.append(O));let Q={sm:420,md:640,lg:900};O.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in R?Q[R.size]+"px":"100vw"}`,O.setAttribute("aria-label",g?.document?.name??i.screen?.content.document.name??"Funnel"),O.open||O.showModal()}async function Fe(i){if(q)return;L=i,h&&n.client.pendingCommand?.requestId!==h&&(r.hidden=!0,h=null);let R=i.locale.startsWith("zh");if($.textContent=R?"\u56DE\u770B":"History",$.hidden=!n.client.review,c.textContent=F.active?R?"\u8FD4\u56DE\u5F53\u524D":"Return to current":R?"\u8FD4\u56DE":"Back",T.textContent=R?"\u5173\u95ED":"Close",A.textContent=R?"\u91CD\u8BD5":"Retry",X(),A.hidden=n.client.pendingCommand===null,d.textContent=i.pendingRequest?R?"\u6B63\u5728\u5904\u7406":"Processing":i.instruction?.type==="wait"?R?"\u7B49\u5F85\u4E2D":"Waiting":"",l!==`${i.revision}:${i.visit}:${i.status}:${i.stopped}`&&(l=`${i.revision}:${i.visit}:${i.status}:${i.stopped}`,z(n.onState,structuredClone(i))),i.stopped||n.client.configurationReady===!1){F.stop(),g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close(),s.hidden=!0,ne();return}if(s.hidden=!1,F.active){ne();return}let Q=oe(i);if(Q!==S&&(_="",g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S=Q,x="",j="",E={...i.answers},ee.reset()),Se(i),i.screen){let U=i.screen.content;g||(g=P(o,{mode:"live",rendererUrl:n.client.webViewUrl,title:U.document.name,onAction(G,se={},ae={}){if(F.active)return;E={...E,...ae};let Te=Object.fromEntries((i.screen?.inputs??[]).filter(({variable:re})=>Object.hasOwn(E,re)).map(({variable:re})=>[re,E[re]]));W(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:G,answers:Te,selection:se}}))},onAnswers:G=>{F.active||(E={...E,...G})},onCustomerDataIntent:G=>{F.active||ee.intent(G).catch(H)},onEscape:()=>{F.active||te()},onError:G=>H(new Error(G)),onRendered:()=>Z.report(Q)}));let M={capabilities:i.screen.capabilities,customerData:i.screen.customerData,parameters:i.parameters,serverInput:{bindings:i.screen.inputs,answers:E,values:i.screen.values}},K=JSON.stringify([U,i.locale,M.parameters,i.screen.inputs,i.screen.values]);if(K!==x)g.update(U.document,i.locale,M),x=K,J=JSON.stringify(M.capabilities),j=JSON.stringify(M.customerData);else{let G=JSON.stringify(M.capabilities);G!==J&&(g.updateCapabilities(M.capabilities),J=G),JSON.stringify(M.customerData)!==j&&(g.updateCustomerData(M.customerData),j=JSON.stringify(M.customerData))}await g.ready}else if(i.paywall&&!V){let U=await y(o,{canInteract:()=>!F.active&&!q,start:async()=>Ce(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:M=>n.onOpenUrl?n.onOpenUrl({receiptId:i.paywall.receiptId,url:M,openIn:"same_window"}):u.defaultView?.location.assign(M),onAction:async M=>{if(F.active)return;let K=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:i.nodeId,visit:i.visit,revision:i.revision,input:{type:"screen",output:M,answers:{}}});await Y(n.client.view??K.run)},onError:H,onDismiss:()=>{!F.active&&!q&&n.client.view?.visit===i.visit&&te()}});q?U.host?.destroy():(V=U.host,V?.setSuspended(F.active)),Z.report(Q)}if(q)return;_=Q,X();let N=i.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!k.has(N.receiptId)){let U=u.createElement("button");U.type="button",U.textContent=N.type==="open_url"?`${R?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:R?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let M=B(),K=N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="new_window"?Ne(N.url):null;W(async()=>{let G="success";if(N.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(ae){z(n.onError,ae),G="failed"}else G=N.openIn==="new_window"&&!K?"failed":"opened";if(N.type==="event"){if(!n.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(N.event)}if(q||n.client.view?.nodeId!==M.nodeId||n.client.view.visit!==M.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let se=await n.client.submit({operation:"submit",...M,input:{type:"client_action",receiptId:N.receiptId,outcome:G}});return k.add(N.receiptId),N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="same_window"&&u.defaultView?.location.assign(N.url),se})},o.replaceChildren(U)}!i.pendingRequest&&i.status==="completed"&&!k.has(`complete:${i.id}`)&&(k.add(`complete:${i.id}`),z(n.onComplete,structuredClone(i))),ne()}function Ne(i){let R=u.defaultView?.open(i,"_blank")??null;return R&&(R.opener=null),R}function Y(i){return X(),w=w.catch(()=>{}).then(()=>Fe(i)),w}let Oe=n.client.subscribe(i=>{n.client.configurationReady===!1&&(s.hidden=!0,g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close()),Y(i).catch(H)}),ke=n.client.subscribeError?.(H);function te(){return v||(q?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(ie(),Promise.resolve()):(v=W(()=>n.client.submit({operation:"close",...B()}),!0).then(()=>{n.client.view?.status==="closed"&&ie()}).finally(()=>{v=null}),v))}function ie(){p?.destroy(),!q&&(q=!0,I&&clearTimeout(I),Oe(),ke?.(),g?.destroy(),F.stop(),V?.destroy(),O.close(),O.remove(),s.remove(),f instanceof HTMLElement&&f.isConnected&&f.focus(),z(n.onDismiss,L?structuredClone(L):null))}c.onclick=()=>{if(!c.disabled){if(F.active){F.exit();return}W(()=>n.client.submit({operation:"back",...B()}))}},$.onclick=()=>{F.open()},T.onclick=()=>{te()},A.onclick=()=>{W(()=>n.client.retry())},O.addEventListener("cancel",i=>{i.preventDefault(),te()});try{let i=await n.client.get();await Y(n.client.view??i.run)}catch(i){throw ie(),i}return{destroy:ie,refresh:ce,review:F.open,exitReview:F.exit,get unappliedDrafts(){return F.drafts}}}export{De as a,rn as b};
1
+ import{a as ue,b as me,c as ye,d as ge,e as ve}from"./chunk-SBPTOOYB.js";import{M as fe,Y as le}from"./chunk-Q64VNSPV.js";import{ea as pe,oa as we,qa as m}from"./chunk-ACF2FBUB.js";import{b as he,e as be}from"./chunk-EARSGITJ.js";import{d as Ie}from"./chunk-XO42OH3M.js";import{a as z}from"./chunk-DSPLGTQI.js";import{b as de}from"./chunk-3PZ4Y6UD.js";function Ce(e){let b=e.view;if(!b?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let n=b.paywall.receiptId,P=b.nodeId,y=b.visit,p=b.paywall.resolution,u=p,f="document"in p?p:null;function s(i){if(!me(i,p))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let o=b.paywall.quote,D=b.paywall.operation,C=!1,$=new AbortController,d=b.paywall.purchaseRequestId,r=0,c=b.paywall.selectionGeneration??0,T=b.paywall.canReselect===!0,A=null,O=new Map,g=new Map,V=new Map;function L(i){if(i.purchase&&i.purchase.receiptId!==n)throw new m("INVALID_RESPONSE","Purchase receipt changed");let a=i.run.paywall;return i.purchase??(a?.receiptId===n?a:null)}function S(){if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,a,l){if(S(),a!==r||l!==void 0&&o?.operationId!==l)return!1;let I=c,w=i.run.paywall;if(w?.receiptId===n){if((w.selectionGeneration??0)<c)return!1;c=w.selectionGeneration??0,T=w.canReselect===!0,s(w.resolution)}let v=L(i),h=c>I,k=h?v?.quote??null:v?.quote??o,E=v?.operation??(k?.operationId===o?.operationId?D:null);return k&&E&&ye(E,{operationId:k.operationId},"Purchase operation changed"),w?.receiptId===n&&(u=w.resolution,f="document"in u?u:f?{...u,document:f.document,offering:f.offering,capabilities:ue(u.capabilities,f.capabilities)}:null),(h||k?.operationId!==o?.operationId)&&(r++,w?.receiptId===n&&(d=w.purchaseRequestId)),o=k,D=ve(D,E,!0),!0}function x(i,a,l){return new Promise((I,w)=>{let v=!1,h=()=>{clearTimeout(B),$.signal.removeEventListener("abort",H)},k=F=>{v||(v=!0,h(),I(F))},E=F=>{v||(v=!0,h(),w(F))},H=()=>E(new m("IDENTITY_CHANGED","Paywall presentation has closed")),B=setTimeout(()=>E(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,l)),Math.max(0,a-Date.now()));$.signal.addEventListener("abort",H,{once:!0}),$.signal.aborted&&H(),i.then(k,E)})}function J(i){return new Promise(a=>{let l=()=>{clearTimeout(I),$.signal.removeEventListener("abort",l),a()},I=setTimeout(l,i);$.signal.addEventListener("abort",l,{once:!0}),$.signal.aborted&&l()})}async function j(i,a,l){S();let I=O.get(i);if(!I){let h=e.pendingCommands?.find(k=>k.requestId===i)??e.pendingCommand;if(h?.operation==="submit"&&h.requestId===i&&h.nodeId===P&&h.visit===y){a.type==="paywall_quote"&&h.input.type==="paywall_quote"&&h.input.predecessor&&!a.predecessor&&(a={...a,predecessor:h.input.predecessor});let k=le.parse(h),E=le.parse({...h,input:a});if(E.operation!=="submit"||k.operation!=="submit"||JSON.stringify(E.input)!==JSON.stringify(k.input))throw new m("CONFLICT","A restored purchase request cannot change its input");a=E.input,I=k,O.set(i,I)}}if(I){if(JSON.stringify(I.input)!==JSON.stringify(a))throw new m("CONFLICT","A purchase request cannot change its input")}else{let h=e.view;if(!h||h.nodeId!==P||h.visit!==y||h.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");I={operation:"submit",requestId:i,nodeId:P,visit:y,revision:h.revision,input:a},O.set(i,I)}let w=Date.now()+3e4,v=await x(e.submit(I),w,i);for(;v.run.pendingRequest?.requestId===i&&Date.now()<w&&!C&&(await J(Math.min(1e3,w-Date.now())),!(C||Date.now()>=w));)v=await x(e.resume(i),w,i);if(C)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(v.run.pendingRequest?.requestId===i)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,i);if(!_(v,l,a.type==="paywall_confirm"||a.type==="paywall_cancel"?a.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed")}async function q(i){if(!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let a=`${i}:${o.operationId}`,l=g.get(a);if(!l){let I=i==="confirm"?"paywall_confirm":"paywall_cancel",w=e.pendingCommands?.find(v=>v.operation==="submit"&&v.input.type===I&&"operationId"in v.input&&v.input.operationId===o.operationId)??e.pendingCommand;l=w?.operation==="submit"&&w.input.type===I&&"operationId"in w.input&&w.input.operationId===o.operationId?w.requestId:crypto.randomUUID(),g.set(a,l)}if(await j(l,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.operationId},r),!D)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(D)}return{get view(){return structuredClone(f)},get quote(){return o?structuredClone(o):null},get operation(){return D?structuredClone(D):null},get webViewUrl(){return e.webViewUrl},get canReselect(){return T},async refresh(){S();let i=r,a=await e.get();if(_(a,i),a.run.paywall?.receiptId!==n)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");if(!f){if("document"in u||!e.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let l=await e.resolvePaywall(u);S(),s(l),f={...u,document:l.document,offering:l.offering,capabilities:ue(u.capabilities,l.capabilities)}}return structuredClone(f)},preview(i){if(!f)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(d&&d!==i.requestId&&(A||!T))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=f.document.buttons[i.actionId],l=a?.type==="checkout"?fe(a.product,i.selection,f.capabilities):null;if(!l)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let I=we(f.document.screen,l,i.selection,f.capabilities),w=JSON.stringify({actionId:i.actionId,product:l,featureQuantities:I,offerId:i.offerId,nativeOffer:i.nativeOffer});if(V.has(i.requestId)&&V.get(i.requestId)!==w)return Promise.reject(new m("CONFLICT","A purchase request cannot change its quantities or Product"));if(V.set(i.requestId,w),d===i.requestId&&A)return A;let v=d!==i.requestId&&c>0?{operationId:o?.operationId??null,generation:c}:void 0;if(v&&(!T||c<=0))return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));d!==i.requestId&&r++;let h=r;d=i.requestId;let k=(async()=>{if(await j(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:l,...Object.keys(I).length?{featureQuantities:I}:{},...v?{predecessor:v}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}},h),!o)throw new m("INVALID_RESPONSE","The accepted quote is missing");return ge(o,{productVersionId:l,featureQuantities:I},"The selected purchase changed"),structuredClone(o)})();return A=k,k.then(()=>{A===k&&(A=null)},E=>{A===k&&(A=null),d===i.requestId&&e.pendingCommand?.requestId!==i.requestId&&E instanceof m&&E.status!==void 0&&E.status<500&&![401,425].includes(E.status)&&(d=null)}),k},confirm:()=>q("confirm"),cancel:()=>q("cancel"),async read(){if(S(),!o)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.operationId,a=r,l=e.pendingCommands?.find(h=>h.operation==="submit"&&(h.input.type==="paywall_confirm"||h.input.type==="paywall_cancel")&&h.input.operationId===i)??e.pendingCommand;l?.operation==="submit"&&(l.input.type==="paywall_confirm"||l.input.type==="paywall_cancel")&&l.input.operationId===i&&await e.settle?.(l.requestId);let I=await e.get(void 0,{receiptId:n,operationId:i});S();let w=L(I);if(w?.quote&&w.quote.operationId!==i||w?.operation&&w.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let v=_(I,a,i)?D:w?.operation;if(!v)throw new m("INVALID_RESPONSE","The current purchase result is missing");return structuredClone(v)},destroy(){C=!0,$.abort(),O.clear(),g.clear(),V.clear()}}}function Ee(e){let b=new Set,n=new Set,P=null;function y(p){if(e.reviewing||b.has(p)||n.has(p)||e.stopped)return;n.add(p);let u=async()=>{if(e.reviewing||e.stopped||e.key!==p){n.delete(p);return}if(e.busy||e.client.pendingCommand){setTimeout(()=>{u()},250);return}let f=(async()=>{let o=e.client.view,D=e.expected(),C=D.requestId,$=!1;try{await e.client.submit({operation:"shown",...D})}catch(d){if(!(d instanceof m)||d.code!=="CONFLICT"||d.status!==409||e.client.pendingCommand)throw d;await e.client.get();let r=e.client.view;if(e.stopped||e.reviewing||e.key!==p||!r||!o||r.id!==o.id||r.source.versionId!==o.source.versionId||r.nodeId!==D.nodeId||r.visit!==D.visit||r.revision<=D.revision||r.stopped||!r.screen||!["running","waiting"].includes(r.status)||e.client.pendingCommand)throw d;let c=e.expected();C=c.requestId,await e.client.submit({operation:"shown",...c})}for(;!e.stopped&&e.key===p&&e.client.pendingCommand?.requestId===C;){if(!e.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await e.client.settle(C),$=!0,e.client.pendingCommand?.requestId===C&&await new Promise(d=>setTimeout(d,1500))}e.stopped||e.key!==p||($&&await e.client.get(),!(e.stopped||e.key!==p)&&b.add(p))})();P=f;let s=()=>{P===f&&(P=null),n.delete(p)};f.then(s,o=>{s(),e.busy||e.fail(o)})};u()}return{report:y,get inFlight(){return P}}}function Pe(e){let b={},n=new Map;async function P(y){let p=e.client.view,u=p?.screen,f=u?.customerData.nodes[y.nodeId];if(e.stopped||e.busy||!p||!u||!f)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let r=e.document,c=r?pe(r,y.nodeId):null,T=c?.type==="customer_data"?c.data.outputs?.[y.action]:void 0;T&&u.outputs.includes(T)?await e.perform(()=>e.client.submit({operation:"submit",...e.expected(),input:{type:"screen",output:T,answers:e.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await e.onIntent?.(y,p);return}let o=y.action.startsWith("sources_")?f.resources.find(r=>r.key===y.value):null;if(y.action.startsWith("sources_")&&!o)throw new m("INVALID_REQUEST","Choose a current resource");let D=`${p.visit}:${y.nodeId}:${o?.key??""}`,C=n.get(D)??[null],d=b[y.nodeId]??{page:1,after:null,filter:"all",...o?{resourceKey:o.key}:{}};if(y.action==="filter"){let r=y.value;if(!r||!(f.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(r))throw new m("INVALID_REQUEST","Unknown data filter");d={page:1,after:null,filter:r},C.splice(0,C.length,null)}else if(y.action==="next"||y.action==="sources_next"){let r=o?.sources.at(-1),c=o?r?{kind:"ledger",cursor:{at:r.detail[0],id:r.id,type:"source"}}:null:u.dataCursors[y.nodeId];if(!c||!o&&!f.hasNext)return;C[d.page]=c,d={...d,page:d.page+1,after:c}}else if(y.action==="previous"||y.action==="sources_previous"){if(d.page<=1)return;d={...d,page:d.page-1,after:C[d.page-2]??null}}n.set(D,C),b={...b,[y.nodeId]:d},await e.perform(()=>e.client.get({nodeId:p.nodeId,visit:p.visit,revision:p.revision,components:b}))}return{get queries(){return b},intent:P,reset(){b={},n.clear()}}}function Re(e){let{doc:b,holder:n,reviewHolder:P,mountScreenPreview:y}=e,p=!1,u,f=0,s=null,o="",D=new Map,C=r=>r?`${r.id}:${r.nodeId}:${r.visit}:${r.revision}:${r.paywall?.quote?.operationId??""}`:"";async function $(r){if(e.stopped||!e.client.review)return;p||(o=C(e.client.view),D.set(o,structuredClone(e.answers))),p=!0,u=r,n.hidden=!0,e.suspend(!0),P.hidden=!1;let c=++f;try{let T=await e.client.review(r);if(e.stopped||c!==f||!p)return;if(!T.review)throw new m("INVALID_RESPONSE","Historical projection is missing");s?.destroy(),s=null,P.replaceChildren();let A=T.run.locale.startsWith("zh"),O=b.createElement("p");O.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",P.append(O);for(let[L,S]of T.review.pages.entries()){let _=b.createElement("button");_.type="button",_.textContent=A?`\u7B2C ${L+1} \u9875`:`Page ${L+1}`,_.onclick=()=>{$(S.receiptId)},P.append(_)}if(T.review.page){let L=T.review.page,S=b.createElement("div");if(S.inert=!0,P.append(S),s=y(S,{mode:"live",rendererUrl:e.client.webViewUrl,title:L.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{d()}}),s.update(L.document,T.run.locale,{serverInput:{bindings:L.inputs,answers:L.answers,values:L.values}}),await s.ready,e.stopped||c!==f||!p)return}let g=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},V=A?{pending:"\u5904\u7406\u4E2D",complete:"\u5DF2\u5B8C\u6210",cancelled:"\u5DF2\u53D6\u6D88",failed:"\u5931\u8D25",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{pending:"Processing",complete:"Completed",cancelled:"Cancelled",failed:"Failed",unknown:"Status unconfirmed"};for(let L of[...T.review.coupons.map((S,_)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${_+1}: ${g[S.status]}`),...T.review.purchases.map((S,_)=>`${A?"\u8D2D\u4E70":"Purchase"} ${_+1}: ${V[S.status]}`)]){let S=b.createElement("p");S.textContent=L,P.append(S)}e.client.view&&await e.enqueue(e.client.view)}catch(T){if(c!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(T)}}async function d(){if(!p||e.stopped||!e.client.review)return;let r=++f;try{if(await e.client.review(),e.stopped||r!==f)return;p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1;let c=e.client.view;C(c)!==o?(D.set(o,structuredClone(e.answers)),e.resetScreen()):(D.delete(o),e.suspend(!1)),c&&await e.enqueue(c)}catch(c){if(r!==f||e.stopped)return;s?.destroy(),s=null,P.replaceChildren(),e.fail(c)}}return{get active(){return p},get receipt(){return u},open:$,exit:d,get drafts(){return new Map([...D].map(([r,c])=>[r,structuredClone(c)]))},stop(){p=!1,f++,s?.destroy(),s=null,P.replaceChildren(),P.hidden=!0,n.hidden=!1}}}function De(e){if(!e.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let b=e.client.pageExperiments.bind(e.client),n=!1,P=!1,y=0,p=!1,u=!1,f,s=new Map,o=new Set,D={},C=new Map,$=he(e.appManifestRelease),d=()=>{for(let g of s.values())g.effect.revert();s.clear();for(let g of C.values())g();C.clear()};function r(g){n||o.has(g)||(o.add(g),b(e.appManifestRelease,[g]).catch(V=>{o.delete(g),z(e.onError,V)}))}async function c(){if(n)return;let g=e.client.view;if(!g||g.stopped||!["running","waiting"].includes(g.status)){y++,d();return}if(p){u=!0;return}p=!0;let V=++y,L=`${g.id}:${g.visit}:${g.revision}`,S=location.href;try{let[_,{applyVisualVariation:x}]=await Promise.all([b(e.appManifestRelease),import("./visual-dom-OFB7BFFB.js")]),J=e.client.view;if(n||V!==y||!J||J.stopped||!["running","waiting"].includes(J.status)||`${J.id}:${J.visit}:${J.revision}`!==L||location.href!==S)return;let j=new Set,q=new Set;for(let i of _.assignments){let a=`${_.payload.environmentId}:${i.experimentKey}`;if(q.add(a),C.has(a)||C.set(a,be(a,D)),!!i.inExperiment)for(let l of _.payload.experiments){if(l.key!==i.experimentKey||!de(location.href,l.urlPatterns??[]))continue;let I=l.meta?.findIndex(H=>H.key===i.variationKey)??-1,w=l.variations[I];if(!w?.renderGuard)continue;let v=i.receiptId+":"+l.changeId,h=JSON.stringify([i.variationKey,w]);j.add(v);let k=s.get(v);if(k?.signature===h){k.effect.applied&&r(i.receiptId);continue}s.get(v)?.effect.revert(),s.delete(v);let E=x(w,{requireUniqueTargets:!0,boundVariations:l.variations,allowJs:!1,onApplied:()=>r(i.receiptId),onError:H=>z(e.onError,H)});s.set(v,{signature:h,effect:E}),E.applied&&r(i.receiptId)}}for(let[i,a]of s)j.has(i)||(a.effect.revert(),s.delete(i));for(let[i,a]of C)q.has(i)||(a(),C.delete(i))}catch(_){V===y&&d(),z(e.onError,_)}finally{p=!1,u&&!n&&(u=!1,c())}}let T=e.client.subscribe(()=>{y++,c()}),A=Ie(()=>{y++,d(),c()}),O=async()=>{await c(),n||(f=setTimeout(()=>{O()},15e3))};return{async start(){P||n||(P=!0,await O())},refresh:c,destroy(){n=!0,y++,clearTimeout(f),T(),A(),d(),$.destroy()}}}async function rn(e,b){let n=b,{mountScreenPreview:P}=await import("./screen-renderer-ZSAR7LPS.js"),{showPaywall:y}=await import("./paywall-527RPFAX.js"),p=n.appManifestRelease?De({client:n.client,appManifestRelease:n.appManifestRelease,onError:n.onError}):void 0;p?.start();let u=e.ownerDocument,f=u.activeElement,s=u.createElement("section"),o=u.createElement("div"),D=u.createElement("div"),C=u.createElement("div"),$=u.createElement("button");C.hidden=!0,$.type="button";let d=u.createElement("p"),r=u.createElement("p"),c=u.createElement("button"),T=u.createElement("button"),A=u.createElement("button"),O=u.createElement("dialog");s.dataset.indianaFunnel="",s.setAttribute("aria-busy","false"),s.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",D.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",d.setAttribute("role","status"),r.setAttribute("role","alert"),r.hidden=!0,c.type=T.type=A.type="button",D.append(c,d,r,A,$,T),s.append(o,C,D),e.append(s);let g=null,V=null,L=null,S="",_="",x="",J="",j="",q=!1,i=0,a=!1,l="",I=null,w=Promise.resolve(),v=null,h=null,k=new Set,E={},H=(t,R=null)=>{q||(h=R,r.textContent=t instanceof Error?t.message:"Request failed",r.hidden=!1,A.hidden=n.client.pendingCommand===null,z(n.onError,t))};function B(){let t=n.client.view;if(!t)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let F=Re({client:n.client,doc:u,holder:o,reviewHolder:C,mountScreenPreview:P,get stopped(){return q},get answers(){return E},suspend(t){V?.setSuspended(t)},resetScreen(){S="",_="",x=""},enqueue:Y,fail:H}),ee=Ee({client:n.client,expected:B,fail:H,get stopped(){return q},get reviewing(){return F.active},get key(){return S},get busy(){return i}}),ne=Pe({client:n.client,expected:B,perform:W,onIntent:n.onCustomerDataIntent,get stopped(){return q},get busy(){return i},get document(){return g?.document},get answers(){return E}}),oe=t=>t&&(t.screen||t.paywall)?`${t.id}:${t.nodeId}:${t.visit}`:"";function X(){let t=n.client.view;c.disabled=!F.active&&(i>0||!!n.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!oe(t)||_!==oe(t))}async function W(t,R=!1){if(!(i&&!R||q||F.active&&!R)){i++,s.setAttribute("aria-busy","true"),X(),r.hidden=!0,h=null;try{if(!R&&ee.inFlight){let N=n.client.view;await ee.inFlight;let U=n.client.view;if(!N||!U||U.id!==N.id||U.nodeId!==N.nodeId||U.visit!==N.visit||U.stopped||!["running","waiting"].includes(U.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(q)return;let Q=await t();q||await Y(n.client.view??Q.run)}catch(Q){H(Q,n.client.pendingCommand?.requestId??null)}finally{i=Math.max(0,i-1),s.setAttribute("aria-busy",String(i>0)),q||(A.hidden=n.client.pendingCommand===null,X())}}}function te(){I&&clearTimeout(I),!(q||!L||!["running","waiting"].includes(L.status)&&!n.client.pendingCommand)&&(I=setTimeout(()=>{I=null,ce().finally(te)},L.pendingRequest||n.client.pendingCommand?1500:5e3))}async function ce(){if(!(q||a||i)){if(F.active){await F.open(F.receipt);return}a=!0;try{let t=n.client.pendingCommand;t&&n.client.settle&&await n.client.settle(t.requestId);let R=n.client.view,Q=ne.queries,N=await n.client.get(R?.screen&&Object.keys(Q).length?{nodeId:R.nodeId,visit:R.visit,revision:R.revision,components:Q}:void 0);!q&&Q===ne.queries&&await Y(n.client.view??N.run)}catch(t){H(t)}finally{a=!1}}}function Se(t){let R=t.screen?.presentation;if(!R||R.type==="inline"){O.open&&O.close(),s.parentElement!==e&&e.append(s);return}s.parentElement!==O&&(O.append(s),e.append(O));let Q={sm:420,md:640,lg:900};O.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in R?Q[R.size]+"px":"100vw"}`,O.setAttribute("aria-label",g?.document?.name??t.screen?.content.document.name??"Funnel"),O.open||O.showModal()}async function Fe(t){if(q)return;L=t,h&&n.client.pendingCommand?.requestId!==h&&(r.hidden=!0,h=null);let R=t.locale.startsWith("zh");if($.textContent=R?"\u56DE\u770B":"History",$.hidden=!n.client.review,c.textContent=F.active?R?"\u8FD4\u56DE\u5F53\u524D":"Return to current":R?"\u8FD4\u56DE":"Back",T.textContent=R?"\u5173\u95ED":"Close",A.textContent=R?"\u91CD\u8BD5":"Retry",X(),A.hidden=n.client.pendingCommand===null,d.textContent=t.pendingRequest?R?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?R?"\u7B49\u5F85\u4E2D":"Waiting":"",l!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(l=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,z(n.onState,structuredClone(t))),!t.pendingRequest&&["closed","ineligible","failed"].includes(t.status)){Z();return}if(t.stopped||n.client.configurationReady===!1){F.stop(),g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close(),s.hidden=!0,te();return}if(s.hidden=!1,F.active){te();return}let Q=oe(t);if(Q!==S&&(_="",g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S=Q,x="",j="",E={...t.answers},ne.reset()),Se(t),t.screen){let U=t.screen.content;g||(g=P(o,{mode:"live",rendererUrl:n.client.webViewUrl,title:U.document.name,onAction(G,se={},ae={}){if(F.active)return;E={...E,...ae};let Te=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:re})=>Object.hasOwn(E,re)).map(({variable:re})=>[re,E[re]]));W(()=>n.client.submit({operation:"submit",...B(),input:{type:"screen",output:G,answers:Te,selection:se}}))},onAnswers:G=>{F.active||(E={...E,...G})},onCustomerDataIntent:G=>{F.active||ne.intent(G).catch(H)},onEscape:()=>{F.active||ie()},onError:G=>H(new Error(G)),onRendered:()=>ee.report(Q)}));let M={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:E,values:t.screen.values}},K=JSON.stringify([U,t.locale,M.parameters,t.screen.inputs,t.screen.values]);if(K!==x)g.update(U.document,t.locale,M),x=K,J=JSON.stringify(M.capabilities),j=JSON.stringify(M.customerData);else{let G=JSON.stringify(M.capabilities);G!==J&&(g.updateCapabilities(M.capabilities),J=G),JSON.stringify(M.customerData)!==j&&(g.updateCustomerData(M.customerData),j=JSON.stringify(M.customerData))}await g.ready}else if(t.paywall&&!V){let U=await y(o,{canInteract:()=>!F.active&&!q,start:async()=>Ce(n.client),onPurchase:n.onPurchase,onCheckoutUrl:n.onCheckoutUrl,resolveOfferId:n.resolveOfferId,onEvent:n.onEvent,onOpenUrl:M=>n.onOpenUrl?n.onOpenUrl({receiptId:t.paywall.receiptId,url:M,openIn:"same_window"}):u.defaultView?.location.assign(M),onAction:async M=>{if(F.active)return;let K=await n.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision,input:{type:"screen",output:M,answers:{}}});await Y(n.client.view??K.run)},onError:H,onDismiss:()=>{!F.active&&!q&&n.client.view?.visit===t.visit&&ie()}});q?U.host?.destroy():(V=U.host,V?.setSuspended(F.active)),ee.report(Q)}if(q)return;_=Q,X();let N=t.instruction;if(N&&(N.type==="open_url"||N.type==="event")&&!k.has(N.receiptId)){let U=u.createElement("button");U.type="button",U.textContent=N.type==="open_url"?`${R?"\u524D\u5F80":"Continue to"} ${new URL(N.url).host}`:R?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let M=B(),K=N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="new_window"?Ne(N.url):null;W(async()=>{let G="success";if(N.type==="open_url")if(n.onOpenUrl)try{G=await n.onOpenUrl({receiptId:N.receiptId,url:N.url,openIn:N.openIn})===!1?"failed":"opened"}catch(ae){z(n.onError,ae),G="failed"}else G=N.openIn==="new_window"&&!K?"failed":"opened";if(N.type==="event"){if(!n.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await n.onEvent(N.event)}if(q||n.client.view?.nodeId!==M.nodeId||n.client.view.visit!==M.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let se=await n.client.submit({operation:"submit",...M,input:{type:"client_action",receiptId:N.receiptId,outcome:G}});return k.add(N.receiptId),N.type==="open_url"&&!n.onOpenUrl&&N.openIn==="same_window"&&u.defaultView?.location.assign(N.url),se})},o.replaceChildren(U)}!t.pendingRequest&&t.status==="completed"&&!k.has(`complete:${t.id}`)&&(k.add(`complete:${t.id}`),z(n.onComplete,structuredClone(t))),te()}function Ne(t){let R=u.defaultView?.open(t,"_blank")??null;return R&&(R.opener=null),R}function Y(t){return X(),w=w.catch(()=>{}).then(()=>Fe(t)),w}let Oe=n.client.subscribe(t=>{n.client.configurationReady===!1&&(s.hidden=!0,g?.destroy(),g=null,V?.destroy(),V=null,o.replaceChildren(),S="",_="",x="",j="",O.open&&O.close()),Y(t).catch(H)}),ke=n.client.subscribeError?.(H);function ie(){return v||(q?Promise.resolve():n.client.view&&!["running","waiting"].includes(n.client.view.status)?(Z(),Promise.resolve()):(v=W(()=>n.client.submit({operation:"close",...B()}),!0).then(()=>{n.client.view?.status==="closed"&&Z()}).finally(()=>{v=null}),v))}function Z(){p?.destroy(),!q&&(q=!0,I&&clearTimeout(I),Oe(),ke?.(),g?.destroy(),F.stop(),V?.destroy(),O.close(),O.remove(),s.remove(),f instanceof HTMLElement&&f.isConnected&&f.focus(),z(n.onDismiss,L?structuredClone(L):null))}c.onclick=()=>{if(!c.disabled){if(F.active){F.exit();return}W(()=>n.client.submit({operation:"back",...B()}))}},$.onclick=()=>{F.open()},T.onclick=()=>{ie()},A.onclick=()=>{W(()=>n.client.retry())},O.addEventListener("cancel",t=>{t.preventDefault(),ie()});try{let t=await n.client.get();await Y(n.client.view??t.run)}catch(t){throw Z(),t}return{destroy:Z,refresh:ce,review:F.open,exitReview:F.exit,get unappliedDrafts(){return F.drafts}}}export{De as a,rn as b};