@tinkerlandai/longplay-sdk 0.10.18 → 0.10.19

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 (55) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +9 -3
  3. package/README.zh-CN.md +1 -1
  4. package/dist/{ai-usage-D7BUuP1H.d.ts → ai-usage-DPGx5otD.d.ts} +3 -3
  5. package/dist/{api-CIbhe8RY.d.ts → api-G8EA_ueL.d.ts} +3596 -200
  6. package/dist/chunk-2JBNOE2D.js +1 -0
  7. package/dist/chunk-4SWGHICJ.js +17 -0
  8. package/dist/chunk-5OD42XQS.js +1 -0
  9. package/dist/{chunk-OMHZBCS3.js → chunk-A7U4Z6EH.js} +1 -1
  10. package/dist/{chunk-LHBBSD77.js → chunk-CCRBXW4M.js} +1 -1
  11. package/dist/chunk-DVKZLOS7.js +1 -0
  12. package/dist/{chunk-ML6EHT43.js → chunk-EDVR7FPD.js} +1 -1
  13. package/dist/chunk-FISFN5IY.js +1 -0
  14. package/dist/chunk-GSFNAB3W.js +6 -0
  15. package/dist/{chunk-26HU2HXU.js → chunk-KHIQQNTR.js} +1 -1
  16. package/dist/{chunk-6HWNW6FJ.js → chunk-LNSFRQ6G.js} +1 -1
  17. package/dist/chunk-W2Z3UVW3.js +1 -0
  18. package/dist/{chunk-T5COWMDA.js → chunk-XIYNQHN7.js} +1 -1
  19. package/dist/{chunk-P6HCD5OQ.js → chunk-XXBN76NP.js} +1 -1
  20. package/dist/{chunk-E4LUW6KP.js → chunk-YNMSSQQY.js} +1 -1
  21. package/dist/{content-DLYNJIEB.js → content-E2OWWKDG.js} +1 -1
  22. package/dist/{customer-page-km5f1PJZ.d.ts → customer-page-BV5EvCUY.d.ts} +20 -0
  23. package/dist/{funnel-local-client-CAuNpJ-e.d.ts → funnel-local-client-DjvVzCfH.d.ts} +14039 -312
  24. package/dist/{funnel-node-evaluation-BLnJp8vj.d.ts → funnel-node-evaluation-D9FwkMa3.d.ts} +425 -1
  25. package/dist/funnel-process-client-bO9Wfumi.d.ts +62372 -0
  26. package/dist/funnel-runtime-host-FOM4Z7ZK.js +1 -0
  27. package/dist/index.d.ts +322 -23334
  28. package/dist/index.js +1 -1
  29. package/dist/native-shell.js +1 -1
  30. package/dist/openrouter.d.ts +2 -2
  31. package/dist/openrouter.js +1 -1
  32. package/dist/page.js +1 -1
  33. package/dist/paywall-OUIB7SVI.js +1 -0
  34. package/dist/popup.d.ts +2 -2
  35. package/dist/popup.js +1 -1
  36. package/dist/react-native.d.ts +41 -38098
  37. package/dist/react-native.js +1 -1
  38. package/dist/screen-renderer-ZNELQB64.js +1 -0
  39. package/dist/server.d.ts +6860 -298
  40. package/dist/server.js +1 -1
  41. package/dist/visual.js +1 -1
  42. package/package.json +1 -1
  43. package/dist/chunk-4ZUMMPHV.js +0 -1
  44. package/dist/chunk-EEZLS2YP.js +0 -1
  45. package/dist/chunk-JVQVQHV2.js +0 -6
  46. package/dist/chunk-KYXX676W.js +0 -1
  47. package/dist/chunk-LC2VUKYM.js +0 -1
  48. package/dist/chunk-N4HZ55YU.js +0 -1
  49. package/dist/chunk-PFHS7HK3.js +0 -17
  50. package/dist/chunk-VVW2J2GL.js +0 -1
  51. package/dist/funnel-process-client-C9EIwNTr.d.ts +0 -20575
  52. package/dist/funnel-runtime-host-FVOUCR35.js +0 -1
  53. package/dist/paywall-6Q3VLXXL.js +0 -1
  54. package/dist/screen-renderer-IZ3VJGU6.js +0 -1
  55. package/dist/{coupon-fA1QujHt.d.ts → coupon-Btz_KFKp.d.ts} +1 -1
@@ -1 +0,0 @@
1
- import{a as d,b as ee,l as B,o as te}from"./chunk-N4HZ55YU.js";import{b as Z}from"./chunk-E4LUW6KP.js";import{a as s}from"./chunk-26HU2HXU.js";import{a as G}from"./chunk-DSPLGTQI.js";import{Ha as $,S as X,a as z,b as Y,c as K,d as Q,e as j,f as M,g as W,n as L,ua as a,wa as H}from"./chunk-JVQVQHV2.js";var U=t=>{if(!Number.isSafeInteger(t)||t<0||t>=Number.MAX_SAFE_INTEGER)throw new s("INVALID_STATE","Installation sequence exhausted");return t+1},he=async t=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(t,e=>e.charCodeAt(0))))].map(e=>e.toString(16).padStart(2,"0")).join("");function _(t,e){return t.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new s("INVALID_STATE","Installation journal is invalid");return e({...n})})}function ne(t,e,n){let i=null,c=0,o=0,l=0,y=Promise.resolve(),P=!1;if(t&&(!n||z.parse(t.scope).projectId!==n.projectId||t.scope.environment!==n.environment))throw new s("SCOPE_MISMATCH","Push installation belongs to another scope");let g=()=>{if(P)throw new s("CLOSED","SDK client was destroyed");if(!t)throw new s("NOT_CONFIGURED","Configure this client's native Push host first");return t},b=r=>{if(r!==c)throw new s("IDENTITY_CHANGED","Identity changed during Push operation")};async function D(r){let u=g();if(!u.sha256&&!globalThis.crypto?.subtle)throw new s("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let p=u.sha256?await u.sha256(Uint8Array.from(r,I=>I.charCodeAt(0))):await he(r);if(!/^[a-f0-9]{64}$/.test(p))throw new s("INVALID_STATE","Push credential digest is invalid");return p}function m(r){let u=M.parse(r);if(u.installationId.toLowerCase()!==g().installationId.toLowerCase())throw new s("INVALID_RESPONSE","Push response belongs to another installation");return u}async function C(r,u){let p=g(),I={installationId:p.installationId,publicKey:p.publicKey,issuedAt:new Date().toISOString(),...u},S=await p.sign(W(r,p.scope,I));return{...I,signature:S}}let f=(r,u,p)=>e.requestWithCredential?e.requestWithCredential(r,u,p):e.request(r,u);async function w(){let r=g(),u=c,p=i?await(e.session?.access()??i):null,I=_(r,v=>v),S;if(I.detachSeq!==null){let v=I.detachSeq,V=Y.parse(await C("detach",{sequence:v,platform:r.platform}));try{let N=await e.request("push/installations/detach",{...r.scope,...V},"POST",{installationDetach:!0});if(!N||typeof N!="object"||!("installation"in N))throw new s("INVALID_RESPONSE","Push detach acknowledgement is invalid");let F=m(N.installation);if(F.bound||F.identitySeq!==v)throw new s("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(N){if(N instanceof s&&N.status===404)S=N;else if(!(N instanceof s)||N.status!==412)throw N}S||_(r,N=>({...N,detachSeq:N.detachSeq===v?null:N.detachSeq}))}if(b(u),!p){if(S)throw S;return null}let q=a.bindPushInstallation,k=q.request.parse(await C("bind",{sequence:l,platform:r.platform,credentialDigest:await D(p)}));b(u);let R=q.response.parse(await f(q.path,k,p));b(u);let T=m(R.installation);if(!T.bound||T.identitySeq!==l)throw new s("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return S&&I.detachSeq!==null&&l>I.detachSeq&&_(r,v=>({...v,detachSeq:v.detachSeq===I.detachSeq?null:v.detachSeq})),T}async function E(){g();let r=c,u=i?await(e.session?.access()??i):null;if(!u)throw new s("NOT_IDENTIFIED","Identify before reading this installation");let p=a.readPushInstallation,I=p.request.parse(await C("read",{credentialDigest:await D(u)}));b(r);let S=p.response.parse(await f(p.path,I,u));return b(r),m(S.installation)}function h(r=w){let u=y.catch(()=>{}).then(r);return y=u,u.catch(p=>{try{t?.onError?.(p instanceof Error?p:new Error("Push synchronization failed"))}catch{}}),u}async function O(r,u,p){let I=g(),S=u.identity,q=u.observation,k=i?await(e.session?.access()??i):null;if(b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");if(!k)throw new s("NOT_IDENTIFIED","Identify before recovering a Push address");if(!r.connectionId||!r.kind||!r.token||!["granted","provisional"].includes(r.permission))throw new s("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await h(async()=>{if(b(S),await w(),b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");let R=_(I,F=>p?F:{...F,addressSeq:U(F.addressSeq)}),v=await C(p?"recovery_confirm":"recovery_request",{...r,sequence:R.addressSeq,credentialDigest:await D(k),...p?{challenge:p}:{}}),V=p?Q.parse(v):K.parse(v);if(b(S),q!==o)throw new s("INVALID_STATE","Push observation changed during recovery");let N=await f(`push/installations/recovery/${p?"confirm":"request"}`,V,k);if(b(S),q!==o||_(I,F=>F).addressSeq!==R.addressSeq)throw new s("INVALID_STATE","Push observation changed during recovery");if(p){let F=a.updatePushAddress.response.parse(N),x=m(F.installation);if(!x.bound||x.identitySeq!==l||x.addressSeq!==R.addressSeq||x.connectionId!==r.connectionId||x.addressStatus!=="active")throw new s("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return x}if(!N||typeof N!="object"||!("recovery"in N))throw new s("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return j.parse(N.recovery)})}return{recoveryObserver(){g();let r={identity:c,observation:++o};return{async request(u){return j.parse(await O(u,r))},async confirm(u,p){return M.parse(await O(p,r,u))}}},identify(r){if(!t)return;l=_(t,p=>({...p,identitySeq:U(p.identitySeq)})).identitySeq,i=r,c++,o++},reset(){if(t)try{_(t,r=>{let u=U(r.identitySeq);return{...r,identitySeq:u,detachSeq:u}})}finally{i=null,c++,o++}},start(){t&&!P&&h()},destroy(){P=!0,i=null,c++,o++},async sync(){return await h()},read:E,async recover(){let r=g(),u=c,p=l;return o++,await h(async()=>{b(u);let I=await E();return b(u),l=_(r,q=>{if(q.identitySeq!==p)throw new s("IDENTITY_CHANGED","A newer installation intent exists");return{...q,identitySeq:U(Math.max(q.identitySeq,I.identitySeq)),addressSeq:Math.max(q.addressSeq,I.addressSeq)}}).identitySeq,await w()})},tokenObserver(){g();let r=++o,u=c;return async p=>{if(r!==o||u!==c)return null;let I=g(),S=i?await(e.session?.access()??i):null;if(!S)throw new s("NOT_IDENTIFIED","Identify before registering a Push token");if(await h(),b(u),r!==o)return null;let q=_(I,v=>({...v,addressSeq:U(v.addressSeq)})),k=a.updatePushAddress,R=k.request.parse(await C("address",{...p,sequence:q.addressSeq,credentialDigest:await D(S)}));if(b(u),r!==o)return null;let T=await f(k.path,R,S);return b(u),r!==o||_(I,v=>v).addressSeq!==q.addressSeq?null:m(k.response.parse(T).installation)}}}}function re(t,e){let n={async preference(i){let c=a.readMessagingPreference;return(await d(t,c,{channel:i})).preference},async setPreference(i){let c=a.setMessagingPreference;return(await d(t,c,i)).preference}};return{messaging:n,push:{sync:e.sync,read:e.read,recover:e.recover,tokenObserver:e.tokenObserver,recoveryObserver:e.recoveryObserver,async preference(){return n.preference("push")},async setPreference(i){return n.setPreference({...i,channel:"push"})}}}}function ie(t,e,n={}){let i=!1;function c(){if(i)throw new s("CLOSED","SDK client was destroyed")}let o=new Set,l=P=>{for(let g of o)try{g(P)}catch{}},y=t.session.subscribeIdentity(()=>{l(!!t.session.peek()),n.afterChange?.()},()=>{e()});return{assertActive:c,isIdentified:()=>!i&&!!t.session.peek(),methods:{subscribeIdentity(P){return c(),o.add(P),()=>{o.delete(P)}},identify(P){c();let g=typeof P=="string"?P:P.accessToken;if(!L.test(g))throw new s("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(g),t.identify(P)},reset(){if(!i)try{n.beforeReset?.()}finally{t.reset()}},destroy(){if(!i){i=!0,y(),o.clear();try{n.beforeDestroy?.(),e()}finally{t.dispose()}}}}}}function A(t){if(t!==null&&typeof t=="object"&&"customerId"in t)throw new s("INVALID_REQUEST","Customer requests use the verified session identity")}var ge={...a.readHoldings,request:a.readHoldings.request.omit({customerId:!0})};function se(t){return{async checkEntitlement(e){A(e);let n=a.checkEntitlement;return d(t,n,e)},async readHoldings(e={}){return d(t,ge,e)}}}function oe(t){return{async readLedger(e){let n=a.readLedger;return d(t,n,{query:e})},async readCreditStatement(e){A(e);let n=a.readCreditStatement;return d(t,n,e)},async quoteBalance(e){A(e);let n=a.quoteBalance;return d(t,n,{command:e})}}}function ae(t){return{async setupPayment(e){A(e);let n=a.setupPayment;return d(t,n,e)},async readPaymentSetup(e){A(e);let n=a.readPaymentSetup;return d(t,n,e)},async readBillingInvoice(e){A(e);let n=a.readBillingInvoice;return d(t,n,e)},async readBillingControls(e={}){A(e);let n=a.readBillingControls;return d(t,n,e)},async prepareBillingAuthorization(e){A(e);let n=a.prepareBillingAuthorization;return d(t,n,e)},async confirmBillingAuthorization(e){A(e);let n=a.confirmBillingAuthorization;return d(t,n,e)},async setBillingCoupons(e){A(e);let n=a.setBillingCoupons;return d(t,n,e,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(e){A(e);let n=a.revokeBillingAuthorization;return d(t,n,e)},async listBillingInvoices(e={after:null,limit:25}){A(e);let n=a.listBillingInvoices;return d(t,n,e)},async confirmBillingAdjustment(e){A(e);let n=a.confirmBillingAdjustment;return d(t,n,e)}}}function ce(t){return{async previewUpdate(e){A(e);let n=a.previewUpdate;return d(t,n,e)},async update(e){A(e);let n=a.update;return d(t,n,e)},async readSubscriptionUpdate(e){A(e);let n=a.readSubscriptionUpdate;return d(t,n,e)},async restoreNativePurchase(e){A(e);let n=a.restoreNativePurchase;return d(t,n,e)},async previewAttach(e){A(e);let n=a.previewAttach;return d(t,n,e)},async attach(e){A(e);let n=a.attach;return d(t,n,e)},async readSubscriptionOperation(e){A(e);let n=a.readSubscriptionOperation;return d(t,n,e)}}}function ue(t){return{async redeemReward(e){return A(e),(await d(t,a.redeemReward,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(e){return A(e),(await d(t,a.claimRewardProduct,e,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(e){return A(e),(await d(t,a.createReferralCode,{...e,requestId:e.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(e,n=crypto.randomUUID()){let i=await d(t,a.redeemCoupon,{code:e,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:i.offer,reason:i.reason}},async claimCoupon(e,n=crypto.randomUUID()){let i=await d(t,a.grantOffer,{couponId:e,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:i.offer,reason:i.reason}},async listOffers(){return(await d(t,a.listOffers,{},{response:"Invalid offers response"})).offers}}}function de(t){return{...se(t),...oe(t),...ae(t),...ce(t),...ue(t)}}function pe(t){return{async resolveContent(e){A(e);let n=a.resolveContent;return d(t,n,e)},async resolvePaywall(e){A(e);let n=a.resolvePaywall;return d(t,n,e)},async resolveOffering(e){A(e);let n=a.resolveOffering;return d(t,n,e)}}}var J=t=>new TextEncoder().encode(JSON.stringify(t)).length,le=16384;function fe(t,e){let n=0,i,c=f=>{i={config:structuredClone(f),until:Date.now()+3e4}},o=[],l=null,y;function P(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}function g(){y||!o.length||(y=setTimeout(()=>{y=void 0,D().catch(()=>{}).finally(g)},5e3),typeof y=="object"&&"unref"in y&&y.unref())}function b(f,w={},E={}){if(P(),i&&Date.now()<i.until&&!X(i.config,f))return;C();let h=a.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:f,properties:w,...E}]}).events[0];if(J({events:[h]})>le)throw new s("INVALID_REQUEST","Event exceeds the delivery size limit");if(o.length>=500)throw new s("EVENT_QUEUE_FULL","Flush pending events before tracking more");o.push(structuredClone(h)),g()}async function D(f=!1){if(P(),l)return l;let w=n,E=(async()=>{let h={inserted:0,duplicates:0,rejected:0,skipped:0},O=o.length;for(;O&&w===n;){let r=[],u=J({events:[]});for(let S of o.slice(0,Math.min(O,100))){let q=J(S)+(r.length?1:0);if(r.length&&u+q>le)break;r.push(S),u+=q}let p=a.trackEvents,I=await d(t,p,{events:r},void 0,{keepalive:f});if(w!==n)throw new s("IDENTITY_CHANGED","Event identity changed during delivery");if(I.inserted+I.duplicates+I.rejected+I.skipped!==r.length)throw new s("INVALID_RESPONSE","Incomplete event acknowledgement");c(I.analyticsConfig),o.splice(0,r.length),O-=r.length,h.inserted+=I.inserted,h.duplicates+=I.duplicates,h.rejected+=I.rejected,h.skipped+=I.skipped}return h})();l=E;try{return await E}finally{l===E&&(l=null)}}let m;function C(){if(m||typeof document>"u")return;let f=()=>{document.visibilityState==="hidden"&&e()&&o.length&&D(!0).catch(()=>{})};document.addEventListener("visibilitychange",f),m=()=>document.removeEventListener("visibilitychange",f)}return{rememberConfiguration:c,track:b,flush:D,reset(){n++,i=void 0,clearTimeout(y),y=void 0,o=[],l=null},detachVisibility(){m?.(),m=void 0}}}function me(t){let e=t.merchandise;if(typeof t.merchandiseId=="string")return{internalId:t.merchandiseId};if(!(!e||typeof e!="object"||Array.isArray(e))){if(typeof e.internalId=="string")return{internalId:e.internalId};if(typeof e.externalId=="string")return{id:e.externalId};if(typeof e.id=="string")return{id:e.id}}}function we(t){let e=me(t),{merchandiseId:n,merchandise:i,...c}=t;return{...c,...e?{merchandise:e}:{}}}function ye(t,e,n,i,c){if(c&&i&&(c.scope.projectId!==i.projectId||c.scope.environment!==i.environment))throw new s("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=0,l=new Set;function y(){if(!e())throw new s("NOT_IDENTIFIED","Call identify before using Features or events")}async function P(g={}){c||y();let b=o,D=!1,m=async()=>{if(D||b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");let R=a.getFeatures,T=c?{scope:{projectId:c.scope.projectId,environment:c.scope.environment},payload:await c.features()}:await d(t,R,{});if(b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");if(i&&(T.scope.projectId!==i.projectId||T.scope.environment!==i.environment))throw new s("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(T.payload.analyticsConfig),T},C=await m(),f=!0,w,E=R=>{try{g.onError?.(R)}catch{}},h=(R,T,v)=>{try{let V=me(v);n.track(R,T,V?{merchandise:V}:{})}catch(V){E(V)}},O=ee({assertUsable:c?.assertFeatures,scope:C.scope,attributes:g.attributes,onError:g.onError,load:async()=>f?(f=!1,C.payload):(await m()).payload,evaluateRemote:async R=>{if(b!==o)throw new s("IDENTITY_CHANGED","Feature identity changed");let T=a.evaluateFeatures,v=await d(t,T,{...R,attributes:we(R.attributes)});if(v.scope.projectId!==C.scope.projectId||v.scope.environment!==C.scope.environment)throw new s("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:v.generation,evaluatedAt:v.evaluatedAt,expiresAt:v.expiresAt,features:v.features,...v.merchandiseContext?{merchandiseContext:v.merchandiseContext}:{}}},onExperimentViewed:(R,T,v)=>h("Experiment Viewed",{experimentId:R.key,variationId:T.key},v),onFeatureUsage:(R,T,v)=>h("Feature Evaluated",{feature:R,value:T.value,source:T.source,ruleId:T.ruleId,...T.experimentResult?{variationId:T.experimentResult.key}:{}},v)}),r=O.refresh;function u(){clearTimeout(w),!c&&(D||b!==o||!O.expiresAt||(w=setTimeout(()=>{p().catch(E)},Math.min(2147483647,Math.max(1e3,Date.parse(O.expiresAt)-Date.now()))),typeof w=="object"&&"unref"in w&&w.unref()))}async function p(){try{return await r()}finally{u()}}let I=()=>{D||p().catch(E)},S=O.subscribe(u),q=c?.subscribe(()=>{!D&&c.fresh&&p().catch(E)});function k(){D||(D=!0,clearTimeout(w),typeof window<"u"&&window.removeEventListener("focus",I),S(),q?.(),O.reset(),l.delete(k))}l.add(k);try{await O.init(),(g.attributes?.merchandise||g.attributes?.merchandiseId)&&await O.refreshRemote()}catch(R){throw k(),R}return u(),!c&&typeof window<"u"&&window.addEventListener("focus",I),Object.assign(O,{refresh:p,destroy:k})}return{features:P,reset(g){o++,g();for(let b of l)b()}}}import{z as ve}from"zod";function Ie(t,e){let n="source"in e?{funnelId:e.source.id,funnelVersionId:e.source.versionId}:"versionId"in e?{funnelId:e.funnelId,funnelVersionId:e.versionId}:e,i=ve.object({funnelId:H.shape.id,funnelVersionId:H.shape.versionId.optional()}).safeParse(n);if(!i.success)throw new s("INVALID_REQUEST","A valid Funnel source is required");let c=Object.freeze(i.data);function o(l){if("customerId"in l)throw new s("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in l&&l.funnelId!==void 0&&l.funnelId!==c.funnelId||"funnelVersionId"in l&&l.funnelVersionId!==void 0&&l.funnelVersionId!==c.funnelVersionId)throw new s("SCOPE_MISMATCH","The original Funnel source cannot change");return{...l,...c}}return{async claimCoupon(l,y=crypto.randomUUID()){let P=a.grantOffer,g=await d(t,P,o({couponId:l,requestId:y}));return{offer:g.offer,reason:g.reason}},async resolveOffering(l){let y=a.resolveOffering;return d(t,y,o(l))},async resolvePaywall(l){let y=a.resolvePaywall;return d(t,y,o(l))},async previewAttach(l){let y=a.previewAttach;return d(t,y,o(l))}}}function Dt(t){return Ae(t)}function Ae(t){let e=Z(t),n=e.request,i;try{i=ne(t.push,e,t.scope??t.configuration?.scope)}catch(y){throw e.dispose(),y}let c=ie(e,()=>{l.reset(o.reset),o.detachVisibility()},{beforeIdentify:i.identify,beforeReset:i.reset,afterChange:i.start,beforeDestroy:i.destroy}),o=fe(n,c.isIdentified),l=ye(n,c.isIdentified,o,t.scope,t.configuration);return{session:e.session,...re(n,i),...de(n),...pe(n),forFunnel(y){return c.assertActive(),Ie(n,y)},async features(y={}){return c.assertActive(),l.features(y)},track(y,P,g={}){return o.track(y,P,g)},flush(){return o.flush()},...c.methods}}function Ut(t){if(!L.test(t.customerToken))throw new s("INVALID_TOKEN","A customer credential is required");if(!t.scope)throw new s("INVALID_REQUEST","An explicit App and environment scope is required");let e=te({...t,scope:t.scope,apiKey:t.customerToken});return{async start(n){let i=await e.start(n),c=B({...t,runToken:i.runToken});c.identify(t.customerToken);let o=i.run.instruction?.type==="evaluate_segment"?await c.get():i;return{...i,...o,controller:c}}}}function Gt(t){if(!t.scope)throw new s("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(t.session!==void 0)throw new s("INVALID_CONFIGURATION","The merchant process adapter owns the session");let e=null,n,i=0,c=new Set,o=new Map,l=new Map;async function y(m){let C,f=new Promise((w,E)=>{C=setTimeout(()=>E(new s("TIMEOUT","Process bridge request timed out")),t.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),f])}finally{clearTimeout(C)}}function P(m){throw m instanceof s&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear()),m}function g(m,C){if(C!==i)throw new s("IDENTITY_CHANGED","Process was detached during a request");let f=$.parse(m);if(f.scope.projectId!==t.scope.projectId||f.scope.environment!==t.scope.environment)throw new s("SCOPE_MISMATCH","Process response belongs to another App/environment");if(e&&(e.run.id!==f.run.id||e.run.source.versionId!==f.run.source.versionId||e.run.source.id!==f.run.source.id||e.run.runExpiresAt!==f.run.runExpiresAt||e.run.identity.startedAs!==f.run.identity.startedAs||e.run.identity.participantId!==f.run.identity.participantId||e.run.identity.binding&&f.run.identity.binding&&e.run.identity.binding.id!==f.run.identity.binding.id))throw new s("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!e||f.run.revision>=e.run.revision){if(e?.run.identity.binding&&!f.run.identity.binding)throw new s("INVALID_RESPONSE","The process lost its Customer binding");e=f;for(let I of c)G(I,f.run);f.run.instruction?.type==="authentication_required"&&G(t.onAuthenticationRequired,f.run)}f.settlement?.accepted!==void 0&&l.set(f.settlement.requestId,f.settlement.accepted);let{identity:w,instruction:E,...h}=f.run,{contract:O,settlement:r,...u}=f,p=r&&(({accepted:I,...S})=>S)(r);return{...u,run:{...h,authenticated:w.binding!==null,instruction:E?.type==="authentication_required"?null:E},...p?{settlement:p}:{}}}let b=m=>(o.has(m)||o.set(m,e?.run.identity.binding?.id??null),o.get(m));async function D(m){let C=i,f=e?.run.identity.binding?.id??null,w=h=>{if(f!==(e?.run.identity.binding?.id??null))throw h;return P(h)};if(m.operation==="page_experiments"){if(!t.adapter.pageExperiments)throw new s("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return y(()=>t.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(w)}let E;if(m.operation==="get"){let{operation:h,customerToken:O,...r}=m;E=await y(()=>t.adapter.get({...r,...r.settlementRequestId?{settlementBindingId:b(r.settlementRequestId)}:{}})).catch(w)}else if(m.operation==="review")E=await y(()=>t.adapter.review(m.receiptId)).catch(w);else{if(m.operation==="start")throw new s("INVALID_REQUEST","Use process.open for entry");{let{customerToken:h,...O}=m;E=await y(()=>t.adapter.command(O,b(O.requestId))).catch(w)}}return g(E,C)}return{get view(){return e?.run??null},get controller(){return n},async open(m){let C=i,f=await y(()=>t.adapter.open(m)).catch(P);if(g(f,C),!n){n=B({...t,runToken:f.runToken,process:{request:D,binding:b,restore(h){for(let[O,r]of Object.entries(h))o.set(O,r)}}});let w=n,E=w.submit;w.submit=async h=>{try{return await E(h)}catch(O){if(!(O instanceof s)||O.reason!=="IDENTITY_CONTEXT_CHANGED"||h.operation!=="submit"||h.input.type!=="screen"||o.get(h.requestId)!==null)throw O;await w.settle?.(h.requestId),await w.get();let r=w.view;if(l.get(h.requestId)!==!1||!r||r.id!==e?.run.id||r.nodeId!==h.nodeId||r.visit!==h.visit||!e?.run.identity.binding)throw O;return E({...h,requestId:crypto.randomUUID(),revision:r.revision})}}}await n.get();for(let w of n.pendingCommands??[])o.has(w.requestId)&&o.get(w.requestId)!==(e?.run.identity.binding?.id??null)&&await n.settle?.(w.requestId);return{run:e.run,controller:n}},async syncIdentity(){let m=i;g(await y(()=>t.adapter.syncIdentity()).catch(P),m),await n?.get();for(let C of n?.pendingCommands??[])o.has(C.requestId)&&o.get(C.requestId)!==(e?.run.identity.binding?.id??null)&&await n?.settle?.(C.requestId);return e.run},async detach(){i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear(),await y(()=>t.adapter.detach())},forProcess(m){if(!e?.run.identity.binding)throw new s("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:e.run.id,bindingId:e.run.identity.binding.id,receiptId:m}},subscribe(m){return c.add(m),()=>{c.delete(m)}},destroy(){i++,n?.reset(),n=void 0,e=null,o.clear(),l.clear(),c.clear()}}}export{Dt as a,Ae as b,Ut as c,Gt as d};
@@ -1 +0,0 @@
1
- import{a as o}from"./chunk-26HU2HXU.js";function s(r,n){let i=structuredClone(r);for(let[a,e]of Object.entries(i.plans)){let t=n.plans[a];!t||t.versionId!==e.versionId||(t.amountMinor!==void 0&&(e.amountMinor=t.amountMinor),t.interval!==void 0&&(e.interval=t.interval),t.intervalCount!==void 0&&(e.intervalCount=t.intervalCount),t.prepaid!==void 0&&(e.prepaid=structuredClone(t.prepaid)))}return i}function c(r,n){let i=a=>"document"in a?a.offering.id:a.content.offeringVersionId;return r.id===n.id&&i(r)===i(n)&&r.content?.artifact.sha256===n.content?.artifact.sha256}function l(r,n,i){if(r.operationId!==n.operationId||n.currency!==void 0&&r.currency!==n.currency)throw new o("INVALID_RESPONSE",i)}function p(r,n,i){let a=Object.fromEntries((r.lines[0]?.prepaid??[]).map(e=>[e.internal_feature_id,e.quantity]));if(n.featureQuantities&&(Object.keys(a).length!==Object.keys(n.featureQuantities).length||Object.entries(n.featureQuantities).some(([e,t])=>a[e]!==t)))throw new o("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(r.lines.length!==1||r.lines[0].productVersionId!==n.productVersionId||n.currency!==void 0&&r.currency!==n.currency||n.provider!==void 0&&r.provider!==n.provider&&!(n.provider==="stripe"&&r.provider==="merchant"&&r.execution?.provider==="merchant"))throw new o("INVALID_RESPONSE",i)}function f(r,n,i=!1){return!r||r.operationId!==n?.operationId?n:r.status==="complete"&&n.status!=="complete"||r.status!=="pending"&&(n.status==="pending"||i&&n.status!=="complete")?r:n}export{s as a,c as b,l as c,p as d,f as e};
@@ -1 +0,0 @@
1
- import{b as dn,c as fn,d as mn,e as pn}from"./chunk-LC2VUKYM.js";import{a as gn}from"./chunk-EEZLS2YP.js";import{a as te,b as Y}from"./chunk-E4LUW6KP.js";import{a as m}from"./chunk-26HU2HXU.js";import{a as ln,b as cn,c as Ce}from"./chunk-LHBBSD77.js";import{$a as un,Ea as Te,Fa as tn,R as Ge,T as Re,Ta as rn,U as Be,Ua as on,V as Je,W as je,Xa as an,Ya as sn,a as Ue,cb as le,da as Q,ea as ze,fa as J,ga as Ke,ha as Oe,ia as M,ka as Qe,la as Ye,ma as $e,n as ue,na as We,oa as Ze,ua as ne,va as Xe,ya as en,za as nn}from"./chunk-JVQVQHV2.js";import{B as ve,Fa as He,v as qe,y as ke}from"./chunk-PFHS7HK3.js";function Bn(e){let n=null,t=null,s=0,d=0,w=new Set,f=null,o=null,g=new Set,i=()=>{for(let a of g)try{a()}catch{}},l={attributes:ve.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(a,r)=>{!w.has(a)&&(!n||!("analyticsConfig"in n)||n.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(a,structuredClone(r),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(a,r)=>(!n||!("analyticsConfig"in n)||n.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(a),structuredClone(r),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?a=>e.saveStickyBucketAssignmentDoc(structuredClone(a)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},u=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function c(a,r=new Set){return w.has(a)?!f||!f.features[a]||["unknownFeature","cyclicPrerequisite"].includes(f.features[a].source):r.has(a)?!1:(r.add(a),(n?.features[a]?.rules??[]).some(p=>[...p.parentConditions??[],...(p.tracks??[]).flatMap(v=>v.experiment.parentConditions??[])].some(v=>c(v.id,r))))}let h=a=>{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 f?.expiresAt&&Date.parse(f.expiresAt)<=Date.now()&&(f=null,l.features=n.features),w.has(a)?!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now()?u():structuredClone(f.features[a]??u()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!f||c(a)?u():structuredClone(ke(a,l))};async function A(){if(!n||!w.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(w.size)throw new Error("Remote Feature evaluation requires a server loader");return}let a=d;if(o?.revision===a)return o.loading;let r=s,p=n,v=[...w],C=(async()=>{let S=je.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:v}));if(!(r!==s||a!==d||p!==n)){if(e.assertUsable?.(p.generation),S.generation!==p.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(v.some(R=>!Object.hasOwn(S.features,R))||Object.keys(S.features).some(R=>!w.has(R)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!S.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=ve.parse({...l.attributes,...S.merchandiseContext})}f=structuredClone(S),l.features={...p.features,...Object.fromEntries(Object.entries(f.features).map(([R,O])=>[R,{defaultValue:O.value}]))},i()}})();o={revision:a,loading:C};try{await C}finally{o?.loading===C&&(o=null)}}function N(){A().catch(a=>{try{e.onError?.(a)}catch{}})}async function x(){if(t)return t;let a=s,r=(async()=>{let p=await e.load(),v="remoteFeatures"in p?Be.parse(p):null,C=v??Re.parse(p);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(a!==s)throw new Error("Feature client was reset");if(e.assertUsable&&n?.generation===C.generation){let{evaluatedAt:R,expiresAt:O,...D}=n,{evaluatedAt:L,expiresAt:k,...G}=C;if(M(D)!==M(G))throw new Error("Immutable Feature generation changed content");return n.evaluatedAt=C.evaluatedAt,n.expiresAt=C.expiresAt,i(),(!f||f.expiresAt&&Date.parse(f.expiresAt)<=Date.now())&&N(),structuredClone(n)}let S=new Set(v?.remoteFeatures??[]);if([...S].some(R=>Object.hasOwn(C.features,R)))throw new Error("Remote Feature definitions must not be delivered locally");return n&&"analyticsConfig"in n&&"analyticsConfig"in C&&!n.analyticsConfig.experimentViewsEnabled&&v?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),n=structuredClone(C),w=S,f=null,o=null,d++,l.features=n.features,l.savedGroups=qe(n.savedGroups),l.trackedFeatureUsage={},i(),N(),structuredClone(n)})();t=r;try{return await r}finally{t===r&&(t=null)}}return{init:x,refresh:x,refreshRemote:A,get generation(){return n?.generation??null},get expiresAt(){return n?.expiresAt??null},subscribe(a){return g.add(a),()=>{g.delete(a)}},setAttributes(a){let r=ve.parse(a);(l.attributes?.merchandise||l.attributes?.merchandiseId||a.merchandise||a.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=r,d++,f=null,o=null,l.features=n?.features??{},l.trackedFeatureUsage={},i(),N()},evalFeature:h,isOn(a){return h(a).on},isOff(a){return h(a).off},getFeatureValue(a,r){let p=h(a).value;return structuredClone(p===null?r:p)},reset(){s++,d++,t=null,o=null,n=null,f=null,w.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),i()}}}function yn(e){let n,t,s=()=>new m("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),d=Promise.resolve().then(async()=>{if(n=e.storage??globalThis.localStorage,t=e.locks??globalThis.navigator?.locks,!n||!t||!globalThis.crypto?.subtle)throw s();let o=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??le).href,e.runToken])),g=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return"indiana.funnel.commands.v1."+Array.from(g,i=>i.toString(16).padStart(2,"0")).join("")});d.catch(()=>{});async function w(o){try{let g=await d;return await t.request(g,{mode:"exclusive"},()=>o(g))}catch(g){throw g instanceof m?g:s()}}function f(o){let g=n.getItem(o);if(g===null)return{revision:0,entry:null};if(g.length>1048576)throw s();let i=JSON.parse(g);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw s();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>w(f),write:(o,g)=>w(i=>{if(f(i).revision!==o)return null;if(!Number.isSafeInteger(o+1))throw s();return n.setItem(i,JSON.stringify({revision:o+1,entry:g})),o+1})}}function be(e,n){let t=en.safeParse(n);if(!t.success)throw new m("INVALID_RESPONSE","Funnel response contract changed");let s=t.data;if(e.scope&&(s.scope.projectId!==e.scope.projectId||s.scope.environment!==e.scope.environment))throw new m("SCOPE_MISMATCH","Funnel scope changed");return s}async function Pe(e,n){let t=We.parse(n),{artifact:s,environmentId:d}=t.content,w=new te(e.baseUrl??le).origin,f=new te(s.url,w);if(f.origin!==w||f.username||f.password||f.search||f.hash||f.pathname!==`/api/v1/configuration/${d}/artifacts/${s.sha256}`)throw new m("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,g,i=new Promise((u,c)=>{g=setTimeout(()=>{let h=new m("TIMEOUT","Public Paywall read timed out");o.abort(h),c(h)},J.initializationMs)}),l=(async()=>{let u=await(e.fetch??globalThis.fetch)(f,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(u.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>s.byteLength)throw u.body?.cancel().catch(()=>{}),new m("INVALID_RESPONSE","Public Paywall is unavailable");let c=await ln(u,s.byteLength,{signal:o.signal,error:h=>new m("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!Ce(c,s))throw new m("INVALID_RESPONSE","Public Paywall digest or size changed");return Ze(t,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c)))})();try{return await Promise.race([l,i])}finally{clearTimeout(g)}}var _e=(e,n)=>new m(e,n);function ot(e){return sn(e,_e)}var Nn=3,On=2e3;function Tn(e){return e instanceof TypeError||e instanceof m&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function _n(e){for(let n=1;;n++)try{return await e.refresh()}catch(t){if(n===Nn||!Tn(t))throw t;await new Promise(s=>setTimeout(s,n*On))}}async function De(e,n,{predict:t=!0}={}){let s=n.instruction;if(s?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new m("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==s.environmentId)throw new m("SCOPE_MISMATCH","Evaluation environment changed");let d=null,w;if(t)try{let f=await e.funnel(n.source.id,n.source.versionId);w=f.manifest.generation,d=Dn(e,n,f)}catch{d=null}return w??=e.snapshot?.generation??(await _n(e)).generation,{advance:{policyRevision:s.policyRevision,generation:w},prediction:d}}function Dn(e,n,t){let s=n.instruction;if(s?.type!=="evaluate_segment"||!t.growth||t.control.evaluationMode!=="local"||t.control.evaluationRevision!==s.policyRevision)return null;let{analyticsConfig:d,remoteFeatures:w,...f}=t.growth,o=rn({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:n.source.id,versionId:n.source.versionId,evaluationMode:"local",evaluationRevision:s.policyRevision,document:t.document,payload:Re.parse(f)}),g=Ln(o,t.document,{...n,...s}),i=g.steps.at(-1),l=g.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:n.visit+g.steps.length-1}:null);return l?{runId:n.id,from:{nodeId:n.nodeId,visit:n.visit,revision:n.revision},nodeId:l.nodeId,visit:l.visit,terminal:!g.boundary}:null}function Ln(e,n,t){return un(e,n,t,_e)}import{z as j}from"zod";var wn=Q.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 m("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),In=j.strictObject({schemaVersion:j.literal(1),scope:Ue,runId:j.uuid(),funnelId:j.uuid(),versionId:j.uuid(),processBindingIds:j.record(j.uuid(),j.uuid().nullable()).optional(),command:wn.optional(),closeCommand:wn.refine(e=>e.operation==="close").optional(),purchase:j.strictObject({receiptId:j.uuid(),operationId:j.uuid(),generation:j.number().int().nonnegative()}).optional(),closed:j.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"),q=()=>new m("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),Se=(e,n)=>JSON.stringify(e)===JSON.stringify(n);function hn(e){let n=0,t=null,s=i=>JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]),d=Promise.resolve();async function w(){let i=await e.read();if(!Number.isSafeInteger(i.revision)||i.revision<0)throw new m("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:i.revision,entry:i.entry===null?null:In.parse(i.entry)}}function f(i){let l=d.then(i);return d=l.catch(()=>{}),l}async function o(i){for(let l=0;l<4;l++){let u=await w();if(u.entry&&t!==null&&s(u.entry)!==t)throw q();let c=i(u.entry,u.revision);if(Se(u.entry,c)){n=u.revision;return}let h=await e.write(u.revision,c);if(h!==null){if(!Number.isSafeInteger(h)||h<=u.revision)throw q();n=h;return}}throw q()}function g(i,l){if(!i||!l)return i;if(i.processBindingIds&&Object.hasOwn(i.processBindingIds,l)){let u={...i.processBindingIds};delete u[l],i={...i,processBindingIds:u}}return i.command?.requestId===l?i.closeCommand?{...i,command:i.closeCommand,closeCommand:void 0}:i.purchase?{...i,command:void 0}:null:i.closeCommand?.requestId===l?{...i,closeCommand:void 0}:i}return{bind(i){let l=JSON.stringify([i.scope,i.runId,i.funnelId,i.versionId]);if(t!==null&&t!==l)throw q();t=l},async load(){let i=await w();return n=i.revision,t=i.entry?s(i.entry):null,i.entry},retain(i){let l=In.parse(i),u=l.command;return!u||t!==null&&s(l)!==t?Promise.reject(q()):(t??=s(l),f(()=>o((c,h)=>{if(c&&!Se(s(c),s(l)))throw q();if(c&&l.processBindingIds){for(let[A,N]of Object.entries(l.processBindingIds))if(c.processBindingIds&&Object.hasOwn(c.processBindingIds,A)&&c.processBindingIds[A]!==N)throw q();c={...c,processBindingIds:{...c.processBindingIds,...l.processBindingIds}}}if(!c){if(h!==n&&u.operation!=="close")throw q();return l}if(!c.command)return{...c,command:u,...u.operation==="close"?{closed:!0}:{}};if(u.operation==="close"&&c.command.operation!=="close"){if(c.command.requestId===u.requestId||c.closeCommand&&!Se(c.closeCommand,u))throw q();return{...c,closeCommand:u,closed:!0}}if(!Se(c.command,u))throw q();return c})))},observePurchase(i,l,u,c){return f(()=>o((h,A)=>{if(!h&&A!==n||h&&s(h)!==s({...i,schemaVersion:1}))throw q();if(h?.purchase&&h.purchase.generation>l.generation)return g(h,c);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw q();return u?!h?.purchase||h.purchase.operationId!==l.operationId?g(h,c):g(h.command?{...h,purchase:void 0}:null,c):g({schemaVersion:1,...i,...h,purchase:l},c)}))},settle(i){return f(()=>o(l=>g(l,i)))}}}function pt(e,n){return n.type==="id"?e.customerId===n.value:e.externalUserId===n.value}function ce(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((d,w)=>ce(d,n[w]));if(!e||!n||typeof e!="object"||typeof n!="object")return!1;let t=Object.entries(e),s=Object.entries(n);return t.length===s.length&&t.every(([d,w])=>Object.hasOwn(n,d)&&ce(w,Reflect.get(n,d)))}function vn(e,n){let t=n&&{...n},s=null,d=0,w=new AbortController;function f(){d++,w.abort(new m("IDENTITY_CHANGED","Run identity changed")),w=new AbortController}let o=!1,g,i=0,l=new Set;return{get scope(){return t},bindScope(u){if(t&&(t.projectId!==u.projectId||t.environment!==u.environment))throw new m("SCOPE_MISMATCH","Run scope changed");t??={...u}},get view(){return s},get generation(){return d},get signal(){return w.signal},get disposed(){return o},get customerToken(){return g},get readSequence(){return i},nextRead(){return++i},assertCurrent(u,c="Run identity changed during the request"){if(u!==d||o)throw new m("IDENTITY_CHANGED",c)},assertRun(u){if(s&&(u.id!==s.id||u.source.type!==s.source.type||u.source.id!==s.source.id||u.source.versionId!==s.source.versionId||u.locale!==s.locale||!ce(u.parameters,s.parameters)))throw new m("INVALID_RESPONSE","Run version changed");if(e&&u.source.id!==e)throw new m("INVALID_RESPONSE","Run belongs to another Funnel")},publish(u,c,h,A,N){if(!(u.operation==="review"&&s&&s!==h&&c.run.revision<=s.revision)&&!(s&&c.run.revision===s.revision&&A!==void 0&&A<i)&&(u.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&s&&c.run.nodeId===s.nodeId&&c.run.visit===s.visit&&c.run.revision===s.revision&&(c.run.screen=s.screen,(s.paywall?.quote?.operationId===c.review?.activeOperationId||!s.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=s.paywall)),!(s?.paywall&&c.run.paywall&&s.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(s.paywall.selectionGeneration??0)))){if(!s||c.run.revision>=s.revision)s=c.run;else if(!N)return;if(s)for(let x of l)try{x(structuredClone(s))}catch{}}},identify(u){if(o)throw new m("IDENTITY_CHANGED","Controller was reset");if(!ue.test(u))throw new m("INVALID_TOKEN","Customer credential required");f(),g=u},subscribe(u){return l.add(u),()=>l.delete(u)},reset(){o||(o=!0,f(),g=void 0,s=null,l.clear())}}}var re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Rt(e,n,t="A server API key is required"){if(typeof window<"u")throw new m("SERVER_ONLY",n);if(!re.test(e))throw new m("INVALID_TOKEN",t)}function Ct(e){let n=Y(e);return n.identify(e.apiKey),n}function $(e){let{customerToken:n,...t}=e;return t}var xn=e=>!(e instanceof m)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function Rn({journal:e,state:n,call:t,processIdentity:s}){let d=null,w=null,f=!1,o={command:null,close:null},g=new Set,i,l=null,u=e?e.load().then(a=>{if(n.disposed)throw new m("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=a,!a)return;if(s){if([a.command,a.closeCommand].some(p=>p&&!Object.hasOwn(a.processBindingIds??{},p.requestId)))throw new m("COMMAND_STORAGE_INVALID","The original process identity is missing");s.restore(a.processBindingIds??{})}if(n.scope&&(a.scope.projectId!==n.scope.projectId||a.scope.environment!==n.scope.environment))throw new m("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=a.purchase,f=a.closed===!0,!a.command)return;let r=a.command;d=r.operation==="close"?null:r,w=r.operation==="close"?r:a.closeCommand?.operation==="close"?a.closeCommand:null,w&&(f=!0);for(let p of[d,w])p&&g.add(p.requestId)}):Promise.resolve();u.catch(()=>{});async function c(a){e&&await u;let r=n.generation;if(e){if(!n.view||!n.scope)throw new m("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:n.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:$(a),...s?{processBindingIds:{[a.requestId]:s.binding(a.requestId)}}:{}})}if(r!==n.generation||d!==a&&w!==a)throw new m("IDENTITY_CHANGED","Run changed before command dispatch");let p=g.has(a.requestId);g.add(a.requestId);try{return await t(a)}catch(v){throw r===n.generation&&(d===a||w===a)&&!p&&!xn(v)&&(e&&await e.settle(a.requestId),r===n.generation&&x(a)),v}}function h(a){let r=Q.parse(a);if(r.operation==="start"||r.operation==="get"||r.operation==="review")throw new m("INVALID_REQUEST","Mutation required");if(f&&r.operation!=="close"){if(d?.requestId===r.requestId)return N(r.requestId);throw new m("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(r.operation==="close"){if(d?.requestId===r.requestId)throw new m("INVALID_REQUEST","Close requires its own request identity");if(f=!0,w&&JSON.stringify($(w))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original Close");return w??=r,o.close?o.close:A(w,"close")}if(d){if(JSON.stringify($(d))!==JSON.stringify($(r)))throw new m("COMMAND_PENDING","Retry the original command before sending another");if(o.command)return o.command}else d=r;return A(d,"command")}function A(a,r){let p=c(a);o[r]=p;let v=()=>{o[r]===p&&(o[r]=null)};return p.then(v,v),p}function N(a){return t({operation:"get",settlementRequestId:a})}function x(a){return!a||d!==a&&w!==a?!1:(d===a&&(d=null),w===a&&(w=null),g.delete(a.requestId),!d&&!w&&(l=null),!0)}return{ready:u,get pending(){return d},get closing(){return w},get closeRequested(){return f},get inFlight(){return o.command},get closeFlight(){return o.close},get purchase(){return i},assertBinding(a){if(l&&(a.run.id!==l.runId||a.run.source.id!==l.funnelId||a.run.source.versionId!==l.versionId))throw new m("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(a,r,p,v){let C=a.operation==="get"?a.settlementRequestId:"requestId"in a&&a.operation!=="start"?a.requestId:void 0,S=C&&r.settlement?.state==="settled"&&r.run.pendingRequest?.requestId!==C&&(a.operation==="get"||!f||a.operation==="close"||!["running","waiting"].includes(r.run.status))?C:void 0,R=d?.requestId===S?d:w?.requestId===S?w:void 0;e?.bind({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId});let O=r.run.paywall,D=O??r.purchase,L=D?.operation,k=r.settlement&&(!O||O.purchaseRequestId===r.settlement.requestId)&&(!i||i.operationId===r.settlement.operationId)?r.settlement:void 0,G=L?.operationId??D?.quote?.operationId??k?.operationId,H=D?.receiptId??k?.receiptId,de=O?.selectionGeneration??i?.generation??0;if(e&&G&&H&&a.operation!=="review"&&(!n.view||r.run.revision>=n.view.revision)&&(v===void 0||v>=n.readSequence)&&(!i||de>=i.generation)){let Z={receiptId:H,operationId:G,generation:de},fe=L?.status==="complete"||D?.canReselect===!0;await e.observePurchase({scope:r.scope,runId:r.run.id,funnelId:r.run.source.id,versionId:r.run.source.versionId},Z,fe,S),n.assertCurrent(p),(!i||Z.generation>=i.generation)&&(v===void 0||v>=n.readSequence)&&(fe?i?.operationId===Z.operationId&&(i=void 0):i=Z)}else e&&S&&await e.settle(S);return n.assertCurrent(p),S?x(R):!1},stop(){f=!0},submit:h,settle:N,reset(){f=!0,d=null,w=null,i=void 0,l=null,o.close=null,g.clear(),o.command=null}}}function Cn(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new m("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!re.test(e.serverKey)))throw new m("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new m("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let n=Y({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),t=vn(e.funnelId,e.scope??e.configuration?.scope),s=e.session?.subscribeIdentity(i),d=null,w=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?yn(e):void 0),f=w&&hn(w),o=Rn({journal:f,state:t,call:l,processIdentity:e.process});async function g(r){if(e.process)return e.process.request(r);let p=t.generation;t.assertCurrent(p);let v=performance.now()+(e.timeoutMs??35e3),C=t.customerToken??("customerToken"in r?r.customerToken:void 0);if(e.session){let O=t.signal,D,L=()=>{},k=new Promise((G,H)=>{L=()=>H(O.reason),O.addEventListener("abort",L,{once:!0}),D=setTimeout(()=>H(new m("TIMEOUT","Longplay request timed out")),Math.max(1,v-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(t.assertCurrent(p),e.session.access())),k])}finally{clearTimeout(D),O.removeEventListener("abort",L)}}t.assertCurrent(p);let S={...r,...C?{customerToken:C}:{}},R=r.operation==="page_experiments"?Te.parse(S):Q.parse(S);return n.requestWithCredential("funnels",R,e.runToken,{headers:e.serverKey&&!C?{[nn]:e.serverKey}:void 0,timeoutMs:Math.max(1,v-performance.now())})}function i(){s?.(),t.reset(),o.reset(),d=null,n.dispose()}async function l(r,p){let v=t.generation,C=()=>t.assertCurrent(v);f&&await o.ready,C();let S=t.view,R=be(e,await g(r));if(r.operation==="review"&&!R.review)throw new m("INVALID_RESPONSE","Historical projection is missing");if(C(),R.runToken&&R.runToken!==e.runToken)throw new m("INVALID_RESPONSE","Run credential changed");let O=r.operation==="get"?r.settlementRequestId:"requestId"in r&&r.operation!=="start"?r.requestId:void 0;if(O&&R.settlement?.requestId!==O)throw new m("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");o.assertBinding(R),t.assertRun(R.run),t.bindScope(R.scope);let D=await o.observe(r,R,v,p);return!R.run.stopped&&["running","waiting"].includes(R.run.status)&&r.operation==="get"&&r.settlementRequestId||(C(),["running","waiting"].includes(R.run.status)||o.stop(),t.publish(r,R,S,p,D)),R}let u=o.submit,c=null,h=new WeakMap;function A(r){let p=h.get(r);if(p)return p;let v=x(r);return h.set(r,v),v}let N=!1;async function x(r){let p=await r;if(p.run.instruction?.type!=="evaluate_segment")return p;if(c)return c;N=!0;let v=t.generation,C=(async()=>{for(let S=0;S<32&&p.run.instruction?.type==="evaluate_segment";S++){if(o.pending||o.closeRequested)return p;let R=p.run;if(p.run.instruction?.type==="evaluate_segment"){let{advance:D}=await De(e.configuration,R,{predict:!1});if(v!==t.generation)throw new m("IDENTITY_CHANGED","Run identity changed during segment calculation");if(o.pending||o.closeRequested)return p;if(t.view&&(t.view.revision!==R.revision||t.view.visit!==R.visit||t.view.nodeId!==R.nodeId))return l({operation:"get"});let L=!0;De(e.configuration,R).then(({prediction:k})=>{L&&v===t.generation&&!o.closeRequested&&t.view?.id===R.id&&!t.view.stopped&&t.view.nodeId===R.nodeId&&t.view.visit===R.visit&&t.view.revision===R.revision&&(d=k)}).catch(()=>{});try{p=await u({operation:"commit_segment",requestId:Xe(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...D})}finally{L=!1,d=null}}}return p})();c=C;try{return await C}finally{c===C&&(c=null)}}let a={get configuration(){return N?e.configuration:void 0},get configurationReady(){return!0},get view(){return t.view?structuredClone(t.view):null},get pendingCommand(){let r=o.closing??o.pending;return r?structuredClone($(r)):null},get pendingCommands(){return[o.pending,o.closing].filter(r=>r!==null).map(r=>structuredClone($(r)))},get pendingPurchase(){return o.purchase?structuredClone(o.purchase):null},get hasDurableJournal(){return f!==void 0},get prediction(){let r=t.view;return d&&r&&!r.stopped&&["running","waiting"].includes(r.status)&&r.id===d.runId&&r.nodeId===d.from.nodeId&&r.visit===d.from.visit&&r.revision===d.from.revision&&!o.closeRequested?structuredClone(d):null},settle:o.settle,get webViewUrl(){return"bundled"},resolvePaywall(r){return Pe(e,r)},async pageExperiments(r,p=[]){let v=t.generation;t.assertCurrent(v);let C=t.view?.id;if(!C)throw new m("INVALID_REQUEST","Read the Run before its page experiments");let S=tn.parse(await g(Te.parse({operation:"page_experiments",release:r,usedReceiptIds:p})));if(t.assertCurrent(v),S.runId!==C||S.scope.projectId!==t.scope?.projectId||S.scope.environment!==t.scope?.environment)throw new m("SCOPE_MISMATCH","Page experiment Run changed");return S},review(r){return l({operation:"review",...r?{receiptId:r}:{}},t.nextRead())},async get(r,p){f&&await o.ready,p??=o.purchase&&{receiptId:o.purchase.receiptId,operationId:o.purchase.operationId};let v=t.nextRead();return A(l({operation:"get",...r?{data:r}:{},...p?{purchase:p}:{}},v))},resume(r=t.view?.pendingRequest?.requestId){return r?o.closeRequested?a.settle(r):o.pending?.requestId===r?A(u(o.pending)):A(u({operation:"resume",requestId:r})):Promise.reject(new m("INVALID_REQUEST","No interrupted command is available"))},submit(r){return A(u(r))},retry(){return o.closeFlight?o.closeFlight:o.closing?u(o.closing):o.closeRequested&&o.pending?a.settle(o.pending.requestId):o.inFlight?A(o.inFlight):o.pending?A(u(o.pending)):Promise.reject(new m("INVALID_REQUEST","No command is pending"))},identify(r){t.identify(r),d=null,n.reset()},subscribe:t.subscribe,reset:i};return a}import{ZodError as Vn}from"zod";function bn(e,n,t,s){try{return e.parse(n)}catch(d){throw s&&d instanceof Vn?new m(t,s):d}}async function Ee(e,n,t,s={},d){let w=typeof s=="function"?{}:s,f=bn(n.request,t,"INVALID_REQUEST",w.request);try{let o=await e(n.path,f,n.method,d),g=typeof s=="function"?s:s.parseResponse;return g?g(n.response,o):bn(n.response,o,"INVALID_RESPONSE",w.response)}catch(o){throw o instanceof m&&f!==null&&typeof f=="object"&&"requestId"in f&&typeof f.requestId=="string"&&(o.commandRequestId??=f.requestId),o}}async function Yt(e,n){if(!ue.test(n.customerToken))throw new m("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==n.customerToken)throw new m("SCOPE_MISMATCH","Paywall credential does not match the shared session");let t=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}:{}}),s=Y(e);e.session||s.identify(n.customerToken);let d=null,w=!1,f=null,o=null,g=null,i=null,l=null,u=null,c=null,h=0;function A(){if(w)throw new m("IDENTITY_CHANGED","Paywall is closed")}async function N(){A();let p=ne.resolvePaywall,v=await Ee(s.request,p,{...t,selector:d?{type:"version",versionId:d.id}:t.selector}),C=await Pe(e,v.paywall);if(A(),n.paywallVersionId?C.id!==n.paywallVersionId:C.paywallId!==n.paywallId)throw new m("INVALID_RESPONSE","The requested Paywall changed");if(d&&(!dn(C,d)||C.paywallId!==d.paywallId))throw new m("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return d=C,structuredClone(d)}async function x(p){if(A(),i&&p!=="read")throw new m("COMMAND_PENDING","Wait for the original quote");if(!f)throw new m("INVALID_REQUEST","A quoted purchase is required");let v=f;if(p!=="read"){if(c){if(u===p)return c;throw new m("COMMAND_PENDING","Wait for the original purchase command")}if(u&&u!==p)throw new m("COMMAND_PENDING","Read the original purchase before changing an uncertain command");u=p,h++}let C=u,S=h,R=p==="read"&&c===null,O=p==="read"?ne.readSubscriptionOperation:ne.attach,D=(async()=>{let L=await Ee(s.request,O,{operationId:v.operationId,...p==="read"?{}:{intent:p}});return fn(L.operation,{operationId:v.operationId,currency:t.commerce.currency},"The purchase operation changed"),A(),f?.operationId!==v.operationId?structuredClone(L.operation):(o=pn(o,L.operation),(p!=="read"||R&&c===null)&&h===S&&u===C&&(u=null),structuredClone(o))})();if(p!=="read"){c=D;let L=()=>{c===D&&(c=null)};D.then(L,L)}return D}let a={get view(){return d?structuredClone(d):null},get quote(){return f?structuredClone(f):null},get operation(){return o?structuredClone(o):null},get webViewUrl(){return"bundled"},get recovery(){return gn({quote:f,operation:o,requestId:l,pending:i!==null||u!==null,destroyed:w})},get pendingCancellation(){return!w&&u==="cancel"},refresh:N,async preview(p){if(A(),!d)throw new m("INVALID_REQUEST","Load the Paywall first");let v=d.document.buttons[p.actionId];if(v?.type!=="checkout")throw new m("INVALID_REQUEST","Choose an authored purchase action");let C=Ge(v.product,p.selection,d.capabilities);if(!C)throw new m("PRODUCT_UNAVAILABLE","Choose an available Product");let S=He(d.document.screen,C,p.selection,d.capabilities),R=ne.previewAttach.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:C,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:t.commerce.provider,currency:t.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),O=JSON.stringify(R);if(g&&g!==O&&(i||u||!o||o.status==="pending"))throw new m("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(g===O){if(i)return i;if(f)return structuredClone(f)}g!==O&&(f=null,o=null),g=O,l=R.requestId;let D=(async()=>{let L=ne.previewAttach,k=await Ee(s.request,L,R);return A(),mn(k.quote,{productVersionId:C,featureQuantities:S,currency:t.commerce.currency,provider:t.commerce.provider},"The purchase quote changed its selected Product or presentment"),f=k.quote,o=null,structuredClone(f)})();i=D;try{return await D}finally{i===D&&(i=null)}},confirm:()=>x("confirm"),cancel:()=>x("cancel"),read:()=>x("read"),destroy(){w||(w=!0,r?.(),s.dispose(),d=null,f=null,o=null,g=null,l=null)}},r=e.session?.subscribeIdentity(a.destroy);try{return await N(),a}catch(p){throw a.destroy(),p}}import{z as kn}from"zod";import{z as ge}from"zod";var Mn=ge.record(ge.string().regex(/^[a-f0-9]{64}$/),ge.strictObject({at:ge.number(),text:ge.string()})),oe=2*1048576,Un=100;function qn(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Pn(e,n){let t=n===void 0?qn():n,s=new Map,d=0,w=!1,f=!1,o,g;async function i(u){if(!t)return null;let c;try{let h=await Promise.race([Promise.resolve().then(()=>t.getItem(u)),new Promise(A=>{c=setTimeout(()=>A(null),Un)})]);return typeof h=="string"&&h.length<=oe&&new TextEncoder().encode(h).byteLength<=oe?h:null}catch{return null}finally{clearTimeout(c)}}function l(){if(g)return g;let u=(async()=>{try{let c=await i(`${e}:artifacts`);if(c)return Mn.parse(JSON.parse(c))}catch{}return{}})();return g=u,u.finally(()=>{g===u&&(g=void 0)}),u}return{async readManifest(){return i(e)},writeManifest(u){!t||u.length>oe||new TextEncoder().encode(u).byteLength>oe||(o=u,!f&&(f=!0,Promise.resolve().then(async()=>{try{for(;o!==void 0;){let c=o;try{await t.setItem(e,c)}catch{}o===c&&(o=void 0)}}finally{f=!1}})))},async readArtifact(u){let c=(await l())[u],h=Date.now();return c&&h>=c.at&&h-c.at<=J.retentionMs?c.text:void 0},writeArtifact(u,c){if(!t||c.length>oe)return;let h=s.get(u);if(h?.text===c||!h&&s.size>=128)return;let A=new TextEncoder().encode(c).byteLength;d-(h?.byteLength??0)+A>oe||(s.set(u,{text:c,byteLength:A}),d+=A-(h?.byteLength??0),!w&&(w=!0,Promise.resolve().then(async()=>{try{for(;s.size;){let N=new Map(s);try{let x={...await l()},a=Date.now();for(let[C,S]of N)x[C]={at:a,text:S.text};let r={},p=2,v=0;for(let[C,S]of Object.entries(x).sort(([,R],[,O])=>O.at-R.at)){if(S.at>a||a-S.at>J.retentionMs)continue;let R=new TextEncoder().encode(JSON.stringify({[C]:S})).byteLength;p+R>oe||v>=128||(r[C]=S,p+=R,v++)}await t.setItem(`${e}:artifacts`,JSON.stringify(r))}catch{}finally{for(let[x,a]of N)s.get(x)===a&&(s.delete(x),d-=a.byteLength)}}}finally{w=!1}})))}}}var E=(e,n)=>new m(e,n),W=()=>performance.now(),Sn=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function sr(e){let n=Ke.parse(e.scope),t=new te(e.origin??le);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 E("INVALID_URL","Configuration requires a trusted HTTPS origin");let s=new Set([t.origin,...(e.assetOrigins??[]).map(I=>{let y=new te(I);if(y.protocol!=="https:"||y.username||y.password||y.search||y.hash||y.pathname!=="/")throw E("INVALID_URL","Invalid configuration asset origin");return y.origin})]),d=e.fetch??globalThis.fetch.bind(globalThis),w=`/api/v1/configuration/${n.environmentId}`,f=`indiana:configuration:1:${t.origin}:${M(n)}`,o=Pn(f,e.storage),g,i=0,l=0,u=!1,c=!1,h=0,A=0,N,x,a,r,p=0,v=new Set,C=new Set,S=new Map,R=new Map,O=0,D=!1;function L(){for(let I of v)try{I()}catch{}}function k(I){try{e.onError?.(I)}catch{}}let G=()=>!c&&!u&&!!g&&W()<i&&Date.now()<l;function H(){if(!G())throw E("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function de(I,y,b){if(!S.has(I)){for(;S.size&&(S.size>=128||O+b>J.maxCacheBytes);){let P=S.entries().next().value;O-=P[1].byteLength,S.delete(P[0])}S.set(I,{text:y,byteLength:b}),O+=b}}function Z(I,y,b){return cn(I,y,{signal:b,error:P=>E("INVALID_RESPONSE",P==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function fe(I){let y=new te(I,t);if(!s.has(y.origin)||y.username||y.password||y.hash||y.search)throw E("INVALID_URL","Configuration artifact origin is not trusted");return y.href}async function Ae(I,y,b=!1){let P=await d(fe(I),{method:"GET",credentials:"omit",redirect:"error",cache:b?"default":"no-cache",signal:y,headers:{}});if(P.status===429){let T=P.headers.get("retry-after")??"";p=/^\d+$/.test(T)?Number(T)*1e3:Math.max(0,Date.parse(T)-Date.now())||15e3}if(!P.ok&&P.status!==304)throw E(`CONFIGURATION_HTTP_${P.status}`,"Configuration synchronization failed");return P}function An(I,y,b){let P=Date.parse(I.headers.get("x-indiana-config-validated-at")??""),T=Date.parse(I.headers.get("x-indiana-config-valid-until")??""),_=Date.parse(I.headers.get("date")??""),F=I.headers.get("age"),B=F!==null&&/^\d+(\.\d+)?$/.test(F)?Number(F)*1e3:NaN;if(![P,T,_,B].every(Number.isFinite)||T<=P||T-P>J.maxControlAgeMs||P>_+1e3)throw E("INVALID_RESPONSE","Configuration freshness evidence is invalid");let V=Math.min(T-P,b.maxControlAgeSeconds*1e3,J.maxControlAgeMs)-Math.max(B,_-P,0)-(W()-y);if(V<=0)throw E("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return W()+V}function Fe(){if(clearTimeout(a),clearTimeout(r),c||!v.size)return;G()&&(r=setTimeout(()=>{G()?Fe():L()},Math.max(1,i-W())),Sn(r));let I=A?Math.min(15e3,1e3*2**Math.min(A-1,4)):Math.min(15e3,(g?.policy.refreshIntervalSeconds??15)*1e3);a=setTimeout(()=>{ie().catch(k)},Math.max(p,I*(.8+Math.random()*.2))),Sn(a)}async function ie(){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(N)return N;let I=h,y=new AbortController;x=y;let b=(async()=>{if(!D){D=!0;try{let he=await o.readManifest();if(he&&!g){let K=Oe.parse(JSON.parse(he));M(K.scope)===M(n)&&(g=K)}}catch{}}y.signal.throwIfAborted();let F=g,B=W(),U=await Ae(w,y.signal);U.status===304&&(!F||!U.headers.has("x-indiana-config-validated-at")||!U.headers.has("x-indiana-config-valid-until")||!U.headers.has("age"))&&(U=await Ae(w,y.signal));let V=U.status===304?F:Oe.parse(JSON.parse(await Z(U,J.maxManifestBytes,y.signal))),{generation:ae,...se}=V,z=U.headers.get("etag");if(M(V.scope)!==M(n)||Qe(se)!==ae||z!==`"${ae}"`&&z!==`W/"${ae}"`)throw E("INVALID_RESPONSE","Configuration scope or content identity changed");if(F&&(V.revision<F.revision||V.revision===F.revision&&V.generation!==F.generation))throw E("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[he,K]of Object.entries(F?.funnels??{})){let ee=V.funnels[he];if(ee&&(ee.controlRevision<K.controlRevision||ee.evaluationRevision<K.evaluationRevision||ee.controlRevision===K.controlRevision&&ee.state!==K.state||ee.evaluationRevision===K.evaluationRevision&&ee.evaluationMode!==K.evaluationMode))throw E("INVALID_RESPONSE","Funnel control revision changed identity")}let X=An(U,B,V.policy);if(y.signal.throwIfAborted(),I!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return g=V,i=X,l=Date.now()+Math.max(0,X-W()),u=!1,A=0,p=0,o.writeManifest(M(V)),L(),structuredClone(V)})(),P=setTimeout(()=>y.abort(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),J.initializationMs),T=new Promise((F,B)=>y.signal.addEventListener("abort",()=>B(y.signal.reason),{once:!0})),_=Promise.race([b,T]).catch(F=>{throw A++,(F instanceof kn.ZodError||F instanceof SyntaxError||F instanceof m&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(F.code))&&(i=0,u=!0,L()),F}).finally(()=>{clearTimeout(P),N===_&&(N=void 0),Fe()});return N=_,_}async function ye(I){let y=I.sha256,b=se=>Ce(se,I);fe(I.url);let P=S.get(y);if(P){if(P.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return S.delete(y),S.set(y,P),P.text}let T=R.get(y);if(T){if(T.byteLength!==I.byteLength)throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return T.promise}let _=new AbortController;C.add(_);let F=h,B=(async()=>{try{let X=await o.readArtifact(y);if(X&&b(X)){if(_.signal.throwIfAborted(),c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,X,I.byteLength),X}}catch{}_.signal.throwIfAborted();let se=await Ae(I.url,_.signal,!0),z=await Z(se,I.byteLength,_.signal);if(!b(z))throw E("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(c||F!==h)throw E("CONFIGURATION_DISPOSED","Configuration scope changed");return de(y,z,I.byteLength),o.writeArtifact(y,z),z})(),U=setTimeout(()=>_.abort(E("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),J.initializationMs),V=new Promise((se,z)=>_.signal.addEventListener("abort",()=>z(_.signal.reason),{once:!0})),ae=Promise.race([B,V]).finally(()=>{clearTimeout(U),C.delete(_),R.delete(y)});return R.set(y,{promise:ae,byteLength:I.byteLength}),ae}async function we(){return G()||await ie(),H(),g}async function me(I){let y,b=new Promise((P,T)=>{y=setTimeout(()=>T(E("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),J.initializationMs)});try{return await Promise.race([I(),b])}finally{clearTimeout(y)}}function pe(I,y){if(H(),g?.generation!==I.generation)throw E("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(y&&g.funnels[y]?.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Le(I){let y=I.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let P=Je.parse(JSON.parse(await ye(b)));if(M(P.scope)!==M({projectId:n.projectId,environment:n.environment})||P.generation!==b.generation||P.remoteFeatures.some(T=>Object.hasOwn(P.features,T)))throw E("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return pe(I),{...P,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,i-W())).toISOString()}}async function xe(I,y){let b=await we(),P=b.funnels[I];y&&(!P||P.evaluationMode==="local"&&!P.versions[y])&&(N&&await N,b=await ie()),pe(b,I);let T=b.funnels[I];if(T.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let _=y??T.currentVersionId,F=T.versions[_];if(!F)throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(b.artifacts[F.artifact].formatVersion!==3)throw E("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[B,U]=await Promise.all([ye(b.artifacts[F.artifact]).then(V=>$e(JSON.parse(V))),T.evaluationMode==="local"?Le(b):void 0]);if(U&&M(Ye(B,U))!==M(F.dependencies))throw E("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return pe(b,I),{document:B,growth:U,versionId:_,control:structuredClone(T),manifest:structuredClone(b)}}async function Ve(I,y){try{return await xe(I,y)}catch(b){if(!(b instanceof m)||!(b.code==="CONFIGURATION_CHANGED"||b.code==="CONFIGURATION_HTTP_404"&&G()))throw b;let P=g?.generation;if(N&&await N,await ie(),b.code!=="CONFIGURATION_CHANGED"&&g?.generation===P)throw b;return xe(I,y)}}function Ne(){u=!0,L(),ie().catch(k)}let Ie=()=>{(typeof document>"u"||document.visibilityState==="visible")&&Ne()};function Fn(I){if(c)throw E("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(I),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",Ne),window.addEventListener("focus",Ie),document.addEventListener("visibilitychange",Ie)),Fe()),()=>{v.delete(I),v.size||(clearTimeout(a),clearTimeout(r),Me())}}function Me(){typeof window<"u"&&(window.removeEventListener("online",Ne),window.removeEventListener("focus",Ie),document.removeEventListener("visibilitychange",Ie))}return{scope:Object.freeze({...n}),refresh:ie,subscribe:Fn,assertFresh:H,assertFeatures(I){H();let y=g.gb.features;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(I!==void 0&&g.artifacts[y].generation!==I)throw E("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return G()},get snapshot(){return g?structuredClone(g):null},get remainingMs(){return G()?Math.max(0,i-W()):0},async features(){return me(async()=>Le(await we()))},pageExperiments:()=>me(async()=>{let I=await we(),y=I.gb.pageExperiments;if(!y)throw E("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let b=I.artifacts[y];if(b.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let P=an.parse(JSON.parse(await ye(b)));if(P.environmentId!==n.environmentId||P.generation!==b.generation)throw E("INVALID_RESPONSE","Page experiment scope or generation changed");return pe(I),P}),funnel:(I,y)=>me(()=>Ve(I,y)),paywall:(I,y)=>me(async()=>{let b=await we(),P=b.paywalls?.[I];if(!P||!y&&P.state!=="published")throw E("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let T=y??P.currentVersionId,_=P.versions[T],F=_&&b.artifacts[_.artifact];if(!F||F.kind!=="paywall"||F.formatVersion!==1)throw E("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let B=ze.parse(JSON.parse(await ye(F)));return pe(b),{document:B,versionId:T,version:_.version,control:structuredClone(P),manifest:structuredClone(b)}}),async localFunnel(I,y){let b=await me(()=>Ve(I,y));if(!b.growth)throw E("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:P,remoteFeatures:T,..._}=b.growth;return on({scope:{projectId:n.projectId,environment:n.environment},funnelId:I,versionId:b.versionId,evaluationMode:"local",evaluationRevision:b.control.evaluationRevision,document:b.document,payload:_})},assertFunnel(I,y,b){H();let P=g.funnels[I];if(!P||P.state!=="active")throw E("FUNNEL_STOPPED","Funnel is paused or unavailable");if(P.evaluationMode!=="local")throw E("EVALUATION_MODE","This Funnel now executes at Longplay");if(y!==void 0&&P.controlRevision!==y)throw E("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(b!==void 0&&!P.versions[b])throw E("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!c){c=!0,h++,i=0,x?.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(a),clearTimeout(r),Me(),L(),v.clear();for(let I of C)I.abort(E("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));S.clear(),O=0}}}}function En(e){let n=ue.test(e.apiKey);if(typeof window<"u"&&!n)throw new m("SERVER_ONLY","Funnel starts are issued by your backend");if(!n&&!re.test(e.apiKey))throw new m("INVALID_TOKEN","A customer credential or server API key is required");return{async start(t){let s=Q.safeParse({...t,operation:"start"});if(!s.success||s.data.operation!=="start"||(n?s.data.customer!==void 0:s.data.customer===void 0))throw new m("INVALID_REQUEST","Invalid current Funnel start");let d=s.data,w=Y({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||w.identify(e.apiKey);let f=be(e,await w.request("funnels",d));if(!f.runToken)throw new m("INVALID_RESPONSE","Funnel start credentials are missing");if(f.run.source.id!==d.funnelId||f.run.locale!==(d.locale??"en")||!ce(f.run.parameters,d.parameters??{})||(d.customer?!f.customerId||d.customer.type==="id"&&f.customerId!==d.customer.value:f.customerId!==void 0))throw new m("INVALID_RESPONSE","Funnel start contract changed");return{...f,runToken:f.runToken}}finally{w.dispose()}}}}async function vr(e){e={...e};let n=e.configuration;if(!n)throw new m("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let t={projectId:n.scope.projectId,environment:n.scope.environment};if(e.scope&&M(t)!==M(e.scope))throw new m("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await n.funnel(e.funnelId)).control.evaluationMode!=="local")throw new m("EVALUATION_MODE","This Funnel uses Remote evaluation");let d=re.test(e.credential);if(d?!e.customerId:e.customerId!==void 0)throw new m("INVALID_REQUEST","Only Server-Key starts name their Customer");let w=En({...e,scope:t,apiKey:e.credential}),f=o=>{let g=Cn({...e,scope:t,runToken:o,...d?{serverKey:e.credential}:{}});return d||g.identify(e.credential),g};return{async start(o){let g=await w.start({...o,funnelId:e.funnelId,...d?{customer:{type:"id",value:e.customerId}}:{}}),i=f(g.runToken),l=await i.get();return{...g,...l,controller:i}},async restore(o){let g=f(o),i=await g.get();if(i.run.source.id!==e.funnelId)throw g.reset(),new m("SCOPE_MISMATCH","Run belongs to another Funnel");return{...i,runToken:o,controller:g}}}}export{Ee as a,Bn as b,be as c,_e as d,ot as e,Ln as f,yn as g,pt as h,ce as i,Rt as j,Ct as k,Cn as l,Yt as m,sr as n,En as o,vr as p};
@@ -1,17 +0,0 @@
1
- import{z as rr}from"zod";var ir=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],$=rr.enum(ir);function or(e){let t=$.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function He(e,t,n="en",r={}){let i=$.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**or(i))}import{z as l}from"zod";function Ge(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function xe(e,t,n){return n===2?Ge(Ge(e+t)+"")%1e4/1e4:null}function Ot(e){return e<=0?[]:new Array(e).fill(1/e)}function Se(e,t){return e>=t[0]&&e<t[1]}function Qe(e,t){for(let[n,r]of t.entries())if(Se(e,r))return n;return-1}function Ke(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=Ot(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,u)=>u+s,0);(i<.99||i>1.01)&&(n=r);let o=0,a=t;return n.map(s=>{let u=o;return o+=s,[u,u+a*s]})}function Ze(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let o=r.replace(/#.*/,"").split("&").map(a=>a.split("=",2)).filter(([a])=>a===e).map(([,a])=>a===void 0?NaN:parseInt(a))[0];return o!==void 0&&o>=0&&o<n?o:null}function We(e){try{return e()}catch{return!1}}function le(e){return typeof e=="string"?e:JSON.stringify(e)}function z(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function vt(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function Je(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let o=cr(e,i.type,i.pattern);if(i.include===!1){if(o)return!1}else n=!0,o&&(r=!0)}return r||!n}function ar(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function sr(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,o)=>{r.push([e.searchParams.get(o)||"",i,!1])}),!r.some(i=>!ar(i[0],i[1],i[2]))}catch{return!1}}function cr(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=vt(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return sr(r,n);return!1}catch{return!1}}function Ye(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function Re(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function Rt(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Re(e.savedGroups??{})}var ur=e=>e/2**32|0,lr=e=>e>>>0;function Nt(e,t,n,r){let i=ur(n),o=lr(n);e.setUint32(t,r?o:i,r),e.setUint32(t+4,r?i:o,r)}function Ct(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Xe=e=>e?`"${e}" `:"";function pr(e,t=""){if(typeof e!="number")throw new TypeError(Xe(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Xe(t)+"expected integer >= 0, got "+e);return e}function Ne(e,t,n=""){if(Ct(e)&&(t===void 0||e.length===t))return e;t!==void 0&&pr(t,"length");let r=Ct(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=Xe(n)+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)}var dr=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Tt=(e,t)=>{dr(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function et(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function jt(e,t){Ne(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function tt(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Ce(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function B(e,t){return e<<32-t|e>>>t}var fr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",mr=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Pt(e){if(Ne(e),fr)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=mr[e[n]];return t}function gr(e,t,n="opts"){return Tt(e,"defaults"),t!==void 0&&Tt(t,n),Object.assign(Object.create(null),e,t)}function Dt(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=gr({},t,"info");let n=(i,o)=>e(o).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var Lt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Ut(e,t,n){return e&t^~e&n}function $t(e,t,n){return e&t^e&n^t&n}var Te=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(t,n,r,i){this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Ce(this.buffer)}update(t){et(this),Ne(t);let{view:n,buffer:r,blockLen:i}=this,o=t.length,a=!1;for(let s=0;s<o;){let u=Math.min(i-this.pos,o-s);if(u===i){let f=Ce(t);for(;i<=o-s;s+=i)this.process(f,s);a=!0;continue}r.set(s===0&&u===o?t:t.subarray(s,s+u),this.pos),this.pos+=u,s+=u,this.pos===i&&(this.process(n,0),this.pos=0,a=!0)}return this.length+=t.length,a&&this.roundClean(),this}digestInto(t){et(this),jt(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:o}=this,{pos:a}=this;n[a++]=128,n.fill(0,a),this.padOffset>i-a&&(this.process(r,0),n.fill(0)),Nt(r,i-8,this.length*8,o),this.process(r,0),this.roundClean();let s=t===n?r:Ce(t),u=this.outputLen,f=u/4,d=this.get();if(u%4||f>d.length)throw new Error("invalid outputLen");for(let g=0;g<f;g++)s.setUint32(4*g,d[g],o)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:o,pos:a}=this;return t.destroyed=o,t.finished=i,t.length=r,t.pos=a,a&&t.buffer.set(n),t}clone(){return this._cloneInto()}},zt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var br=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),X=new Uint32Array(64),nt=class extends Te{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(t,n){super(64,t,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0,this.F=n[5]|0,this.G=n[6]|0,this.H=n[7]|0}get(){let{A:t,B:n,C:r,D:i,E:o,F:a,G:s,H:u}=this;return[t,n,r,i,o,a,s,u]}set(t,n,r,i,o,a,s,u){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=o|0,this.F=a|0,this.G=s|0,this.H=u|0}_cloneInto(t){return(t||=new this.constructor).set(...this.get()),this._cloneIntoMeta(t)}process(t,n){for(let g=0;g<16;g++,n+=4)X[g]=t.getUint32(n,!1);for(let g=16;g<64;g++){let A=X[g-15],y=X[g-2],b=B(A,7)^B(A,18)^A>>>3,k=B(y,17)^B(y,19)^y>>>10;X[g]=k+X[g-7]+b+X[g-16]|0}let{A:r,B:i,C:o,D:a,E:s,F:u,G:f,H:d}=this;for(let g=0;g<64;g++){let A=B(s,6)^B(s,11)^B(s,25),y=d+A+Ut(s,u,f)+br[g]+X[g]|0,k=(B(r,2)^B(r,13)^B(r,22))+$t(r,i,o)|0;d=f,f=u,u=s,s=a+y|0,a=o,o=i,i=r,r=y+k|0}r=r+this.A|0,i=i+this.B|0,o=o+this.C|0,a=a+this.D|0,s=s+this.E|0,u=u+this.F|0,f=f+this.G|0,d=d+this.H|0,this.set(r,i,o,a,s,u,f,d)}roundClean(){tt(X)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),tt(this.buffer)}},rt=class extends nt{constructor(){super(32,zt)}};var Ft=Dt(()=>new rt,Lt(1));var Vt=new Map,it=32,Bt=new WeakMap,Mt=new WeakMap;function hr(e){return Pt(Ft(new TextEncoder().encode(String(e))))}var Pe=e=>Array.isArray(e)?e.map(Pe):typeof e=="string"||typeof e=="number"?hr(e):null,je=e=>typeof e=="string"?e.toLowerCase():e;function Kt(e){let t=Bt.get(e);return t||(t=new Set(e),Bt.set(e,t)),t}function yr(e){let t=Mt.get(e);return t||(t=new Set(e.map(je)),Mt.set(e,t)),t}function Zt(e){Re(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=it&&Kt(n)}return e}function M(e,t,n,r){n=n||{},r||Re(n),r=r||new Set;for(let[i,o]of Object.entries(t))switch(i){case"$or":if(!Qt(e,o,n,r))return!1;break;case"$nor":if(Qt(e,o,n,r))return!1;break;case"$and":if(!Ir(e,o,n,r))return!1;break;case"$not":if(M(e,o,n,r))return!1;break;case"$savedGroup":if(!xr(e,o,n,r))return!1;break;default:if(!ke(o,Wt(e,i),n,!1,r))return!1}return!0}function xr(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:o}=t;if(typeof i!="string"||r.has(i)||o!==void 0&&typeof o!="string")return!1;let a=n[i];if(!a||Array.isArray(a)||typeof a!="object")return!1;let s=new Set(r).add(i);if(a.type==="list"||a.type==="hashed"){let u=o??a.attributeKey;if(typeof u!="string"||!Array.isArray(a.values))return!1;let f=Wt(e,u);return ie(a.type==="hashed"?Pe(f):f,a.values)}return a.type==="condition"?!a.condition||typeof a.condition!="object"?!1:M(e,a.condition,n,s):!1}function Wt(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function qt(e,t=!1){let n=`${e}${t?"/i":""}`,r=Vt.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Vt.set(n,r)),r}function ke(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!Jt(e))return JSON.stringify(t)===JSON.stringify(e);let o=e;for(let a in o)if(!Ar(a,t,o[a],n,i))return!1;return!0}function Jt(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function Sr(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function kr(e,t,n,r){if(!Array.isArray(e))return!1;let i=Jt(t)?o=>ke(t,o,n,!1,r):o=>M(o,t,n,r);for(let o=0;o<e.length;o++)if((e[o]??null)!==null&&i(e[o]))return!0;return!1}function ie(e,t,n=!1){if(n){let i;if(t.length>=it){let o=yr(t);i=a=>{let s=je(a);return!(typeof s=="number"&&Number.isNaN(s))&&o.has(s)}}else i=o=>t.some(a=>je(o)===je(a));return Array.isArray(e)?e.some(o=>i(o)):i(e)}let r=t.length>=it?(i=>o=>i.has(o))(Kt(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Ht(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Gt(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let o=0;o<t.length;o++){let a=!1;for(let s=0;s<e.length;s++)if(ke(t[o],e[s],n,r,i)){a=!0;break}if(!a)return!1}return!0}function Ar(e,t,n,r,i=new Set){let o=t,a=n;switch(e){case"$veq":return z(t)===z(n);case"$vne":return z(t)!==z(n);case"$vgt":return z(t)>z(n);case"$vgte":return z(t)>=z(n);case"$vlt":return z(t)<z(n);case"$vlte":return z(t)<=z(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return o<a;case"$lte":return o<=a;case"$gt":return o>a;case"$gte":return o>=a;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?ie(t,n):!1;case"$ini":return Array.isArray(n)?ie(t,n,!0):!1;case"$inGroup":{let s=r[n],u=Ht(s);return u===null?!1:ie(s?.type==="hashed"?Pe(t):t,u)}case"$notInGroup":{let s=r[n],u=Ht(s);return u===null?!1:!ie(s?.type==="hashed"?Pe(t):t,u)}case"$nin":return Array.isArray(n)?!ie(t,n):!1;case"$nini":return Array.isArray(n)?!ie(t,n,!0):!1;case"$not":return!ke(n,t,r,!1,i);case"$size":return Array.isArray(t)?ke(n,t.length,r,!1,i):!1;case"$elemMatch":return kr(t,n,r,i);case"$all":return Array.isArray(n)?Gt(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?Gt(t,n,r,!0,i):!1;case"$regex":try{return qt(n).test(t)}catch{return!1}case"$regexi":try{return qt(n,!0).test(t)}catch{return!1}case"$type":return Sr(t)===n;default:return!1}}function Qt(e,t,n,r){if(!t.length)return!0;for(let i of t)if(M(e,i,n,r))return!0;return!1}function Ir(e,t,n,r){for(let i of t)if(!M(e,i,n,r))return!1;return!0}function ot(e){return Rt(e),{context:e,stack:{evaluatedFeatures:new Set}}}function at(e){return{...e.attributes,...e.attributeOverrides}}function ee(e,t,n){let r=t||"id",i="",o=at(e);return o[r]&&(i=o[r]),!i&&n&&(o[n]&&(i=o[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function E(e,t,n){e.context.log?.(t,n)}function De(e,t){return t=t||0,`${e}__${t}`}function st(e,t){return`${e}||${t}`}function Er(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:o}=ee(e,t),a=st(i,le(o)),{hashAttribute:s,hashValue:u}=ee(e,n),f=u?st(s,le(u)):null,d={};return f&&r[f]&&Object.assign(d,r[f].assignments||{}),r[a]&&Object.assign(d,r[a].assignments||{}),d}function Yt({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:o,expMeta:a}){n=n||0,o=o||0,r=r||"id",a=a||[];let s=De(t,n),u=Er(e,r,i);if(o>0)for(let g=0;g<o;g++){let A=De(t,g);if(u[A]!==void 0)return{variation:-1,versionIsBlocked:!0}}let f=u[s];if(f===void 0)return{variation:-1};let d=a.findIndex(g=>g.key===f);return d<0?{variation:-1}:{variation:d}}function Xt(e,t,n,r){let i=st(t,n),o=e.stickyBucketAssignmentDocs,a=o&&o[i]?o[i].assignments||{}:{},s={...a,...r},u=JSON.stringify(a)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:u}}function en(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function tn(e,t){let n=ot(t),r=on(e,null,n);return t.onExperimentEval?.(e,r),r}function nn(e,t){return ut(e,ot(t))}function _r(e){return e.forcedVariations||{}}function rn(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=cn(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}ct(()=>r.onExperimentViewed?.(t,n))}function wr(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}ct(()=>r.onFeatureUsage?.(t,n))}function ct(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function ut(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return E(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),te(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let o of r?.rules??[])Ye(o);let i=n.forcedFeatureValues;if(i&&i.has(e))return E(t,"Global override",{id:e,value:i.get(e)}),te(t,e,i.get(e),"override");if(!r)return E(t,"Unknown feature",{id:e}),te(t,e,null,"unknownFeature");if(r.rules){let o=new Set(t.stack.evaluatedFeatures);e:for(let a of r.rules){if(a.parentConditions)for(let f of a.parentConditions){t.stack.evaluatedFeatures=new Set(o);let d=ut(f.id,t);if(d.source==="cyclicPrerequisite")return te(t,e,null,"cyclicPrerequisite");let g={value:d.value};if(!M(g,f.condition||{},n.savedGroups||{})){if(f.gate)return E(t,"Feature blocked by prerequisite",{id:e,rule:a}),te(t,e,null,"prerequisite");E(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:a});continue e}}if(a.filters&&sn(a.filters,t)){E(t,"Skip rule because of filters",{id:e,rule:a});continue}if("force"in a){if(a.condition&&!an(a.condition,t)){E(t,"Skip rule because of condition ff",{id:e,rule:a});continue}if(!Or(t,a.seed||e,a.hashAttribute,n.saveStickyBucketAssignmentDoc&&!a.disableStickyBucketing?a.fallbackAttribute:void 0,a.range,a.coverage,a.hashVersion)){E(t,"Skip rule because user not included in rollout",{id:e,rule:a});continue}return E(t,"Force value from rule",{id:e,rule:a}),a.tracks&&a.tracks.forEach(f=>{rn(t,f.experiment,f.result)}),te(t,e,a.force,"force",a.id)}if(!a.variations){E(t,"Skip invalid rule",{id:e,rule:a});continue}let s={variations:a.variations,key:a.key||e};"coverage"in a&&(s.coverage=a.coverage),a.weights&&(s.weights=a.weights),a.hashAttribute&&(s.hashAttribute=a.hashAttribute),a.fallbackAttribute&&(s.fallbackAttribute=a.fallbackAttribute),a.disableStickyBucketing&&(s.disableStickyBucketing=a.disableStickyBucketing),a.bucketVersion!==void 0&&(s.bucketVersion=a.bucketVersion),a.minBucketVersion!==void 0&&(s.minBucketVersion=a.minBucketVersion),a.meta&&(s.meta=a.meta),a.ranges&&(s.ranges=a.ranges),a.name&&(s.name=a.name),a.phase&&(s.phase=a.phase),a.seed&&(s.seed=a.seed),a.hashVersion&&(s.hashVersion=a.hashVersion),a.filters&&(s.filters=a.filters),a.condition&&(s.condition=a.condition);let u=on(s,e,t);if(n.onExperimentEval?.(s,u),u.inExperiment&&!u.passthrough)return te(t,e,u.value,"experiment",a.id,s,u)}}return E(t,"Use default value",{id:e,value:r.defaultValue}),te(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function on(e,t,n){let{context:r}=n;Ye(e);let i=e.key,o=e.variations.length;if(o<2)return E(n,"Invalid experiment",{id:i}),D(n,e,-1,!1,t);if(r.enabled===!1)return E(n,"Context disabled",{id:i}),D(n,e,-1,!1,t);if(e.urlPatterns&&!Je(r.url||"",e.urlPatterns))return E(n,"Skip because of url targeting",{id:i}),D(n,e,-1,!1,t);let a=Ze(i,r.url||"",o);if(a!==null)return E(n,"Force via querystring",{id:i,variation:a}),D(n,e,a,!1,t);let u=_r(r)[i];if(u!==void 0)return E(n,"Force via dev tools",{id:i,variation:u}),D(n,e,u,!1,t);if(e.active===!1)return E(n,"Skip because inactive",{id:i}),D(n,e,-1,!1,t);let{hashAttribute:f,hashValue:d}=ee(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return E(n,"Skip because missing hashAttribute",{id:i}),D(n,e,-1,!1,t);let g=-1,A=!1,y=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:w,versionIsBlocked:U}=Yt(en({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));A=w>=0,g=w,y=!!U}if(!A){if(e.filters&&sn(e.filters,n))return E(n,"Skip because of filters",{id:i}),D(n,e,-1,!1,t);if(e.include&&!We(e.include))return E(n,"Skip because of include function",{id:i}),D(n,e,-1,!1,t);if(e.condition&&!an(e.condition,n))return E(n,"Skip because of condition exp",{id:i}),D(n,e,-1,!1,t);if(e.parentConditions){let w=new Set(n.stack.evaluatedFeatures);for(let U of e.parentConditions){n.stack.evaluatedFeatures=new Set(w);let re=ut(U.id,n);if(re.source==="cyclicPrerequisite")return D(n,e,-1,!1,t);let qe={value:re.value};if(!M(qe,U.condition||{},r.savedGroups||{}))return E(n,"Skip because prerequisite evaluation fails",{id:i}),D(n,e,-1,!1,t)}}}let b=xe(e.seed||i,d,e.hashVersion??2);if(b===null)return E(n,"Skip because of invalid hash version",{id:i}),D(n,e,-1,!1,t);if(!A){let w=e.ranges||Ke(o,e.coverage===void 0?1:e.coverage,e.weights);g=Qe(b,w)}if(y)return E(n,"Skip because sticky bucket version is blocked",{id:i}),D(n,e,-1,!1,t,void 0,!0);if(g<0)return E(n,"Skip because of coverage",{id:i}),D(n,e,-1,!1,t);if("force"in e)return E(n,"Force variation",{id:i,variation:e.force}),D(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return E(n,"Skip because QA mode",{id:i}),D(n,e,-1,!1,t);let k=D(n,e,g,!0,t,b,A);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:w,key:U,doc:re}=Xt(r,f,le(d),{[De(e.key,e.bucketVersion)]:k.key});if(w){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[U]=re;let qe=r.saveStickyBucketAssignmentDoc;ct(()=>qe(re))}}return rn(n,e,k),E(n,"In experiment",{id:i,variation:k.variationId}),k}function te(e,t,n,r,i,o,a){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return o&&(s.experiment=o),a&&(s.experimentResult=a),r!=="override"&&wr(e,t,s),s}function an(e,t){return M(at(t.context),e,t.context.savedGroups||{})}function sn(e,t){return e.some(n=>{let{hashValue:r}=ee(t.context,n.attribute);if(!r)return!0;let i=xe(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(o=>Se(i,o))})}function Or(e,t,n,r,i,o,a){if(!i&&o===void 0)return!0;if(!i&&o===0)return!1;let{hashValue:s}=ee(e.context,n,r);if(!s)return!1;let u=xe(t,s,a??2);return u===null?!1:i?Se(u,i):o!==void 0?u<=o:!0}function D(e,t,n,r,i,o,a){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:u,hashValue:f}=ee(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},g=t.variations[0];for(let[y,b]of t.variations.entries())if(y===n){g=b;break}let A={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:g,hashAttribute:u,hashValue:f,stickyBucketUsed:!!a};return d.name&&(A.name=d.name),o!==void 0&&(A.bucket=o),d.passthrough&&(A.passthrough=d.passthrough),A}function cn(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
2
- Copyright (c) 2025 GrowthBook, Inc.
3
-
4
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
5
- furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all
8
- copies or substantial portions of the Software.
9
-
10
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
11
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
13
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16
- SOFTWARE.
17
- */var ne=l.json().superRefine((e,t)=>{let n=0;function r(i,o){if(++n>1e4||o>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(a=>r(a,o+1));else if(i&&typeof i=="object")for(let[a,s]of Object.entries(i))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,o+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),pt=l.record(l.string().min(1).max(128),ne).superRefine((e,t)=>{(!ne.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),vr=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Le=pt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r)){if(i==="$savedGroup"&&!l.strictObject({id:l.uuid(),attributeKey:l.string().min(1).max(128).optional()}).safeParse(o).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!vr.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof o=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(o)||[...o.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(o.replace(/\\u([0-9a-f]{4})/gi,(a,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(o)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(o)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),Rr=l.discriminatedUnion("type",[l.strictObject({type:l.literal("condition"),condition:Le}),l.strictObject({type:l.literal("list"),attributeKey:l.string().min(1).max(128),values:l.array(l.union([l.string(),l.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Nr(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?t.add(o.id):["$inGroup","$notInGroup"].includes(i)&&typeof o=="string"?t.add(o):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(o)}return n(e),[...t]}var Cr=l.record(l.uuid(),Rr).superRefine((e,t)=>{let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(o),a.type==="condition"&&Nr(a.condition).forEach(i),n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),dt=l.tuple([l.number().min(0).max(1),l.number().min(0).max(1)]).refine(([e,t])=>e<=t),un=l.strictObject({attribute:l.string().optional(),seed:l.string().min(1),hashVersion:l.literal(2),ranges:l.array(dt).min(1).max(100)}),Tr=l.strictObject({id:l.string().min(1).max(128),condition:Le,gate:l.boolean().optional()}),lt={id:l.string().max(128).optional(),condition:Le.optional(),parentConditions:l.array(Tr).max(50).optional(),filters:l.array(un).max(20).optional()},jr=l.union([l.strictObject({...lt}),l.strictObject({...lt,force:ne,coverage:l.number().min(0).max(1).optional(),range:dt.optional(),seed:l.string().min(1).optional(),hashAttribute:l.string().optional(),hashVersion:l.literal(2).optional()}),l.strictObject({...lt,type:l.literal("experiment-ref"),experimentId:l.uuid(),values:l.record(l.string().min(1),ne),meta:l.record(l.string().min(1),l.strictObject({passthrough:l.boolean()})).optional()})]),Pr=l.strictObject({defaultValue:ne,rules:l.array(jr).max(100)}),Xo=l.record(l.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Pr).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}n.add(o);for(let s of a.rules)for(let u of s.parentConditions??[])i(u.id);n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),Dr=l.strictObject({name:l.string().max(80),reason:l.string().max(500),dateStarted:l.iso.datetime({offset:!0}),dateEnded:l.iso.datetime({offset:!0}).nullable(),coverage:l.number().min(0).max(1),variationWeights:l.array(l.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Le,savedGroups:l.array(l.strictObject({match:l.enum(["any","all","none"]),ids:l.array(l.uuid()).min(1)})).max(50),namespace:l.strictObject({id:l.uuid(),ranges:l.array(dt).min(1)}).nullable(),seed:l.string().min(1).max(128)}),Lr=l.strictObject({key:l.string().min(1).max(128),name:l.string().min(1).max(80),hypothesis:l.string().max(2e3),status:l.enum(["draft","running","stopped"]),hashAttribute:l.string().min(1).max(128),fallbackAttribute:l.string().max(128).nullable(),hashVersion:l.literal(2),disableStickyBucketing:l.boolean(),bucketVersion:l.number().int().min(0).max(1e3),minBucketVersion:l.number().int().min(0).max(1e3),variations:l.array(l.strictObject({id:l.string().min(1),key:l.string().min(1),name:l.string().max(80),description:l.string().max(500)})).min(2).max(20),phases:l.array(Dr).min(1).max(100),releasedVariationId:l.string().nullable(),excludeFromPayload:l.boolean(),statusSchedule:l.strictObject({startAt:l.iso.datetime({offset:!0}).nullable(),stopAt:l.iso.datetime({offset:!0}).nullable(),stopAfter:l.strictObject({value:l.number().int().positive().max(36500),unit:l.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],o,a)=>r>=i||a.some(([s,u],f)=>f!==o&&r<u&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var Ur=Lr.safeExtend({filters:l.array(un).optional()}),$r=l.strictObject({experiments:l.record(l.uuid(),Ur),savedGroups:Cr}),zr=l.strictObject({attributeName:l.string(),attributeValue:l.string(),assignments:l.record(l.string(),l.string())}),ea=l.strictObject({snapshot:$r,attributes:pt,results:pt,stickyBucketAssignmentDocs:l.record(l.string(),zr)}),ta=l.strictObject({variantKey:l.string().nullable(),bucketVersion:l.number().int().min(0),source:l.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:l.number().min(0).max(1).optional(),stickyBucketUsed:l.boolean().optional(),hashUsed:l.boolean().optional()});import{z as v}from"zod";import{z as R}from"zod";var Ue=R.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),N=R.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Fr=R.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),ft=N.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),ln=R.string().min(1).max(64),oe=R.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),pn=R.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),q=R.record(ln,R.union([R.string().max(120),R.number().finite(),R.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),dn=R.record(ln,R.union([R.string().max(120),R.number().finite(),R.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),pe=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},fn=R.array(R.object({upTo:ft.nullable(),cost:N}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&pe(t.upTo)>pe(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),Vr=R.object({key:pn,match:dn,priority:R.number().int().default(0),cost:N.optional(),tiers:fn.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),Br=R.object({key:pn,match:dn,factor:ft.optional(),add:Fr.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),Mr=R.object({units:ft.default("1"),cost:N,tiers:fn.optional(),dimensions:R.array(Vr).max(12).optional(),multipliers:R.array(Br).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(a=>a.key)).size!==n.length||new Set(r.map(a=>a.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[a,s]of n.entries())for(let u of n.slice(a+1))Object.keys(s.match).length===Object.keys(u.match).length&&s.priority===u.priority&&!Object.keys(s.match).some(f=>u.match[f]!==void 0&&u.match[f]!==s.match[f])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(a=>a.cost),...n.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(s=>s.cost)])],o=pe(e.units);for(let a of i)for(let s=0;s<1<<r.length;s++){let u=r.filter((b,k)=>s&1<<k);if(u.some((b,k)=>u.slice(k+1).some(w=>Object.keys(b.match).some(U=>w.match[U]!==void 0&&w.match[U]!==b.match[U]))))continue;let f=pe(a),d=BigInt("1"),g=BigInt("0");for(let[b,k]of r.entries())s&1<<b&&(f*=pe(k.factor??"1"),d*=BigInt("1000000"),g+=pe(k.add??"0"));let A=(f+g*d)*BigInt("1000000"),y=d*o;(A<BigInt("0")||A%y!==BigInt("0")||A/y>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),ia=Mr.safeExtend({featureKey:oe});import{z as qr}from"zod";import{z as de}from"zod";var mn=de.enum(["stripe","apple","google","merchant"]),sa=de.enum(["membership","credit_pack","lifetime"]),ca=de.enum(["active","grace","suspended","inactive","revoked"]),ua=de.strictObject({currency:de.string().regex(/^[A-Z]{3}$/),micros:de.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var gn=qr.object({provider:mn,currency:$}).strict();var bn=v.strictObject({internal_feature_id:v.uuid(),quantity:N.refine(e=>/[1-9]/.test(e)),properties:q,entityId:v.uuid().optional()}),xa=v.strictObject({requirement:bn,commerce:gn.optional(),paywallId:v.uuid().optional()}),Hr=v.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Gr=v.strictObject({productId:v.string().min(1),productVersionId:v.string().min(1),name:v.string().min(1).max(120),action:v.enum(["purchase","upgrade","addon","topup"]),membershipId:v.string().min(1).nullable(),currency:$,amountMinor:v.string().regex(/^(0|[1-9]\d{0,8})$/),interval:v.enum(["free","week","month","year","one_time"]),intervalCount:v.number().int().min(1).max(156)}),hn=v.strictObject({internal_feature_id:v.string().min(1),name:v.string().min(1).max(120),kind:v.enum(["access","metered","credit"]),quantity:N,allowed:v.boolean(),reason:Hr.nullable(),preview:v.strictObject({scenario:v.enum(["feature_flag","usage_limit"]),candidates:v.array(Gr).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),Sa=v.strictObject({paywallId:v.uuid(),requirement:bn});import{z as x}from"zod";import{z as ge}from"zod";import{z as me}from"zod";import{z as fe}from"zod";var yn=fe.number().int().min(0).max(1e8),mt=fe.strictObject({kind:fe.enum(["graduated","volume"]),tiers:fe.array(fe.strictObject({upTo:fe.number().int().min(1).max(1e4).nullable(),unitAmountMinor:yn,flatAmountMinor:yn.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function gt(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?mt.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let o of n.tiers){let a=o.upTo??1e4;if(n.kind==="volume"){if(t<=a){r=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function xn(e){return gt({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var Qr=N.refine(e=>/[1-9]/.test(e)),kn=me.strictObject({units:Qr,prices:me.array(me.strictObject({currency:$,amountMinor:me.number().int().min(0).max(1e8),pricing:mt.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:me.number().int().min(0).max(1e4),maximumQuantity:me.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&gt({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function Sn(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))}function An(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Sn(e)+Sn(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}var bt=ge.strictObject({internalFeatureId:ge.uuid(),name:ge.string().min(1).max(120),includedAmount:ge.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:ge.enum(["hour","day","week","month","year","lifetime"]),resetCount:ge.number().int().min(1).max(100),terms:kn});var Kr=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],$e=x.object({plan:x.string().min(1).max(200).optional(),coupon:x.uuid().optional(),promotionCode:x.uuid().optional(),picker:x.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),In=x.object({text:x.string().optional(),label:x.string().optional(),alt:x.string().optional(),html:x.string().max(32768).optional(),price:x.object({current:x.string(),original:x.string().nullable(),period:x.string()}).optional(),code:x.string().optional(),countdownAt:x.iso.datetime().optional(),planId:x.string().min(1).max(200).optional(),planVersionId:x.string().min(1).max(200).optional(),currency:$.optional(),couponId:x.uuid().optional(),offerId:x.uuid().optional(),unavailable:x.boolean().optional(),unavailableReason:x.string().optional(),missing:x.array(x.string()).optional()}).strict(),La=x.object({paywall:hn.optional(),nodes:x.record(x.string(),x.object({base:In,picker:x.string().optional(),byPlan:x.record(x.string(),In).optional()}).strict()),plans:x.record(x.string(),x.object({id:x.string().min(1).max(200),versionId:x.string().min(1).max(200),available:x.boolean(),name:x.string(),price:x.string(),period:x.string(),currency:$.optional(),amountMinor:x.number().int().nonnegative().optional(),interval:x.enum(["free","week","month","year","one_time"]).optional(),intervalCount:x.number().int().positive().optional(),prepaid:x.array(bt).max(100).optional()}).strict()),pickers:x.record(x.string(),x.object({options:x.array(x.string().min(1).max(200)).max(20),selected:x.string().min(1).max(200).nullable()}).strict()),quantities:x.record(x.string(),x.strictObject({minimum:x.number().int().nonnegative(),maximum:x.number().int().nonnegative(),step:x.number().int().positive(),value:x.number().int().nonnegative(),label:x.string(),available:x.boolean()})).optional(),diagnostics:x.array(x.object({nodeId:x.string(),message:x.string()}).strict())}).strict();function En(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function ht(e){let t=En(e).filter(r=>!Kr.includes(r)&&!/^variables\.[A-Za-z0-9_][A-Za-z0-9_.:-]*$/.test(r)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function Ua(e,t,n={}){let r=e?.nodes[t];if(!r)return;let i=r.picker?n[r.picker]??e?.pickers[r.picker]?.selected:void 0;return typeof i=="string"?r.byPlan?.[i]??r.base:r.base}import{z as S}from"zod";var Zr=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],_n=S.enum(Zr),wn=S.object({source:_n,layout:S.enum(["full","compact"]),resourceKey:oe.optional(),pageSize:S.number().int().min(1).max(50),showSources:S.boolean(),allowPurchase:S.boolean(),outputs:S.object({billing_adjustment:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),j=S.string().max(2e3),On=S.object({id:S.string().max(100),label:j,detail:S.array(j).max(12),value:j.optional(),status:j.optional(),facts:S.array(S.object({label:j,value:j}).strict()).max(1e3),purchaseId:S.uuid().optional(),invoiceUrl:S.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:S.array(S.strictObject({action:S.literal("invoice_open"),label:j})).max(1).optional(),membershipActions:S.array(S.object({value:S.string().max(100),label:j}).strict()).max(3).optional()}).strict(),Wr=S.object({key:oe,name:j,spendable:j,reserved:j,available:j,expiry:j.nullable(),sources:S.array(On).max(50),sourceCount:S.number().int().nonnegative(),sourcePage:S.number().int().positive(),hasNextSources:S.boolean(),hasPreviousSources:S.boolean()}).strict(),Jr=S.object({source:_n,status:S.enum(["idle","loading","ready","error"]),stale:S.boolean(),preview:S.boolean(),errorCode:S.string().max(80).optional(),errorMessage:j.optional(),resources:S.array(Wr).max(500),rows:S.array(On).max(50),hasNext:S.boolean(),hasPrevious:S.boolean(),page:S.number().int().positive(),filter:S.string().max(40),updatedAt:S.iso.datetime().optional(),buyingId:S.uuid().optional(),membershipBusy:S.boolean().optional(),billingBusy:S.boolean().optional(),membershipReview:S.object({title:j,note:j,facts:S.array(S.object({label:j,value:j}).strict()).max(100)}).strict().optional(),membershipResult:j.optional()}).strict(),Va=S.object({nodes:S.record(S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Jr)}).strict(),Ba=S.object({nodeId:S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:S.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:S.string().max(100).optional()}).strict();import{z as O}from"zod";var Yr=O.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ha=O.discriminatedUnion("type",[O.object({type:O.literal("fixed"),productVersionId:O.string().min(1).max(200)}).strict(),O.object({type:O.literal("picker"),pickerId:Yr,allowedProductVersionIds:O.array(O.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Xr=O.strictObject({min:O.number().finite().min(1).max(1800),max:O.number().finite().min(1).max(1800),viewport:O.number().finite().min(1).max(100)}).refine(e=>e.min<=e.max,"Desktop width range is reversed"),vn={desktopWidth:Xr.optional(),mobile:O.enum(["sheet","fullscreen"]).optional(),backdrop:O.enum(["none","scrim","dim","strong-dim","blur"]).optional()},Rn=O.discriminatedUnion("type",[O.strictObject({type:O.literal("modal"),size:O.enum(["sm","md","lg"]),...vn}),O.strictObject({type:O.literal("sheet"),size:O.enum(["sm","md","lg"]),...vn}),O.strictObject({type:O.literal("fullscreen")}),O.strictObject({type:O.literal("inline")})]),ei={sm:360,md:420,lg:560};import{z as c}from"zod";function Nn(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Cn(e){let t={};function n(r){if(Nn(r)){let i=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let a of r.children){let s=a.type==="stack"?a.bind?.plan:void 0;s&&!i.ids.includes(s)&&i.ids.push(s)}let o=r.children[r.interaction.defaultIndex];!i.defaultId&&o?.type==="stack"&&(i.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}function Tn(e,t,n){let r={};function i(u){if(u.hidden)return;if(u.type==="plan_picker"){let g=n.pickers[u.id];r[u.id]={ids:g?.options??[],defaults:g?.selected?[g.selected]:[],remembered:[]};return}if(u.type!=="stack")return;let f=u.children.filter(g=>!g.hidden),d=u.interaction;if(Nn(u)){let g=r[u.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},A=n.pickers[u.interaction.pickerId]?.options??[];for(let b of f){let k=b.type==="stack"?b.bind?.plan:void 0;k&&A.includes(k)&&!g.ids.includes(k)&&g.ids.push(k),k&&b.id===t[u.id]&&g.remembered.push(k)}let y=u.children[u.interaction.defaultIndex];y?.type==="stack"&&!y.hidden&&y.bind?.plan&&g.defaults.push(y.bind.plan)}if(d?.type==="tabs"){let g=f.find(A=>A.id===t[u.id])??u.children[d.defaultIndex];g&&i(g)}else if(d?.type==="toggle"){let g=typeof t[u.id]=="boolean"?t[u.id]:d.defaultEnabled,A=u.children[g?0:1];A&&i(A)}else f.forEach(i)}let o=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,a=e.pages.find(u=>u.id===o);a&&i(a.root);let s={};for(let[u,f]of Object.entries(r)){let d=t[u],g=f.remembered[0]??(f.ids.includes(n.pickers[u]?.selected??"")?n.pickers[u]?.selected:f.defaults[0]);s[u]=typeof d=="string"?f.ids.includes(d)?d:"":g&&f.ids.includes(g)?g:""}for(let u of Object.keys(Cn(e)))s[u]??="";return s}import{z as Y}from"zod";var jn=Y.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Pn=Y.strictObject({tiers:Y.array(Y.strictObject({id:jn,name:Y.string().trim().min(1).max(80)})).min(1).max(8),assignments:Y.array(Y.strictObject({productVersionId:Y.string().min(1).max(200),tierId:jn,period:Y.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function Dn(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}function Ja(e){let t=ht(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let r=n;if(e.startsWith("<!--",n)){let i=e.indexOf("-->",n+4);n=i<0?e.length:i+2}else{let i="";for(n++;n<e.length;n++){let o=e[n];if(i)o===i&&(i="");else if(o==='"'||o==="'")i=o;else if(o===">")break}}/\{\{|\}\}/.test(e.slice(r,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}import{z as m}from"zod";var T={state:32,enumValues:64,derived:96,bindings:256,controls:64,timers:4,effects:8,depth:12,expressionNodes:2e3},Un=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),L=m.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,63}$/).refine(e=>!Un.has(e),"Reserved UI identifier"),yt=m.union([m.string().max(2e3),m.number().finite(),m.boolean(),m.null()]),ti=m.discriminatedUnion("type",[m.strictObject({type:m.literal("enum"),values:m.array(yt).min(1).max(T.enumValues),default:yt}),m.strictObject({type:m.literal("number"),min:m.number().finite(),max:m.number().finite(),step:m.number().finite().positive(),default:m.number().finite()}),m.strictObject({type:m.literal("text"),maxLength:m.number().int().min(0).max(2e3),default:m.string().max(2e3).nullable()}),m.strictObject({type:m.literal("boolean"),default:m.boolean()})]);function ze(e,t){if(e.type==="enum")return e.values.some(r=>r===t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="text")return t===null||typeof t=="string"&&t.length<=e.maxLength;if(typeof t!="number"||!Number.isFinite(t)||t<e.min||t>e.max)return!1;let n=(t-e.min)/e.step;return Number.isFinite(n)&&Math.abs(n-Math.round(n))<=Math.min(1e-7,Math.max(1,Math.abs(n))*Number.EPSILON*8)}var ni=ti.superRefine((e,t)=>{e.type==="enum"&&new Set(e.values).size!==e.values.length&&t.addIssue({code:"custom",path:["values"],message:"UI enum values must be unique"}),e.type==="number"&&e.min>e.max&&t.addIssue({code:"custom",path:["max"],message:"UI number range is reversed"}),ze(e,e.default)||t.addIssue({code:"custom",path:["default"],message:"UI default must match its state definition"})}),ri=["add","sub","mul","div","min","max","round","floor","eq","ne","gt","gte","lt","lte","and","or","not","if","concat","number","parse_number","money","lookup","now","duration"];function ii(e,t){return e==="now"?t===0:e==="concat"?!0:e==="lookup"?t>=4&&t%2===0:e==="if"?t===3:["sub","div","eq","ne","gt","gte","lt","lte"].includes(e)?t===2:["round","floor","not","number","parse_number","money","duration"].includes(e)?t===1:t>=1}var se=m.lazy(()=>m.union([yt,m.strictObject({ref:L}),m.strictObject({op:m.enum(ri),args:m.array(se).max(T.expressionNodes)}).superRefine((e,t)=>{ii(e.op,e.args.length)||t.addIssue({code:"custom",path:["args"],message:"Invalid UI expression arity"})})]));function H(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function ae(e,t,n){if(!e||typeof e!="object")return!0;if(!H(e))return t.addIssue({code:"custom",path:n,message:"UI objects must be plain data"}),!1;for(let r of Object.keys(e)){if(Un.has(r))return t.addIssue({code:"custom",path:[...n,r],message:"Reserved UI object key"}),!1;let i=Object.getOwnPropertyDescriptor(e,r);if(i&&!Object.hasOwn(i,"value"))return t.addIssue({code:"custom",path:[...n,r],message:"UI objects cannot contain accessors"}),!1}return!0}function be(e,t,n,r){let i=[{value:e,depth:1,path:n}];for(;i.length;){let o=i.pop();if(++r.nodes>T.expressionNodes||o.depth>T.depth){t.addIssue({code:"custom",path:o.path,message:"UI expression budget exceeded"});return}if(!ae(o.value,t,o.path))return;if(H(o.value)&&Array.isArray(o.value.args)){if(o.value.args.length>T.expressionNodes){t.addIssue({code:"custom",path:[...o.path,"args"],message:"UI expression budget exceeded"});return}for(let a=o.value.args.length-1;a>=0;a--)i.push({value:o.value.args[a],depth:o.depth+1,path:[...o.path,"args",a]})}}}var es=m.unknown().superRefine((e,t)=>{be(e,t,[],{nodes:0})}).pipe(se),xt=m.record(L,se).refine(e=>Object.keys(e).length>0&&Object.keys(e).length<=T.state,"UI assignments need 1\u201332 state keys"),oi=m.strictObject({target:L,property:m.enum(["text","visible","disabled","checked","value","class","aria-label","aria-selected","aria-checked","aria-valuetext","tabindex"]),expression:se,className:L.optional()}).superRefine((e,t)=>{e.property==="class"!=(e.className!==void 0)&&t.addIssue({code:"custom",path:["className"],message:"Only class bindings require a safe className"})}),ai=m.discriminatedUnion("type",[m.strictObject({type:m.literal("scroll_latch"),target:L,state:L}),m.strictObject({type:m.literal("input"),target:L,state:L,set:xt.optional()}),m.strictObject({type:m.literal("action"),target:L,set:xt}),m.strictObject({type:m.literal("carousel"),target:L,state:L,initialIndex:m.number().int().nonnegative().optional(),maxWidth:m.number().int().min(1).max(1e4).optional(),previousTarget:L.optional(),nextTarget:L.optional(),inactiveTargets:m.array(L).max(20).optional(),inactiveMaxWidth:m.number().int().min(1).max(1e4).optional()})]),si=m.strictObject({afterMs:m.number().int().min(0).max(6e4),set:xt}),ci=m.strictObject({type:m.literal("mosaic_waves"),target:L,color:m.string().regex(/^#[0-9a-fA-F]{6}$/),hotColor:m.string().regex(/^#[0-9a-fA-F]{6}$/),enabled:se.optional(),speed:m.number().min(0).max(4).optional(),pitch:m.number().min(.05).max(4).optional(),fill:m.number().min(.05).max(1).optional(),feather:m.number().min(0).max(1).optional(),warp:m.number().min(0).max(4).optional(),warpScale:m.number().min(0).max(32).optional(),detailScale:m.number().min(0).max(32).optional(),waveScale:m.number().min(0).max(32).optional(),falloff:m.number().min(.1).max(32).optional(),brightness:m.number().min(0).max(32).optional(),ambient:m.number().min(0).max(1).optional(),gamma:m.number().min(.05).max(8).optional(),vignette:m.number().min(0).max(1).optional(),opacity:m.number().min(0).max(1).optional()}),ui=m.strictObject({type:m.literal("number_counter"),target:L,value:se,prefix:m.string().max(20).optional(),format:m.enum(["number","short"]).optional()}),li=m.strictObject({state:m.record(L,ni).refine(e=>Object.keys(e).length<=T.state,"Too many UI state keys").optional(),derived:m.record(L,se).refine(e=>Object.keys(e).length<=T.derived,"Too many UI derived keys").optional(),bindings:m.array(oi).max(T.bindings).optional(),controls:m.array(ai).max(T.controls).optional(),timers:m.array(si).max(T.timers).optional(),effects:m.array(m.discriminatedUnion("type",[ci,ui])).max(T.effects).optional(),clock:m.boolean().optional()});function pi(e,t){if(!ae(e,t,[])||!H(e))return;for(let[r,i]of[["state",T.state],["derived",T.derived]]){let o=e[r];if(!ae(o,t,[r]))return;if(H(o)&&Object.keys(o).length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}}for(let[r,i]of[["bindings",T.bindings],["controls",T.controls],["timers",T.timers],["effects",T.effects]])if(Array.isArray(e[r])&&e[r].length>i){t.addIssue({code:"custom",path:[r],message:"UI declaration budget exceeded"});return}if(Array.isArray(e.effects)){for(let[r,i]of e.effects.entries())if(!ae(i,t,["effects",r]))return}if(H(e.state))for(let[r,i]of Object.entries(e.state)){if(!ae(i,t,["state",r]))return;if(H(i)&&Array.isArray(i.values)&&i.values.length>T.enumValues){t.addIssue({code:"custom",path:["state",r,"values"],message:"Too many UI enum values"});return}}let n={nodes:0};if(H(e.derived))for(let[r,i]of Object.entries(e.derived))be(i,t,["derived",r],n);for(let r of["bindings","controls","timers"]){let i=e[r];if(Array.isArray(i)){for(let[o,a]of i.entries())if(!(!ae(a,t,[r,o])||!H(a))){if(r==="bindings")be(a.expression,t,[r,o,"expression"],n);else if(ae(a.set,t,[r,o,"set"])&&H(a.set)){if(Object.keys(a.set).length>T.state){t.addIssue({code:"custom",path:[r,o,"set"],message:"Too many UI assignments"});return}for(let[s,u]of Object.entries(a.set))be(u,t,[r,o,"set",s],n)}if(n.nodes>T.expressionNodes)return}}}if(Array.isArray(e.effects))for(let[r,i]of e.effects.entries())H(i)&&i.type==="number_counter"?be(i.value,t,["effects",r,"value"],n):H(i)&&i.enabled!==void 0&&be(i.enabled,t,["effects",r,"enabled"],n)}function Ln(e){let t=[],n=[e];for(;n.length;){let r=n.pop();!r||typeof r!="object"||("ref"in r?t.push(r.ref):n.push(...r.args))}return t}var $n=m.unknown().superRefine(pi).pipe(li).superRefine((e,t)=>{let n=e.state??{},r=e.derived??{},i=new Set([...Object.keys(n),...Object.keys(r)]),o=(y,b)=>{for(let k of Ln(y))i.has(k)||t.addIssue({code:"custom",path:b,message:`Unknown UI reference: ${k}`})};for(let[y,b]of Object.entries(e.derived??{}))Object.hasOwn(n,y)&&t.addIssue({code:"custom",path:["derived",y],message:"UI state and derived identifiers must be distinct"}),o(b,["derived",y]);let a=new Set,s=new Set,u=y=>{if(a.has(y))return!1;if(s.has(y))return!0;a.add(y);for(let b of Ln(r[y]))if(Object.hasOwn(r,b)&&!u(b))return!1;return a.delete(y),s.add(y),!0};for(let y of Object.keys(r))if(!u(y)){t.addIssue({code:"custom",path:["derived",y],message:"Cyclic UI derived references"});break}for(let[y,b]of(e.bindings??[]).entries())o(b.expression,["bindings",y,"expression"]);let f=new Set;for(let[y,b]of(e.effects??[]).entries())f.has(b.target)&&t.addIssue({code:"custom",path:["effects",y,"target"],message:"Effect targets must be unique"}),f.add(b.target),b.type==="number_counter"?(o(b.value,["effects",y,"value"]),typeof b.value=="number"&&Math.abs(b.value)>1e12&&t.addIssue({code:"custom",path:["effects",y,"value"],message:"Counter values must be within the display bound"})):b.enabled!==void 0&&o(b.enabled,["effects",y,"enabled"]);let d=(y,b)=>{for(let[k,w]of Object.entries(y))Object.hasOwn(n,k)||t.addIssue({code:"custom",path:[...b,k],message:"UI assignments can only update declared state"}),o(w,[...b,k])},g=new Set,A=new Set;for(let[y,b]of(e.controls??[]).entries()){if(b.type==="carousel"&&b.inactiveMaxWidth!==void 0&&b.inactiveTargets===void 0&&t.addIssue({code:"custom",path:["controls",y,"inactiveMaxWidth"],message:"Inactive width requires inactive article targets"}),b.type==="carousel")for(let k of b.inactiveTargets??[])(k===b.target||A.has(k))&&t.addIssue({code:"custom",path:["controls",y,"inactiveTargets"],message:"Inactive article targets must have one carousel owner"}),A.add(k);if(b.type==="carousel")for(let k of["previousTarget","nextTarget"]){let w=b[k];w!==void 0&&((w===b.target||g.has(w)||(e.controls??[]).some(U=>U.target===w))&&t.addIssue({code:"custom",path:["controls",y,k],message:"Carousel navigation needs a distinct, exclusive button target"}),g.add(w))}if(b.type!=="action"){let k=Object.hasOwn(n,b.state)?n[b.state]:void 0;(!k||b.type==="input"&&k.type==="enum"&&k.values.some(w=>typeof w!="string"))&&t.addIssue({code:"custom",path:["controls",y,"state"],message:"Control needs a supported declared UI state"}),b.type==="carousel"&&(k?.type!=="number"||!Number.isInteger(k.min)||k.min<0||!Number.isInteger(k.max)||k.step!==1||b.initialIndex!==void 0&&!ze(k,b.initialIndex))&&t.addIssue({code:"custom",path:["controls",y],message:"Carousel needs bounded nonnegative integer index state"}),b.type==="scroll_latch"&&k?.type!=="boolean"&&t.addIssue({code:"custom",path:["controls",y,"state"],message:"Scroll latches require boolean UI state"})}(b.type==="input"||b.type==="action")&&b.set&&d(b.set,["controls",y,"set"])}for(let[y,b]of(e.timers??[]).entries())d(b.set,["timers",y,"set"])});import{z as di}from"zod";var Fn=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,he=di.string().max(16).regex(Fn,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function St(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:r,region:i}=new Intl.Locale(t),o=[n,r,i].filter(Boolean).join("-");return Fn.test(o)?o:null}catch{return null}}var fi=new Set(["TW","HK","MO"]);function zn(e){let[t,n,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let i=n?.length===4?n:void 0,o=n?.length===4?r:n;return i?`zh-${i}`:o&&fi.has(o)?"zh-Hant":"zh-Hans"}function Vn(e,t,n){let r=t.map(i=>({code:he.parse(i),normalized:i}));for(let i of e){let o=St(i);if(!o)continue;let a=r.find(d=>d.normalized===o);if(a)return a.code;let s=zn(o),u=r.filter(d=>zn(d.normalized)===s),f=u.find(d=>!d.normalized.includes("-")||d.normalized===s)??u[0];if(f)return f.code}return n}var mi=4,Q={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:32768,documentBytes:2e5},Ie=c.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),_=c.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gi=c.enum(["none","xs","sm","md","lg","xl"]),bi=c.enum(["none","sm","md","lg","full"]),kt=c.string().regex(/^#[0-9a-fA-F]{6}$/),It=c.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),At=c.union([It,c.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),c.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),c.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Bn=c.object({primary:kt,background:kt,text:kt,radius:bi,font:c.enum(["system","serif","rounded","mono"]),fontAssets:c.object({family:c.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/),faces:c.array(c.object({url:It,weight:c.number().int().min(100).max(900).multipleOf(100),family:c.string().regex(/^[A-Za-z][A-Za-z0-9 -]{0,39}$/).optional()}).strict()).min(1).max(4)}).strict().optional()}).strict(),Ee=c.union([c.enum(["primary","text","muted","background","surface"]),c.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),I=(e,t)=>c.number().int().min(e).max(t),Mn=c.union([c.enum(["fit","fill"]),I(1,1200)]),hi=c.object({top:I(0,200),right:I(0,200),bottom:I(0,200),left:I(0,200)}).strict(),yi=c.object({top:I(-100,200),right:I(-100,200),bottom:I(-100,200),left:I(-100,200)}).strict(),qn=c.object({x:I(0,100),y:I(0,100)}).strict(),xi=c.discriminatedUnion("type",[c.object({type:c.literal("color"),color:Ee}).strict(),c.object({type:c.literal("linear"),angle:I(0,360),stops:c.array(c.object({color:Ee,at:I(0,100)}).strict()).min(2).max(4)}).strict(),c.object({type:c.literal("image"),src:At,fit:c.enum(["cover","contain"]),position:qn.optional()}).strict()]),Si=c.discriminatedUnion("type",[c.object({type:c.literal("rect"),radius:c.union([I(0,200),c.object({topLeft:I(0,200),topRight:I(0,200),bottomRight:I(0,200),bottomLeft:I(0,200)}).strict()])}).strict(),c.object({type:c.literal("pill")}).strict()]),ki=c.object({width:I(0,12),color:Ee,style:c.enum(["solid","dashed"])}).strict(),Ai=c.object({x:I(-40,40),y:I(-40,40),blur:I(0,80),spread:I(-20,40),color:Ee}).strict(),Ii=c.object({font:c.enum(["system","serif","rounded","mono"]),size:I(8,96),weight:c.number().int().min(100).max(900).multipleOf(100),lineHeight:c.number().min(.8).max(3),letterSpacing:c.number().min(-5).max(20),color:Ee,align:c.enum(["start","center","end"]),italic:c.boolean(),decoration:c.enum(["none","underline","line-through"]),transform:c.enum(["none","uppercase"])}).strict().partial(),ce=c.object({width:Mn,height:Mn,padding:hi,margin:yi,gap:I(0,120),grow:c.union([c.boolean(),c.number().min(0).max(12)]),background:xi,opacity:c.number().min(0).max(1),clipContent:c.boolean(),shape:Si,border:ki,shadow:Ai,text:Ii}).strict().partial(),F={id:Ie,name:c.string().trim().min(1).max(60).optional(),hidden:c.boolean().optional(),style:ce.optional(),fallback:_.optional()},Ei=c.object({...F,type:c.literal("text"),productField:c.enum(["name","price","trial","period"]).optional(),feature:c.object({id:c.uuid(),field:c.enum(["name","allowance"])}).strict().optional(),text:_,variant:c.enum(["title","heading","body","caption"])}).strict(),_i=c.object({...F,type:c.literal("image"),src:At,localizedSrc:c.record(he,At).optional(),alt:_,aspect:c.enum(["auto","1:1","4:3","16:9","3:1"]),fit:c.enum(["cover","contain"]),position:qn.optional()}).strict(),wi=c.object({...F,type:c.literal("button"),label:_,variant:c.enum(["primary","secondary","link"]),action:_,purpose:c.enum(["purchase","navigation","close"]).optional(),bind:$e.optional()}).strict(),Oi=c.object({...F,type:c.literal("divider")}).strict(),vi=c.object({...F,type:c.literal("customer_data"),title:_,data:wn}).strict(),Ri=c.object({...F,type:c.literal("spacer"),size:gi}).strict(),Ni=c.object({...F,type:c.literal("custom_html"),html:c.record(he,c.string().max(Q.customHtml)),css:c.string().max(Q.customCss),ui:$n.optional()}).strict(),Ci=c.object({...F,type:c.literal("price"),fallback:_,parts:c.object({current:ce.optional(),original:ce.optional(),period:ce.optional()}).strict().optional()}).strict(),Ti=c.object({...F,type:c.literal("coupon_code"),label:_,fallback:_}).strict(),ji=c.object({...F,type:c.literal("countdown"),source:c.enum(["offer.ends_at","offer.expires_at","fixed"]),at:c.iso.datetime().optional(),granularity:c.enum(["day","hour","minute","second"]),expired:_,fallback:_}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Pi=c.object({...F,type:c.literal("plan_picker"),label:_,fallback:_,planIds:c.array(c.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:c.string().min(1).max(200).optional(),grouping:Pn.safeExtend({monthLabel:_,yearLabel:_,unavailableLabel:_}).optional(),states:c.object({selected:ce.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Dn(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Di=c.object({...F,type:c.literal("quantity_picker"),bind:$e.optional(),label:_,fallback:_,internalFeatureId:c.uuid(),minimumQuantity:I(0,1e4),maximumQuantity:I(0,1e4),defaultQuantity:I(0,1e4),step:I(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),Li=c.discriminatedUnion("type",[c.object({type:c.literal("input"),label:_,keyboard:c.enum(["text","email","tel","url"]),maxLength:I(1,500)}).strict(),c.object({type:c.literal("multiselect"),label:_,min:I(0,50),max:I(1,50)}).strict(),c.object({type:c.literal("select"),label:_,defaultIndex:I(0,49),purpose:c.enum(["option","product","tier"]).optional(),pickerId:Ie.optional(),selectedStyle:ce.optional()}).strict(),c.object({type:c.literal("tabs"),label:_,defaultIndex:I(0,49),purpose:c.literal("tier").optional()}).strict(),c.object({type:c.literal("toggle"),label:_,defaultEnabled:c.boolean()}).strict(),c.object({type:c.literal("carousel"),label:_}).strict()]),G={...F,type:c.literal("stack"),direction:c.enum(["vertical","horizontal","overlay"]),align:c.enum(["start","center","end","stretch"]),justify:c.enum(["start","center","end","between"]),productSlot:c.object({index:I(0,19),period:c.enum(["month","year"]).optional(),requireBinding:c.boolean().optional()}).strict().optional(),interaction:Li.optional(),states:c.object({selected:ce.optional()}).strict().optional(),purpose:c.literal("benefits").optional(),purchaseAction:_.optional(),buttonVariant:c.enum(["primary","secondary","link"]).optional(),bind:$e.optional()},Hn=c.lazy(()=>c.object({...F,type:G.type,direction:G.direction,align:G.align,justify:G.justify,children:c.array(Ui).max(Q.children),productSlot:G.productSlot,interaction:G.interaction,states:G.states,purpose:G.purpose,purchaseAction:G.purchaseAction,buttonVariant:G.buttonVariant,bind:G.bind}).strict()),Ui=c.lazy(()=>c.union([Hn,Ei,_i,wi,Oi,Ri,Ni,Ci,Ti,ji,Pi,Di,vi])),$i=c.union([c.string().max(500),c.number().finite(),c.boolean(),c.null()]),Ae={id:_,event:_,properties:c.record(_,$i).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},zi=c.discriminatedUnion("type",[c.object({...Ae,type:c.literal("navigate"),close:c.literal(!1),pageId:Ie}).strict(),c.object({...Ae,type:c.literal("event"),close:c.boolean()}).strict(),c.object({...Ae,type:c.literal("close"),close:c.literal(!0)}).strict(),c.object({...Ae,type:c.literal("open_url"),close:c.boolean(),url:It}).strict(),c.object({...Ae,type:c.literal("claim_offer"),close:c.boolean(),couponId:c.uuid()}).strict()]),Fi=c.object({defaultLocale:he,locales:c.record(he,c.record(_,c.string().max(Q.stringLength)))}).strict(),Vi=c.enum(["popup","paywall","onboarding","page","banner"]);var Bi=c.object({kind:c.literal("screen"),schemaVersion:c.literal(mi),name:c.string().trim().min(1).max(80),surface:Vi,initialPageId:Ie.optional(),presentation:Rn,theme:Bn,pages:c.array(c.object({id:Ie,name:c.string().trim().min(1).max(60),root:Hn,theme:Bn.optional(),editorPosition:c.object({x:c.number().finite().min(-1e5).max(1e5),y:c.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Q.pages),strings:Fi,actions:c.array(zi).max(Q.actions)}).strict();function W(e,t){for(let n of e.pages)Et(n.root,t)}var ds=Bi.superRefine((e,t)=>{let n=Q;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(g=>g.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>Q.locales&&r(`\u6700\u591A ${Q.locales} \u79CD\u8BED\u8A00`);let o=new Set;for(let d of e.actions)o.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let a=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),a.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let s=new Set,u=0,f=!1;W(e,(d,g)=>{if(u++,g>Q.depth&&(f=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!o.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let A of Object.keys(d.html))i.includes(A)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${A}`);if(d.type==="image")for(let A of Object.keys(d.localizedSrc??{}))i.includes(A)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${A}`)}),u>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),f&&r(`\u5C42\u7EA7\u6700\u591A ${Q.depth} \u5C42`)});function Et(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Et(i,t,n+1,e)}function Gn(e){let t=[],n=new Set;return W(e,r=>{let i=(o,a,s)=>{n.has(o)||(n.add(o),t.push({key:o,nodeId:r.id,nodeType:r.type,field:a,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function Mi(e,t,n){if(t.field==="html"){let r;return W(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=_t(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function qi(e){let t=Gn(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(o=>!Mi(e,o,r)?.trim()).map(o=>o.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Hi(e){return qi(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function fs(e,t){return Vn(t,Hi(e),e.strings.defaultLocale)}function ms(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let a of Gn(e)){if(a.field==="html"||a.field==="src")continue;let s=n[a.key]?.trim()?n[a.key]:r[a.key];s!==void 0&&(i[a.key]=s)}let o=a=>{if(a.type==="stack")return{...a,children:a.children.map(o)};if(a.type==="custom_html"){let s=a.html[t]?.trim()?a.html[t]:a.html[e.strings.defaultLocale];return{...a,html:s===void 0?{}:{[t]:s}}}if(a.type==="image"){let{localizedSrc:s,...u}=a;return{...u,src:s?.[t]??s?.[e.strings.defaultLocale]??a.src}}return a};return{...e,pages:e.pages.map(a=>({...a,root:o(a.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function Gi(e,t){let n=null;return Et(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function _t(e,t){for(let n of e.pages){let r=Gi(n.root,t);if(r)return r}return null}function gs(e){let t=St(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function bs(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;if(W(e,o=>{if(o.type==="quantity_picker"){let s=i[o.id];typeof s=="number"&&Number.isSafeInteger(s)&&s>=o.minimumQuantity&&s<=o.maximumQuantity&&(s-o.minimumQuantity)%o.step===0&&(r[o.id]=s);return}if(o.type==="plan_picker"){let s=i[o.id];typeof s=="string"&&(r[o.id]=n?.pickers[o.id]?.options.includes(s)?s:"");return}if(o.type==="custom_html"&&o.ui)for(let[s,u]of Object.entries(o.ui.state??{})){let f=`${o.id}.${s}`,d=i[f];d!==null&&ze(u,d)&&(r[f]=d)}if(o.type!=="stack"||!o.interaction)return;let a=Object.hasOwn(i,o.id)?i[o.id]:void 0;["select","tabs"].includes(o.interaction.type)&&typeof a=="string"&&o.children.some(s=>s.id===a)&&(r[o.id]=a),o.interaction.type==="toggle"&&typeof a=="boolean"&&(r[o.id]=a)}),e.surface==="paywall"&&typeof i.__page=="string"&&e.pages.some(o=>o.id===i.__page)&&(r.__page=i.__page),n){let o={...r};for(let[a,s]of Object.entries(i))(typeof s=="string"||typeof s=="boolean")&&(o[a]=s);Object.assign(r,Tn(e,o,n))}return r}import{z as C}from"zod";import{z as p}from"zod";import{z as h}from"zod";var ue=N.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),_e=h.string().min(1).max(120),Fe=h.enum(["cap","overflow"]),V=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},we=e=>{try{return e()}catch{return!1}},ks=h.discriminatedUnion("operation",[h.object({operation:h.literal("quote"),overageBehavior:Fe.optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:ue,properties:q}).strict(),h.object({operation:h.literal("consume"),overageBehavior:Fe.optional(),occurredAt:h.iso.datetime({offset:!0}).optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:N,properties:q,idempotencyKey:_e}).strict(),h.object({operation:h.literal("reserve"),occurredAt:h.iso.datetime({offset:!0}).optional(),internal_feature_id:h.uuid(),entityId:h.uuid().optional(),quantity:ue,properties:q,idempotencyKey:_e,expiresInSeconds:h.number().int().min(1).max(86400)}).strict(),h.object({operation:h.literal("confirm"),operationId:h.uuid(),quantity:ue,properties:q.optional(),idempotencyKey:_e}).strict(),h.object({operation:h.literal("refund"),operationId:h.uuid(),quantity:ue,idempotencyKey:_e}).strict(),h.object({operation:h.literal("release"),operationId:h.uuid(),idempotencyKey:_e}).strict()]),Qi=h.object({internal_credit_feature_id:h.uuid().nullable(),internal_metered_feature_id:h.uuid(),dimension:h.string().min(1).max(64),counterKey:h.string().min(1).max(240),cycleStart:h.iso.datetime({offset:!0}),unitCost:N,units:ue,amount:Ue,tier:h.number().int().min(1).max(12).nullable()}).strict(),Oe=h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Qn(e,t){let n=e.reduce((r,i)=>r+V(i.units,12),0n)-V(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var Kn=h.discriminatedUnion("funding",[h.strictObject({funding:h.literal("balance"),sourceId:h.uuid(),rolloverId:h.uuid().nullable(),units:Oe.refine(e=>/[1-9]/.test(e)),amount:Ue}),h.strictObject({funding:h.literal("unbilled"),units:Oe.refine(e=>/[1-9]/.test(e))}),h.object({funding:h.literal("prepaid"),sourceId:h.uuid(),units:ue,amount:Ue,pricing:h.array(Qi).min(1).max(12)}).strict().refine(e=>we(()=>e.pricing.reduce((t,n)=>t+V(n.units,6),0n)===V(e.units,6)&&e.pricing.reduce((t,n)=>t+V(n.amount,12),0n)===V(e.amount,12)&&e.pricing.every(t=>V(t.unitCost,6)*V(t.units,6)===V(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),h.object({funding:h.literal("postpaid"),invoiceLineId:h.uuid().nullable(),units:ue,authorizationId:h.uuid()}).strict()]),Ve=h.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),As=h.object({allowed:h.boolean(),internal_feature_id:h.uuid(),quantity:N,requestedQuantity:N.optional(),overageBehavior:Fe.optional(),reason:Ve.nullable(),allocations:h.array(Kn).max(500)}).strict().refine(e=>we(()=>e.allowed?e.reason===null&&Qn(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>we(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&V(e.requestedQuantity,6)>=V(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Is=h.object({id:h.uuid(),internal_feature_id:h.uuid(),kind:h.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:h.uuid().nullable(),quantity:N,requestedQuantity:N.optional(),overageBehavior:Fe.optional(),accepted:h.boolean(),reason:h.enum([...Ve.options,"expired"]).nullable(),createdAt:h.iso.datetime({offset:!0}),reservationStatus:h.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:h.iso.datetime({offset:!0}).nullable(),allocations:h.array(Kn).max(500)}).strict().refine(e=>we(()=>e.accepted?e.reason===null&&Qn(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>we(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&V(e.requestedQuantity,6)>=V(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as K}from"zod";var Ki=K.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Zi=K.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Zn=K.strictObject({internal_feature_id:K.uuid(),entityId:K.uuid().nullable()}),Os=Zn.extend({quantity:N,expectedRevision:K.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:K.string().min(1).max(120),properties:q.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Wn=Zn.extend({operationId:K.uuid().nullable(),usage:N,capacity:Ki.nullable(),remaining:Zi.nullable(),withinLimit:K.boolean(),revision:K.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:K.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[o,a=""]=(i?r.slice(1):r).split(".");if(o===void 0||o==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(o)*10n**12n+BigInt(a.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var J=p.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),Z=p.iso.datetime({offset:!0}),Wi=p.enum(["access","metered","credit"]),ve={internal_feature_id:p.uuid(),key:oe,name:p.string().min(1).max(120),kind:Wi},Ps=p.object({customerId:p.uuid(),snapshotAt:Z,memberships:p.array(p.object({id:p.uuid(),productId:p.string().min(1).max(255),productVersionId:p.uuid(),billingProductVersionId:p.uuid(),version:p.number().int().positive(),key:p.string().min(1).max(64),name:p.string().min(1).max(120),groupId:p.string().max(255).nullable(),membershipType:p.enum(["main","addon"]),status:p.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:p.boolean(),accessEnabled:p.boolean(),renewalChange:p.object({productVersionId:p.uuid(),name:p.string().min(1).max(120),version:p.number().int().positive(),effectiveAt:Z,benefitsAppliedAt:Z.nullable(),timing:p.enum(["immediate","renewal"]),changeKind:p.enum(["plan","seats","quantity"]),feature:p.strictObject({internal_feature_id:p.uuid(),name:p.string().min(1).max(80),fromQuantity:p.number().int().min(0).max(1e4),toQuantity:p.number().int().min(0).max(1e4)}).optional(),seat:p.object({key:p.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:p.number().int().min(0).max(1e4),toQuantity:p.number().int().min(0).max(1e4)}).strict().nullable(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:p.object({phase:p.enum(["paid","trial"]),startsAt:Z,endsAt:Z.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:p.boolean(),balances:p.array(p.object({...ve,usageType:p.enum(["consumable","non_consumable"]).nullable(),accessible:p.boolean(),unlimited:p.boolean(),available:J,held:J,debt:J,nextExpiresAt:Z.nullable(),usage:Wn.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:p.boolean()}).strict(),Jn=p.enum(["source","usage","transaction","invoice","debt","settlement"]),Be=p.object({at:Z,id:p.uuid(),type:Jn}).strict(),Ds=p.object({type:Jn.nullable(),resourceKey:oe.optional(),kind:p.enum(["purchase","refund"]).optional(),topup:p.boolean().optional(),from:p.iso.date().nullable(),to:p.iso.date().nullable(),after:Be.nullable(),limit:p.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ye={id:p.uuid(),occurredAt:Z},Ji=p.discriminatedUnion("type",[p.strictObject({...ye,type:p.literal("invoice"),status:p.string().min(1).max(80),paid:J,refunded:J,currency:$,externalId:p.string().nullable()}),p.object({...ye,...ve,type:p.literal("source"),reason:p.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:J,unlimited:p.boolean(),status:p.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:Z,expiresAt:Z.nullable(),orderId:p.uuid().nullable(),parentSourceId:p.uuid().nullable()}).strict(),p.object({...ye,type:p.literal("usage"),internal_feature_id:p.uuid(),name:p.string().min(1).max(120),kind:p.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:p.uuid().nullable(),quantity:N,accepted:p.boolean(),reason:p.enum([...Ve.options,"expired"]).nullable(),properties:q,reservationStatus:p.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Z.nullable(),charges:p.array(p.discriminatedUnion("funding",[p.strictObject({funding:p.literal("balance"),sourceId:p.uuid(),rolloverId:p.uuid().nullable(),units:Oe,amount:J}),p.strictObject({funding:p.literal("unbilled"),units:Oe}),p.object({...ve,funding:p.literal("prepaid"),amount:J}).strict(),p.object({funding:p.literal("postpaid"),invoiceId:p.uuid(),invoiceLineId:p.uuid(),authorizationId:p.uuid(),units:N,currency:$}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),p.object({...ye,type:p.literal("transaction"),purpose:p.enum(["product","invoice"]),productVersionId:p.uuid().nullable(),productName:p.string().min(1).max(120).nullable(),productVersion:p.number().int().positive().nullable(),invoiceId:p.uuid().nullable(),orderId:p.uuid(),originalId:p.uuid().nullable(),kind:p.enum(["purchase","refund"]),amountMinor:p.number().int().nonnegative().max(2e8).nullable(),currency:$.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),p.object({...ye,...ve,type:p.literal("debt"),sourceId:p.uuid(),transactionId:p.uuid(),amount:J}).strict(),p.object({...ye,...ve,type:p.literal("settlement"),sourceId:p.uuid(),debtId:p.uuid(),kind:p.enum(["payment","usage_refund","payment_return"]),amount:J}).strict()]),Ls=p.object({customerId:p.uuid(),rows:p.array(Ji).max(50),nextCursor:Be.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var Vs=C.discriminatedUnion("kind",[C.object({kind:C.literal("ledger"),cursor:Be}).strict(),C.object({kind:C.literal("billing"),cursor:C.uuid()}).strict()]),Yi=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Xi=C.record(C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),C.union([C.string().max(500),C.boolean(),C.array(C.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),eo=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function wt(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>wt(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||eo.test(n)||wt(r,t+1)))}var to=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,Bs=C.record(Yi,ne).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!wt(e)&&!to.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var Yn=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),no=C.array(C.object({variable:Yn,componentId:Yn,required:C.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),Ms=C.object({bindings:no,answers:Xi,values:C.record(C.string(),ne).optional()}).strict();function Xn(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},o={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},a=e==="week"?`/${o[r]??o.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?a:`/${n} ${a.slice(1)}${r==="en"?"s":""}`}function Js(e,t){let n=[],r={};W(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let o=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&W(e,a=>{if(a.type==="plan_picker"&&a.id===i.bind?.picker&&o.push(...a.planIds??[]),a.type==="stack"&&a.interaction?.type==="select"&&a.interaction.pickerId===i.bind?.picker)for(let s of a.children)s.type==="stack"&&s.bind?.plan&&o.push(s.bind.plan)}),o.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let a of new Set(o)){let s=t[a]?.prepaid?.find(f=>f.internalFeatureId===i.internalFeatureId)?.terms,u=r[a]??=new Set;(!s||u.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),u.add(i.internalFeatureId)}});for(let[i,o]of Object.entries(t))for(let a of o.prepaid??[])r[i]?.has(a.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${a.internalFeatureId}`);return n}function Ys(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let o={};if(W(e,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker"||a.hidden||(a.bind?.plan??(a.bind?.picker?n[a.bind.picker]:void 0))!==t)return;let u=i.prepaid?.find(d=>d.internalFeatureId===a.internalFeatureId)?.terms,f=n[a.id];if(!u||typeof f!="number"||!Number.isSafeInteger(f)||f<Math.max(u.minimumQuantity,a.minimumQuantity)||f>Math.min(u.maximumQuantity,a.maximumQuantity)||(f-a.minimumQuantity)%a.step!==0||o[a.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");o[a.internalFeatureId]=f}),(i.prepaid??[]).some(a=>o[a.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return o}function ro(e,t,n){let r=e.terms.prices.find(i=>i.currency===t);if(!r||n<e.terms.minimumQuantity||n>e.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:xn({quantity:n,unitAmountMinor:r.amountMinor,...r.pricing?{pricing:r.pricing}:{}}),allowance:An(e.includedAmount,e.terms.units,n)}}function Xs(e,t,n,r){let i=!1;if(W(e,s=>{s.type==="quantity_picker"&&(i=!0)}),!i)return t;let o=structuredClone(t);o.quantities={};let a=new Map;W(e,s=>{if(s.hidden)return!1;if(s.type!=="quantity_picker")return;let u=s.bind?.plan??(s.bind?.picker?n[s.bind.picker]??o.pickers[s.bind.picker]?.selected:void 0),f=typeof u=="string"?o.plans[u]:void 0,d=f?.prepaid?.find(re=>re.internalFeatureId===s.internalFeatureId),g=Math.max(s.minimumQuantity,d?.terms.minimumQuantity??0),A=Math.min(s.maximumQuantity,d?.terms.maximumQuantity??0),y=n[s.id]??s.defaultQuantity,b=typeof y=="number"&&Number.isSafeInteger(y)?y:s.defaultQuantity,k=!!d&&!!f?.available&&b>=g&&b<=A&&(b-s.minimumQuantity)%s.step===0,w=o.quantities[s.id]={minimum:g,maximum:Math.max(g,A),step:s.step,value:b,label:"",available:k};if(!k||!d||!f?.currency||f.amountMinor===void 0)return;let U=ro(d,f.currency,b);w.label=`${new Intl.NumberFormat(r).format(Number(U.allowance))} ${d.name}${["week","month","year"].includes(d.reset)?Xn(d.reset,r,d.resetCount):d.reset==="lifetime"?"":` / ${d.resetCount} ${d.reset}`}`,a.set(String(u),(a.get(String(u))??f.amountMinor)+U.amountMinor)});for(let[s,u]of a){let f=o.plans[s];if(!f?.currency)continue;let d=He(u,f.currency,r);f.price=d;for(let[g,A]of Object.entries(o.nodes)){let y=_t(e,g),b=k=>{if(k.price&&(k.price={...k.price,current:d,original:null}),y?.type==="text"){let w=e.strings.locales[r]?.[y.text]??e.strings.locales[e.strings.defaultLocale]?.[y.text];w?.includes("{{plan.price")&&(k.text=w.replace(/\{\{\s*plan.price\s*\}\}/g,d).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,He(Math.round(u/((f.interval==="year"?12:1)*(f.intervalCount??1))),f.currency,r)))}};A.byPlan?.[s]&&b(A.byPlan[s]),(A.base.planVersionId===s||y&&"bind"in y&&y.bind?.plan===s)&&b(A.base)}}return o}import{z as P}from"zod";var Me=P.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),rc=P.enum([...Me.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),ic=P.enum([...Me.options,"stale_revision"]),io=P.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),oo=P.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),tr={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var er={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function ao(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(er,e)){let r=er[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Me.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:tr[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function oc(e,t){let n=Me.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):tr[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function so(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var nr=P.object({retryable:P.boolean(),recovery:io,reason:oo.optional(),retryAfterSeconds:P.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),co=P.object({requestId:P.uuid().optional(),error:P.object({code:P.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:P.string(),...nr.partial().shape})}),ac=P.object({error:co.shape.error.extend({requestId:P.uuid().optional()})}),sc=P.object({error:P.string(),code:P.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:P.uuid(),...nr.shape});function cc(e,t,n={}){let r=ao(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,o=r.retryable&&n.retryable!==!1&&i!=="recover_operation",a=o?so(n.retryAfter??null):void 0;return{...r,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...n.reason?{reason:n.reason}:{}}}export{Me as a,io as b,oo as c,oc as d,co as e,cc as f,$ as g,or as h,He as i,Ue as j,N as k,Fr as l,q as m,mt as n,xn as o,kn as p,An as q,le as r,Je as s,Pt as t,Ft as u,Zt as v,M as w,tn as x,nn as y,cn as z,ne as A,pt as B,Le as C,Nr as D,zr as E,he as F,St as G,ks as H,Qi as I,Oe as J,As as K,Is as L,Zn as M,Os as N,Wn as O,J as P,Ps as Q,Ds as R,Ls as S,bt as T,sa as U,gn as V,bn as W,xa as X,Gr as Y,hn as Z,In as _,La as $,En as aa,Ua as ba,Cn as ca,Pn as da,Dn as ea,Va as fa,Ba as ga,Ja as ha,Ha as ia,Rn as ja,ei as ka,Q as la,_ as ma,At as na,W as oa,ds as pa,Et as qa,Gn as ra,qi as sa,fs as ta,ms as ua,_t as va,gs as wa,bs as xa,Vs as ya,Xi as za,Bs as Aa,no as Ba,Ms as Ca,Xn as Da,Js as Ea,Ys as Fa,Xs as Ga};
@@ -1 +0,0 @@
1
- import{c as Se}from"./chunk-T5COWMDA.js";import{a as Ee,b as qe,c as De,d as Fe,e as ke}from"./chunk-LC2VUKYM.js";import{a as ye}from"./chunk-EEZLS2YP.js";import{a as y}from"./chunk-26HU2HXU.js";import{b as Ne,e as Te}from"./chunk-SLUA7ABW.js";import{d as Oe}from"./chunk-6HWNW6FJ.js";import{a as K}from"./chunk-DSPLGTQI.js";import{R as Re,da as we}from"./chunk-JVQVQHV2.js";import{Fa as Pe,s as be,va as Ce}from"./chunk-PFHS7HK3.js";function _e(n){let N=n.view;if(!N?.paywall)throw new y("INVALID_REQUEST","The current node is not a Paywall");let e=N.paywall.receiptId,R=N.nodeId,d=N.visit,f=N.paywall.resolution,r=N.paywall,P="document"in f?{document:f.document,offering:f.offering,capabilities:f.capabilities}:null;function u(){let i=r.resolution;return"document"in i?i:P&&{...i,document:P.document,offering:P.offering,capabilities:Ee(i.capabilities,P.capabilities)}}function v(i){if(!qe(i,f))throw new y("INVALID_RESPONSE","The pinned Paywall binding changed")}let k=!1,C=new AbortController,c=(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===R&&i.visit===d&&i.input.type==="paywall_quote")?.requestId??N.paywall.purchaseRequestId,a=0,p=null,O=new Set,U=null,E=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==e)throw new y("INVALID_RESPONSE","Purchase receipt changed");let o=i.run.paywall;return i.purchase??(o?.receiptId===e?o:null)}function q(){if(k)throw new y("IDENTITY_CHANGED","Paywall presentation has closed")}function I(i,o,s){if(q(),o!==a||s!==void 0&&r.quote?.operationId!==s)return!1;let g=r.selectionGeneration??0,m=i.run.paywall;if(m?.receiptId===e){if((m.selectionGeneration??0)<(r.selectionGeneration??0))return!1;v(m.resolution)}let w=A(i),L=m?.receiptId===e&&(m.selectionGeneration??0)>g,$=L?w?.quote??null:w?.quote??r.quote,F=w?.operation??($?.operationId===r.quote?.operationId?r.operation:null);return $&&F&&De(F,{operationId:$.operationId},"Purchase operation changed"),(L||$?.operationId!==r.quote?.operationId)&&(a++,m?.receiptId===e&&(c=m.purchaseRequestId)),r={...r,...m?.receiptId===e?m:{},quote:$,operation:ke(r.operation,F,!0)},!0}function V(i,o,s){return new Promise((g,m)=>{let w=!1,L=()=>{clearTimeout(T),C.signal.removeEventListener("abort",h)},$=te=>{w||(w=!0,L(),g(te))},F=te=>{w||(w=!0,L(),m(te))},h=()=>F(new y("IDENTITY_CHANGED","Paywall presentation has closed")),T=setTimeout(()=>F(new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s)),Math.max(0,o-Date.now()));C.signal.addEventListener("abort",h,{once:!0}),C.signal.aborted&&h(),i.then($,F)})}function M(i){return new Promise(o=>{let s=()=>{clearTimeout(g),C.signal.removeEventListener("abort",s),o()},g=setTimeout(s,i);C.signal.addEventListener("abort",s,{once:!0}),C.signal.aborted&&s()})}function j(i,o){q();let s=E.get(i)??n.pendingCommands?.find(w=>w.requestId===i)??n.pendingCommand;if(s?.operation==="submit"&&s.requestId===i&&s.nodeId===R&&s.visit===d){o.type==="paywall_quote"&&s.input.type==="paywall_quote"&&s.input.predecessor&&!o.predecessor&&(o={...o,predecessor:s.input.predecessor});let w=we.parse(s),L=we.parse({...s,input:o});if(w.operation!=="submit"||L.operation!=="submit"||JSON.stringify(w.input)!==JSON.stringify(L.input))throw new y("CONFLICT","A purchase request cannot change its input");return E.set(i,w),w}let g=n.view;if(!g||g.nodeId!==R||g.visit!==d||g.paywall?.receiptId!==e)throw new y("PRECONDITION_FAILED","The Paywall visit has changed");let m=we.parse({operation:"submit",requestId:i,nodeId:R,visit:d,revision:g.revision,input:structuredClone(o)});if(m.operation!=="submit")throw new y("INVALID_REQUEST","A purchase submission is required");return E.set(i,m),m}async function x(i,o){q();let{requestId:s,input:g}=i,m=Date.now()+3e4;O.add(s);try{let w=await V(n.submit(i),m,s);for(;w.run.pendingRequest?.requestId===s&&Date.now()<m&&!k&&(await M(Math.min(1e3,m-Date.now())),!(k||Date.now()>=m));)w=await V(n.resume(s),m,s);if(k)throw new y("IDENTITY_CHANGED","Paywall presentation has closed");if(w.run.pendingRequest?.requestId===s)throw new y("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,s);if(!I(w,o,g.type==="paywall_confirm"||g.type==="paywall_cancel"?g.operationId:void 0))throw new y("PRECONDITION_FAILED","The purchase selection has changed");U===s&&(U=null)}catch(w){throw U=s,w}finally{O.delete(s)}}async function X(i){if(!r.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let o=i==="confirm"?"paywall_confirm":"paywall_cancel",s=[...E.values(),...n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])].find(m=>m.operation==="submit"&&m.input.type===o&&"operationId"in m.input&&m.input.operationId===r.quote.operationId),g=s?.operation==="submit"&&s.input.type===o&&"operationId"in s.input&&s.input.operationId===r.quote.operationId?s.requestId:crypto.randomUUID();if(await x(j(g,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:r.quote.operationId}),a),!r.operation)throw new y("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(r.operation)}return{get view(){return structuredClone(u())},get quote(){return r.quote?structuredClone(r.quote):null},get operation(){return r.operation?structuredClone(r.operation):null},get webViewUrl(){return n.webViewUrl},get canReselect(){return r.canReselect===!0},get recovery(){let i=n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[]),o=n.pendingPurchase;if(o&&(o.receiptId!==e||o.operationId!==r.quote?.operationId))return{type:"recover",operationId:o.operationId,requestId:i[0]?.requestId??null};let s=ye({quote:r.quote,operation:r.operation,requestId:i[0]?.requestId??U??c,pending:O.size>0||i.length>0||U!==null,destroyed:k,canReselect:r.canReselect});return s.type==="recover"&&s.requestId===null&&!k&&n.hasDurableJournal===!0&&!r.quote&&!r.operation&&(r.selectionGeneration??0)===0&&!o&&!i.length&&!O.size&&!c?{type:"native",operationId:null}:s},get pendingCancellation(){return!k&&(n.pendingCommands??(n.pendingCommand?[n.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===R&&i.visit===d&&i.input.type==="paywall_cancel"&&i.input.operationId===r.quote?.operationId)},async refresh(){q();let i=a,o=await n.get();if(I(o,i),o.run.paywall?.receiptId!==e)throw new y("PRECONDITION_FAILED","Paywall presentation has changed");if(!u()){if("document"in r.resolution||!n.resolvePaywall)throw new y("INVALID_RESPONSE","Public Paywall reader is unavailable");let s=await n.resolvePaywall(r.resolution);q(),v(s),P={document:s.document,offering:s.offering,capabilities:s.capabilities}}return structuredClone(u())},preview(i){let o=u();if(!o)return Promise.reject(new y("PRECONDITION_FAILED","Load the Paywall presentation first"));if(c&&c!==i.requestId&&(p||r.canReselect!==!0))return Promise.reject(new y("COMMAND_PENDING","Retry the original purchase before starting another"));let s=o.document.buttons[i.actionId],g=s?.type==="checkout"?Re(s.product,i.selection,o.capabilities):null;if(!g)return Promise.reject(new y("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let m=Pe(o.document.screen,g,i.selection,o.capabilities),w=c!==i.requestId&&(r.selectionGeneration??0)>0?{operationId:r.quote?.operationId??null,generation:r.selectionGeneration??0}:void 0;if(w&&r.canReselect!==!0)return Promise.reject(new y("COMMAND_PENDING","Original purchase requires authoritative termination"));let L;try{L=j(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:g,...Object.keys(m).length?{featureQuantities:m}:{},...w?{predecessor:w}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{}})}catch(h){return Promise.reject(h)}if(c===i.requestId&&p)return p;c!==i.requestId&&a++;let $=a;c=i.requestId;let F=(async()=>{if(await x(L,$),!r.quote)throw new y("INVALID_RESPONSE","The accepted quote is missing");return Fe(r.quote,{productVersionId:g,featureQuantities:m},"The selected purchase changed"),structuredClone(r.quote)})();return p=F,F.then(()=>{p===F&&(p=null)},h=>{p===F&&(p=null),c===i.requestId&&n.pendingCommand?.requestId!==i.requestId&&h instanceof y&&h.status!==void 0&&h.status<500&&![401,425].includes(h.status)&&(c=null)}),F},confirm:()=>X("confirm"),cancel:()=>X("cancel"),async read(){if(q(),!r.quote)throw new y("INVALID_REQUEST","A quoted purchase is required");let i=r.quote.operationId,o=a,s=n.pendingCommands?.find($=>$.operation==="submit"&&($.input.type==="paywall_confirm"||$.input.type==="paywall_cancel")&&$.input.operationId===i)??n.pendingCommand;s?.operation==="submit"&&(s.input.type==="paywall_confirm"||s.input.type==="paywall_cancel")&&s.input.operationId===i&&await n.settle?.(s.requestId);let g=await n.get(void 0,{receiptId:e,operationId:i});q();let m=A(g);if(m?.quote&&m.quote.operationId!==i||m?.operation&&m.operation.operationId!==i)throw new y("INVALID_RESPONSE","Purchase operation changed");let w=I(g,o,i),L=w?r.operation:m?.operation;if(!L)throw new y("INVALID_RESPONSE","The current purchase result is missing");return w&&O.size===0&&!(n.pendingCommands?.length??(n.pendingCommand?1:0))&&(U=null),structuredClone(L)},destroy(){k=!0,C.abort(),E.clear()}}}function Ae(n){let N=new Set,e=new Set,R=null;function d(f){if(n.reviewing||N.has(f)||e.has(f)||n.stopped)return;e.add(f);let r=async()=>{if(n.reviewing||n.stopped||n.key!==f){e.delete(f);return}if(n.busy||n.client.pendingCommand){setTimeout(()=>{r()},250);return}let P=(async()=>{let v=n.client.view,k=n.expected(),C=k.requestId,J=!1;try{await n.client.submit({operation:"shown",...k})}catch(c){if(!(c instanceof y)||c.code!=="CONFLICT"||c.status!==409||n.client.pendingCommand)throw c;await n.client.get();let a=n.client.view;if(n.stopped||n.reviewing||n.key!==f||!a||!v||a.id!==v.id||a.source.versionId!==v.source.versionId||a.nodeId!==k.nodeId||a.visit!==k.visit||a.revision<=k.revision||a.stopped||!a.screen&&(!a.paywall||a.paywall.receiptId!==v.paywall?.receiptId)||!["running","waiting"].includes(a.status)||n.client.pendingCommand)throw c;let p=n.expected();C=p.requestId,await n.client.submit({operation:"shown",...p})}for(;!n.stopped&&n.key===f&&n.client.pendingCommand?.requestId===C;){if(!n.client.settle)throw new y("COMMAND_PENDING","The original display acknowledgement is still pending");await n.client.settle(C),J=!0,n.client.pendingCommand?.requestId===C&&await new Promise(c=>setTimeout(c,1500))}n.stopped||n.key!==f||(J&&await n.client.get(),!(n.stopped||n.key!==f)&&N.add(f))})();R=P;let u=()=>{R===P&&(R=null),e.delete(f)};P.then(u,v=>{u(),n.busy||n.fail(v)})};r()}return{report:d,get inFlight(){return R}}}function Ve(n){let N={},e=new Map;async function R(d){let f=n.client.view,r=f?.screen,P=r?.customerData.nodes[d.nodeId];if(n.stopped||n.busy||!f||!r||!P)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(d.action)){let a=n.document,p=a?Ce(a,d.nodeId):null,O=p?.type==="customer_data"?p.data.outputs?.[d.action]:void 0;O&&r.outputs.includes(O)?await n.perform(()=>n.client.submit({operation:"submit",...n.expected(),input:{type:"screen",output:O,answers:n.answers,selection:d.value?{[d.nodeId]:d.value}:{}}})):await n.onIntent?.(d,f);return}let v=d.action.startsWith("sources_")?P.resources.find(a=>a.key===d.value):null;if(d.action.startsWith("sources_")&&!v)throw new y("INVALID_REQUEST","Choose a current resource");let k=`${f.visit}:${d.nodeId}:${v?.key??""}`,C=e.get(k)??[null],c=N[d.nodeId]??{page:1,after:null,filter:"all",...v?{resourceKey:v.key}:{}};if(d.action==="filter"){let a=d.value;if(!a||!(P.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(a))throw new y("INVALID_REQUEST","Unknown data filter");c={page:1,after:null,filter:a},C.splice(0,C.length,null)}else if(d.action==="next"||d.action==="sources_next"){let a=v?.sources.at(-1),p=v?a?{kind:"ledger",cursor:{at:a.detail[0],id:a.id,type:"source"}}:null:r.dataCursors[d.nodeId];if(!p||!v&&!P.hasNext)return;C[c.page]=p,c={...c,page:c.page+1,after:p}}else if(d.action==="previous"||d.action==="sources_previous"){if(c.page<=1)return;c={...c,page:c.page-1,after:C[c.page-2]??null}}e.set(k,C),N={...N,[d.nodeId]:c},await n.perform(()=>n.client.get({nodeId:f.nodeId,visit:f.visit,revision:f.revision,components:N}))}return{get queries(){return N},intent:R,reset(){N={},e.clear()}}}function Le(n){let{doc:N,holder:e,reviewHolder:R,mountScreenPreview:d}=n,f=!1,r,P=0,u=null,v="",k=new Map,C=a=>a?`${a.id}:${a.nodeId}:${a.visit}:${a.revision}:${a.paywall?.quote?.operationId??""}`:"";async function J(a){if(n.stopped||!n.client.review)return;f||(v=C(n.client.view),k.set(v,structuredClone(n.answers))),f=!0,r=a,e.hidden=!0,n.suspend(!0),R.hidden=!1;let p=++P;try{let O=await n.client.review(a);if(n.stopped||p!==P||!f)return;if(!O.review)throw new y("INVALID_RESPONSE","Historical projection is missing");u?.destroy(),u=null,R.replaceChildren();let U=O.run.locale.startsWith("zh"),E=N.createElement("p");E.textContent=U?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",R.append(E);for(let[I,V]of O.review.pages.entries()){let M=N.createElement("button");M.type="button",M.textContent=U?`\u7B2C ${I+1} \u9875`:`Page ${I+1}`,M.onclick=()=>{J(V.receiptId)},R.append(M)}if(O.review.page){let I=O.review.page,V=N.createElement("div");if(V.inert=!0,R.append(V),u=d(V,{mode:"live",rendererUrl:n.client.webViewUrl,title:I.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{},onEscape:()=>{c()}}),u.update(I.document,O.run.locale,{serverInput:{bindings:I.inputs,answers:I.answers,values:I.values}}),await u.ready,n.stopped||p!==P||!f)return}let A=U?{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"},q=U?{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 I of[...O.review.coupons.map((V,M)=>`${U?"\u4F18\u60E0\u5238":"Coupon"} ${M+1}: ${A[V.status]}`),...O.review.purchases.map((V,M)=>`${U?"\u8D2D\u4E70":"Purchase"} ${M+1}: ${q[V.status]}`)]){let V=N.createElement("p");V.textContent=I,R.append(V)}n.client.view&&await n.enqueue(n.client.view)}catch(O){if(p!==P||n.stopped)return;u?.destroy(),u=null,R.replaceChildren(),n.fail(O)}}async function c(){if(!f||n.stopped||!n.client.review)return;let a=++P;try{if(await n.client.review(),n.stopped||a!==P)return;f=!1,P++,u?.destroy(),u=null,R.replaceChildren(),R.hidden=!0,e.hidden=!1;let p=n.client.view;C(p)!==v?(k.set(v,structuredClone(n.answers)),n.resetScreen()):(k.delete(v),n.suspend(!1)),p&&await n.enqueue(p)}catch(p){if(a!==P||n.stopped)return;u?.destroy(),u=null,R.replaceChildren(),n.fail(p)}}return{get active(){return f},get receipt(){return r},open:J,exit:c,get drafts(){return new Map([...k].map(([a,p])=>[a,structuredClone(p)]))},stop(){f=!1,P++,u?.destroy(),u=null,R.replaceChildren(),R.hidden=!0,e.hidden=!1}}}function $e(n){if(!n.client.pageExperiments)throw new Error("The Run controller does not support page experiments");let N=n.client.pageExperiments.bind(n.client),e=!1,R=!1,d=0,f=!1,r=!1,P,u=new Map,v=new Set,k={},C=new Map,J=Ne(n.appManifestRelease),c=()=>{for(let A of u.values())A.effect.revert();u.clear();for(let A of C.values())A();C.clear()};function a(A){if(e||v.has(A))return;v.add(A);let q=d;N(n.appManifestRelease,[A]).catch(I=>{v.delete(A),!e&&q===d&&K(n.onError,I)})}async function p(){if(e)return;let A=n.client.view;if(!A||A.stopped||!["running","waiting"].includes(A.status)){d++,c();return}if(f){r=!0;return}f=!0;let q=++d,I=`${A.id}:${A.visit}:${A.revision}`,V=location.href;try{let[M,{applyVisualVariation:j}]=await Promise.all([N(n.appManifestRelease),import("./visual-dom-7IF7ITAK.js")]),x=n.client.view;if(e||q!==d||!x||x.stopped||!["running","waiting"].includes(x.status)||`${x.id}:${x.visit}:${x.revision}`!==I||location.href!==V)return;let X=new Set,i=new Set;for(let o of M.assignments){let s=`${M.payload.environmentId}:${o.experimentKey}`;if(i.add(s),C.has(s)||C.set(s,Te(s,k)),!!o.inExperiment)for(let g of M.payload.experiments){if(g.key!==o.experimentKey||!be(location.href,g.urlPatterns??[]))continue;let m=g.meta?.findIndex(T=>T.key===o.variationKey)??-1,w=g.variations[m];if(!w?.renderGuard)continue;let L=o.receiptId+":"+g.changeId,$=JSON.stringify([o.variationKey,w]);X.add(L);let F=u.get(L);if(F?.signature===$){F.effect.applied&&a(o.receiptId);continue}u.get(L)?.effect.revert(),u.delete(L);let h=j(w,{requireUniqueTargets:!0,boundVariations:g.variations,allowJs:!1,onApplied:()=>a(o.receiptId),onError:T=>K(n.onError,T)});u.set(L,{signature:$,effect:h}),h.applied&&a(o.receiptId)}}for(let[o,s]of u)X.has(o)||(s.effect.revert(),u.delete(o));for(let[o,s]of C)i.has(o)||(s(),C.delete(o))}catch(M){q===d&&c(),!e&&q===d&&K(n.onError,M)}finally{f=!1,r&&!e&&(r=!1,p())}}let O=n.client.subscribe(()=>{d++,p()}),U=Oe(()=>{d++,c(),p()}),E=async()=>{await p(),e||(P=setTimeout(()=>{E()},15e3))};return{async start(){R||e||(R=!0,await E())},refresh:p,destroy(){e=!0,d++,clearTimeout(P),O(),U(),c(),J.destroy()}}}async function In(n,N){let e=N,{mountScreenPreview:R}=await import("./screen-renderer-IZ3VJGU6.js"),{showPaywall:d}=await import("./paywall-6Q3VLXXL.js"),f=e.appManifestRelease?$e({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;f?.start();let r=n.ownerDocument,P=r.activeElement,u=r.createElement("section"),v=r.createElement("div"),k=r.createElement("div"),C=r.createElement("div"),J=r.createElement("button");C.hidden=!0,J.type="button";let c=r.createElement("p"),a=r.createElement("p"),p=r.createElement("button"),O=r.createElement("button"),U=r.createElement("button"),E=r.createElement("dialog"),A;u.dataset.indianaFunnel="",u.setAttribute("aria-busy","false"),u.style.cssText="box-sizing:border-box;width:100%;min-width:0;font:14px/1.5 system-ui,sans-serif;color:#172033;background:#fff",k.style.cssText="display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:12px 20px",c.setAttribute("role","status"),a.setAttribute("role","alert"),a.hidden=!0,p.type=O.type=U.type="button",k.append(p,c,a,U,J,O),u.append(v,C,k),n.append(u);let q=null,I=null,V=null,M="",j="",x="",X="",i="",o=!1,s=0,g=!1,m="",w=null,L=Promise.resolve(),$=null,F=null,h=null,T=null;function te(){return h&&e.client.hasDurableJournal===!0&&T?.acknowledged===!0&&T.operationId===h.operationId&&e.client.view?.id===T.runId&&e.client.view?.status==="closed"&&e.client.view.revision===T.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?h:null}function Ie(t){let l=t.run.paywall;if(T&&t.settlement?.requestId===T.requestId&&t.settlement.state==="settled"&&t.settlement.operationId===null&&t.run.id===T.runId&&t.run.status==="closed"&&!t.run.pendingRequest&&t.run.revision===T.revision+1&&t.run.nodeId===T.nodeId&&t.run.visit===T.visit&&l?.receiptId===T.receiptId&&l.selectionGeneration===T.selectionGeneration&&(l.quote?.operationId??null)===T.operationId&&(l.operation?.operationId??l.quote?.operationId??null)===T.operationId){let S=T.operationId===null&&l.selectionGeneration===0&&!l.quote&&!l.operation&&!l.purchaseRequestId,b=ye({quote:l.quote,operation:l.operation,requestId:l.purchaseRequestId,pending:!1,destroyed:!1,canReselect:l.canReselect});(S||l.canReselect===!0&&b.type==="native")&&(T.acknowledged=!0)}}let le=null,pe=new Set,B={},W=(t,l=null)=>{o||(le=l,a.textContent=t instanceof Error?t.message:"Request failed",a.hidden=!1,U.hidden=e.client.pendingCommand===null,K(e.onError,t))};function ie(){let t=e.client.view;if(!t)throw new y("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision}}let _=Le({client:e.client,doc:r,holder:v,reviewHolder:C,mountScreenPreview:R,get stopped(){return o},get answers(){return B},suspend(t){I?.setSuspended(t)},resetScreen(){M="",j="",x=""},enqueue:Z,fail:W}),ue=Ae({client:e.client,expected:ie,fail:W,get stopped(){return o},get reviewing(){return _.active},get key(){return M},get busy(){return s}}),fe=Ve({client:e.client,expected:ie,perform:re,onIntent:e.onCustomerDataIntent,get stopped(){return o},get busy(){return s},get document(){return q?.document},get answers(){return B}}),ge=t=>t&&(t.screen||t.paywall)?`${t.id}:${t.nodeId}:${t.visit}`:"";function de(){let t=e.client.view;p.disabled=!_.active&&(s>0||!!e.client.pendingCommand||!t?.canBack||t.stopped||!["running","waiting"].includes(t.status)||!ge(t)||j!==ge(t))}async function re(t,l=!1){if(!((s||F||h)&&!l||o||_.active&&!l)){s++,u.setAttribute("aria-busy","true"),de(),a.hidden=!0,le=null;try{if(!l&&ue.inFlight){let b=e.client.view;await ue.inFlight;let G=e.client.view;if(!b||!G||G.id!==b.id||G.nodeId!==b.nodeId||G.visit!==b.visit||G.stopped||!["running","waiting"].includes(G.status))throw new y("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}if(o)return;let S=await t();o||await Z(e.client.view??S.run)}catch(S){W(S,e.client.pendingCommand?.requestId??null)}finally{s=Math.max(0,s-1),u.setAttribute("aria-busy",String(s>0)),o||(U.hidden=e.client.pendingCommand===null,de())}}}function me(){w&&clearTimeout(w),!(o||!V||!["running","waiting"].includes(V.status)&&!e.client.pendingCommand)&&(w=setTimeout(()=>{w=null,he().finally(me)},V.pendingRequest||e.client.pendingCommand?1500:5e3))}async function he(){if(!(o||g||s)){if(_.active){await _.open(_.receipt);return}g=!0;try{let t=e.client.pendingCommand;t&&e.client.settle&&await e.client.settle(t.requestId);let l=e.client.view,S=fe.queries,b=await e.client.get(l?.screen&&Object.keys(S).length?{nodeId:l.nodeId,visit:l.visit,revision:l.revision,components:S}:void 0);!o&&S===fe.queries&&await Z(e.client.view??b.run)}catch(t){W(t)}finally{g=!1}}}function Ue(t){let l=t.screen?.presentation;if(!l||l.type==="inline"){E.open&&E.close(),u.parentElement!==n&&n.append(u);return}u.parentElement!==E&&(E.append(u),n.append(E));let S={sm:420,md:640,lg:900};E.style.cssText=`padding:0;border:0;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);overflow:auto;width:${"size"in l?S[l.size]+"px":"100vw"}`,E.setAttribute("aria-label",(A?.screen===t.screen?.content.document.name?A?.label:void 0)??q?.document?.name??t.screen?.content.document.name??"Funnel"),E.open||(E.showModal(),Se(E,l.type))}async function Me(t){if(o)return;V=t,le&&e.client.pendingCommand?.requestId!==le&&(a.hidden=!0,le=null);let l=t.locale.startsWith("zh");if(J.textContent=l?"\u56DE\u770B":"History",J.hidden=!e.client.review,p.textContent=_.active?l?"\u8FD4\u56DE\u5F53\u524D":"Return to current":l?"\u8FD4\u56DE":"Back",O.textContent=l?"\u5173\u95ED":"Close",U.textContent=l?"\u91CD\u8BD5":"Retry",de(),U.hidden=e.client.pendingCommand===null,c.textContent=t.pendingRequest?l?"\u6B63\u5728\u5904\u7406":"Processing":t.instruction?.type==="wait"?l?"\u7B49\u5F85\u4E2D":"Waiting":"",m!==`${t.revision}:${t.visit}:${t.status}:${t.stopped}`&&(m=`${t.revision}:${t.visit}:${t.status}:${t.stopped}`,K(e.onState,structuredClone(t))),!t.pendingRequest&&["closed","ineligible","failed"].includes(t.status)){oe();return}if(t.stopped||e.client.configurationReady===!1){_.stop(),q?.destroy(),q=null,I?.destroy(),I=null,v.replaceChildren(),M="",j="",x="",i="",E.open&&E.close(),u.hidden=!0,me();return}if(u.hidden=!1,_.active){me();return}let S=ge(t);if(S!==M&&(j="",q?.destroy(),q=null,I?.destroy(),I=null,v.replaceChildren(),M=S,x="",i="",B={...t.answers},fe.reset()),Ue(t),t.screen){let G=t.screen.content;q||(q=R(v,{mode:"live",rendererUrl:e.client.webViewUrl,title:G.document.name,onAction(D,se={},Q={}){if(_.active)return;B={...B,...Q};let z=Object.fromEntries((t.screen?.inputs??[]).filter(({variable:ne})=>Object.hasOwn(B,ne)).map(({variable:ne})=>[ne,B[ne]]));re(()=>e.client.submit({operation:"submit",...ie(),input:{type:"screen",output:D,answers:z,selection:se}}))},onAnswers:D=>{_.active||(B={...B,...D})},onCustomerDataIntent:D=>{_.active||fe.intent(D).catch(W)},onEscape:()=>{_.active||F||h||ce()},onError:D=>W(new Error(D)),onRendered:D=>{if(!D)return ue.report(S);A={screen:G.document.name,label:D},E.open&&E.setAttribute("aria-label",D),ue.report(S)}}));let H={capabilities:t.screen.capabilities,customerData:t.screen.customerData,parameters:t.parameters,serverInput:{bindings:t.screen.inputs,answers:B,values:t.screen.values}},ee=JSON.stringify([G,t.locale,H.parameters,t.screen.inputs,t.screen.values]);if(ee!==x)q.update(G.document,t.locale,H),x=ee,X=JSON.stringify(H.capabilities),i=JSON.stringify(H.customerData);else{let D=JSON.stringify(H.capabilities);D!==X&&(q.updateCapabilities(H.capabilities),X=D),JSON.stringify(H.customerData)!==i&&(q.updateCustomerData(H.customerData),i=JSON.stringify(H.customerData))}await q.ready}else if(t.paywall&&!I){let G=await d(v,{canInteract:()=>!_.active&&!o&&!F&&!h,start:async()=>_e(e.client),onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resolveOfferId:e.resolveOfferId,onEvent:e.onEvent,onOpenUrl:H=>e.onOpenUrl?e.onOpenUrl({receiptId:t.paywall.receiptId,url:H,openIn:"same_window"}):r.defaultView?.location.assign(H),onAction:async H=>{if(_.active)return;let ee=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:t.nodeId,visit:t.visit,revision:t.revision,input:{type:"screen",output:H,answers:{}}});await Z(e.client.view??ee.run)},onError:W,onDismiss:()=>{!_.active&&!o&&!F&&!h&&e.client.view?.visit===t.visit&&ce()}});o?G.host?.destroy():(I=G.host,I?.setSuspended(_.active)),ue.report(S)}if(o)return;j=S,de();let b=t.instruction;if(b&&(b.type==="open_url"||b.type==="event")&&!pe.has(b.receiptId)){let G=r.createElement("button");G.type="button",G.textContent=b.type==="open_url"?`${l?"\u524D\u5F80":"Continue to"} ${new URL(b.url).host}`:l?"\u7EE7\u7EED":"Continue",G.onclick=()=>{let H=ie(),ee=b.type==="open_url"&&!e.onOpenUrl&&b.openIn==="new_window"?He(b.url):null;re(async()=>{let D="success";if(b.type==="open_url")if(e.onOpenUrl)try{D=await e.onOpenUrl({receiptId:b.receiptId,url:b.url,openIn:b.openIn})===!1?"failed":"opened"}catch(Q){K(e.onError,Q),D="failed"}else D=b.openIn==="new_window"&&!ee?"failed":"opened";if(b.type==="event"){if(!e.onEvent)throw new y("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(b.event)}if(o||e.client.view?.nodeId!==H.nodeId||e.client.view.visit!==H.visit)throw new y("PRECONDITION_FAILED","The client action visit changed");let se=await e.client.submit({operation:"submit",...H,input:{type:"client_action",receiptId:b.receiptId,outcome:D}});return pe.add(b.receiptId),b.type==="open_url"&&!e.onOpenUrl&&b.openIn==="same_window"&&r.defaultView?.location.assign(b.url),se})},v.replaceChildren(G)}!t.pendingRequest&&t.status==="completed"&&!pe.has(`complete:${t.id}`)&&(pe.add(`complete:${t.id}`),K(e.onComplete,structuredClone(t))),me()}function He(t){let l=r.defaultView?.open(t,"_blank")??null;return l&&(l.opener=null),l}function Z(t){return de(),L=L.catch(()=>{}).then(()=>Me(t)),L}let Ge=e.client.subscribe(t=>{e.client.configurationReady===!1&&(u.hidden=!0,q?.destroy(),q=null,I?.destroy(),I=null,v.replaceChildren(),M="",j="",x="",i="",E.open&&E.close()),Z(t).catch(W)}),Qe=e.client.subscribeError?.(W);function ce(t){return $||(o||!t&&(F||h)?Promise.resolve():e.client.view&&!["running","waiting"].includes(e.client.view.status)?(oe(),Promise.resolve()):($=re(async()=>{let l=await e.client.submit({operation:"close",...t??ie()});return t&&Ie(l),l},!0).then(()=>{e.client.view?.status==="closed"&&oe()}).finally(()=>{$=null}),$))}function oe(){f?.destroy(),!o&&(o=!0,w&&clearTimeout(w),Ge(),Qe?.(),q?.destroy(),_.stop(),I?.destroy(),E.close(),E.remove(),u.remove(),P instanceof HTMLElement&&P.isConnected&&P.focus(),K(e.onDismiss,V?structuredClone(V):null))}p.onclick=()=>{if(!p.disabled){if(_.active){_.exit();return}re(()=>e.client.submit({operation:"back",...ie()}))}},J.onclick=()=>{_.open()},O.onclick=()=>{F||ce()},U.onclick=()=>{re(()=>e.client.retry())},E.addEventListener("cancel",t=>{t.preventDefault(),F||ce()});try{let t=await e.client.get();await Z(e.client.view??t.run)}catch(t){throw oe(),t}return{destroy:oe,refresh:he,get recovery(){let t=te();if(t)return t;if(!o&&!s&&!F&&I){let l=I.recovery;if(l.type!=="native")return l}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??h?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(F)return F;let t=te();if(t)return Promise.resolve(t);let l=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??h?.operationId??null,S=()=>({type:"recover",operationId:l,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let D=I?.recovery;return Promise.resolve(D&&D.type!=="native"&&D.type!=="cancel"?D:S())}let b=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(D=>D.operation==="close");if(o&&!(b||h&&e.client.view?.status==="closed")||s||g||$||_.active||!I&&!h&&!b)return Promise.resolve(S());let G=I,H=(async()=>{try{if(!h&&b){let Q=await e.client.retry();return await Z(e.client.view??Q.run),S()}if(!h){let Q=await G.prepareFallback();if(Q.type!=="native")return Q;if(e.client.hasDurableJournal!==!0)return S();h=Q}let D=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(D.length){let Q=D.find(ne=>ne.operation==="close");if(!Q||!T||Q.requestId!==T.requestId)return S();let z=await e.client.retry();Ie(z),await Z(e.client.view??z.run)}else{let Q=e.client.view,z=Q?.paywall;if(!Q||!z||z.selectionGeneration===void 0||(z.quote?.operationId??null)!==h.operationId||h.operationId!==null&&z.canReselect!==!0)return S();let ne=z.selectionGeneration,xe=await e.client.get();await Z(e.client.view??xe.run);let Y=e.client.view,ae=Y?.paywall;if(!Y||!ae||!["running","waiting"].includes(Y.status)||Y.stopped||Y.id!==Q.id||Y.nodeId!==Q.nodeId||Y.visit!==Q.visit||ae.receiptId!==z.receiptId||ae.selectionGeneration!==ne||(ae.quote?.operationId??null)!==h.operationId||h.operationId!==null&&ae.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return S();let ve=ie();T={runId:Y.id,operationId:h.operationId,revision:ve.revision,requestId:ve.requestId,nodeId:Y.nodeId,visit:Y.visit,receiptId:ae.receiptId,selectionGeneration:ne,acknowledged:!1},await ce(ve)}let se=te();return se?(oe(),se):S()}catch(D){return W(D),S()}})();F=H;let ee=()=>{F===H&&(F=null)};return H.then(ee,ee),H},review:_.open,exitReview:_.exit,get unappliedDrafts(){return _.drafts}}}export{$e as a,In as b};