@tinkerlandai/longplay-sdk 0.10.40 → 0.10.42

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 (121) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +57 -1
  3. package/README.zh-CN.md +5 -1
  4. package/dist/{ai-usage-DXwAGTxT.d.ts → ai-usage-B-qsCn-k.d.ts} +1 -1
  5. package/dist/{api-r6FfVQpg.d.ts → api-DpRb_Pd3.d.ts} +52 -0
  6. package/dist/check-response-OIBVUP72.js +1 -0
  7. package/dist/chunk-2EVGXJ4R.js +1 -0
  8. package/dist/chunk-3SXPCVIP.js +1 -0
  9. package/dist/chunk-3WTVQ6OV.js +1 -0
  10. package/dist/{chunk-LSPHUA7V.js → chunk-5JRBCW6V.js} +1 -1
  11. package/dist/chunk-5TJISOWN.js +1 -0
  12. package/dist/{chunk-X6ONZGRY.js → chunk-67SIVUOS.js} +1 -1
  13. package/dist/chunk-6XRXHFM6.js +1 -0
  14. package/dist/chunk-7MYS52FL.js +1 -0
  15. package/dist/chunk-ABXCDVC7.js +1 -0
  16. package/dist/{chunk-2DPNSTCN.js → chunk-AC53CUJE.js} +1 -1
  17. package/dist/chunk-ANXDWUPK.js +1 -0
  18. package/dist/chunk-AQONMY2H.js +1 -0
  19. package/dist/chunk-ASL7TJFU.js +1 -0
  20. package/dist/{chunk-ORMQJAQE.js → chunk-AV2WZSII.js} +1 -1
  21. package/dist/chunk-B4AELNLE.js +1 -0
  22. package/dist/{chunk-O4KXODTJ.js → chunk-C4NG6RVA.js} +1 -1
  23. package/dist/chunk-CALDEF4M.js +1 -0
  24. package/dist/chunk-CSLTAXC7.js +1 -0
  25. package/dist/chunk-CWD36SJO.js +1 -0
  26. package/dist/chunk-DCZWNTG2.js +1 -0
  27. package/dist/chunk-DGZCD3AY.js +1 -0
  28. package/dist/{chunk-57GPGWSK.js → chunk-FTGRTYBL.js} +1 -1
  29. package/dist/chunk-HLCDAU5A.js +1 -0
  30. package/dist/{chunk-CZ4TQCUV.js → chunk-HTXB2WVI.js} +1 -1
  31. package/dist/chunk-JWTA2OCB.js +1 -0
  32. package/dist/{chunk-VC2HPREX.js → chunk-KEF6HIFK.js} +1 -1
  33. package/dist/chunk-KP4QI4RX.js +1 -0
  34. package/dist/{chunk-FCDWCQYC.js → chunk-LSVTH3TS.js} +1 -1
  35. package/dist/chunk-LUGZNBIW.js +1 -0
  36. package/dist/{chunk-YLPQLD2A.js → chunk-LZ3OJYBY.js} +1 -1
  37. package/dist/{chunk-5DZJCFNQ.js → chunk-MEDW4N3F.js} +1 -1
  38. package/dist/{chunk-7QDT6DO7.js → chunk-MPD3UIY4.js} +1 -1
  39. package/dist/chunk-MWICFZUF.js +1 -0
  40. package/dist/{chunk-POCDWUD3.js → chunk-NVF54BDR.js} +1 -1
  41. package/dist/{chunk-C2KT5ZFU.js → chunk-O6CUNETH.js} +1 -1
  42. package/dist/chunk-OXXPMJRJ.js +1 -0
  43. package/dist/{chunk-P6C3PNMQ.js → chunk-P6TNBX2S.js} +1 -1
  44. package/dist/{chunk-EREQZWGI.js → chunk-PBZSOTKZ.js} +1 -1
  45. package/dist/chunk-QHWR5UHD.js +1 -0
  46. package/dist/{chunk-33ZVZOSC.js → chunk-RDUKCMST.js} +1 -1
  47. package/dist/{chunk-ASDJTOGM.js → chunk-RJY5CUTB.js} +1 -1
  48. package/dist/chunk-S7A3IBAF.js +10 -0
  49. package/dist/{chunk-QZTTKH2H.js → chunk-SVLEVNHP.js} +1 -1
  50. package/dist/{chunk-WLGLQJ6M.js → chunk-TL67SYPH.js} +1 -1
  51. package/dist/{chunk-YY445FBU.js → chunk-UJMP7AMY.js} +1 -1
  52. package/dist/{chunk-67AY54E2.js → chunk-V65FSNYO.js} +1 -1
  53. package/dist/chunk-VILB5M4X.js +1 -0
  54. package/dist/{chunk-RV6UAUK2.js → chunk-ZICZN6WO.js} +1 -1
  55. package/dist/{configuration-sync-BHrAf-ql.d.ts → configuration-sync-7ruSsSrL.d.ts} +150 -1
  56. package/dist/content-KSIF5AXD.js +1 -0
  57. package/dist/funnel-host-purchase-YNC4LQJS.js +1 -0
  58. package/dist/{funnel-local-client-DR8OpKGU.d.ts → funnel-local-client-BMxDQWE6.d.ts} +51987 -22983
  59. package/dist/{funnel-node-evaluation-COxXtZEQ.d.ts → funnel-node-evaluation-COIh1hKs.d.ts} +3 -0
  60. package/dist/funnel-paywall-prerender-DAAQUEEZ.js +1 -0
  61. package/dist/{funnel-process-client-C87U4r_G.d.ts → funnel-process-client-DNR9nHs8.d.ts} +7338 -3163
  62. package/dist/funnel-route-prediction-XGCMCIKA.js +1 -0
  63. package/dist/funnel-route-source-O76QSUYU.js +1 -0
  64. package/dist/funnel-runtime-host-WPU42YVT.js +1 -0
  65. package/dist/index.d.ts +273 -22
  66. package/dist/index.js +1 -1
  67. package/dist/merchant-bridge-contracts-FB63H7NE.js +1 -0
  68. package/dist/native-shell.js +1 -1
  69. package/dist/openrouter.d.ts +2 -2
  70. package/dist/openrouter.js +1 -1
  71. package/dist/operation-contracts-YSFIINLK.js +1 -0
  72. package/dist/page.d.ts +1 -1
  73. package/dist/page.js +1 -1
  74. package/dist/paywall-PZ4BBEFG.js +1 -0
  75. package/dist/paywall-content-5IWLT7YD.js +1 -0
  76. package/dist/paywall-session-K7GPR3UF.js +1 -0
  77. package/dist/popup.d.ts +2 -2
  78. package/dist/popup.js +1 -1
  79. package/dist/{presentation-loading-B_v5XZtM.d.ts → presentation-loading-B2OeFzRN.d.ts} +1 -0
  80. package/dist/react-native.d.ts +6 -6
  81. package/dist/react-native.js +1 -1
  82. package/dist/screen-renderer-RDXKWHYE.js +1 -0
  83. package/dist/server.d.ts +34204 -17797
  84. package/dist/server.js +1 -1
  85. package/dist/{visual-dom-5LUN4AHO.js → visual-dom-IN6DRNX3.js} +1 -1
  86. package/dist/visual.js +1 -1
  87. package/package.json +1 -1
  88. package/dist/check-response-DRQCUWDW.js +0 -1
  89. package/dist/chunk-3NCMYTNG.js +0 -1
  90. package/dist/chunk-4TEZZZYK.js +0 -1
  91. package/dist/chunk-6PG3AS3G.js +0 -1
  92. package/dist/chunk-AZFWG352.js +0 -1
  93. package/dist/chunk-BYP4KVB3.js +0 -10
  94. package/dist/chunk-C3GYAKIU.js +0 -1
  95. package/dist/chunk-ESAHTG3Y.js +0 -1
  96. package/dist/chunk-GC6JBIRQ.js +0 -1
  97. package/dist/chunk-IJKAQNK6.js +0 -1
  98. package/dist/chunk-IOJVF52Q.js +0 -1
  99. package/dist/chunk-OOD2VDDP.js +0 -1
  100. package/dist/chunk-P23JOPR5.js +0 -1
  101. package/dist/chunk-PJS7M6X3.js +0 -1
  102. package/dist/chunk-PZOQV6MU.js +0 -1
  103. package/dist/chunk-RFNIGJOL.js +0 -1
  104. package/dist/chunk-RULQQ7WI.js +0 -1
  105. package/dist/chunk-U7GH4VME.js +0 -1
  106. package/dist/chunk-VOKEZHAH.js +0 -1
  107. package/dist/chunk-XDOKFAE6.js +0 -1
  108. package/dist/chunk-Y6HL2IY2.js +0 -1
  109. package/dist/content-QUEVNSXD.js +0 -1
  110. package/dist/funnel-host-purchase-LMVMJNUO.js +0 -1
  111. package/dist/funnel-paywall-prerender-LGUSHEP3.js +0 -1
  112. package/dist/funnel-runtime-host-H5FM67UC.js +0 -1
  113. package/dist/merchant-bridge-contracts-LZSQYE3O.js +0 -1
  114. package/dist/operation-contracts-O7TCDGV4.js +0 -1
  115. package/dist/paywall-UANWOKKC.js +0 -1
  116. package/dist/paywall-content-CHPX2P77.js +0 -1
  117. package/dist/paywall-session-3BNUC5ZE.js +0 -1
  118. package/dist/screen-renderer-FFVZ64MR.js +0 -1
  119. /package/dist/{chunk-RGEBK6UF.js → chunk-GPJF3T43.js} +0 -0
  120. /package/dist/{chunk-OJM6ORHE.js → chunk-RA7GZ67U.js} +0 -0
  121. /package/dist/{chunk-CILM5XMH.js → chunk-WPFTSHP2.js} +0 -0
@@ -0,0 +1 @@
1
+ import{b as e}from"./chunk-GPJF3T43.js";var y=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),z=e.discriminatedUnion("type",[e.object({type:e.literal("fixed"),productVersionId:e.string().min(1).max(200)}).strict(),e.object({type:e.literal("picker"),pickerId:y,allowedProductVersionIds:e.array(e.string().min(1).max(200)).min(1).max(20)}).strict().refine(t=>new Set(t.allowedProductVersionIds).size===t.allowedProductVersionIds.length,"Product choices must be unique")]),x=e.strictObject({min:e.number().finite().min(1).max(1800),max:e.number().finite().min(1).max(1800),viewport:e.number().finite().min(1).max(100)}).refine(t=>t.min<=t.max,"Desktop width range is reversed"),f={desktopWidth:x.optional(),mobile:e.enum(["sheet","fullscreen"]).optional(),backdrop:e.enum(["none","scrim","dim","strong-dim","blur"]).optional()},G=e.discriminatedUnion("type",[e.strictObject({type:e.literal("modal"),position:e.enum(["center","top","bottom"]).optional(),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("sheet"),size:e.enum(["sm","md","lg"]),...f}),e.strictObject({type:e.literal("fullscreen")}),e.strictObject({type:e.literal("inline")})]),V={sm:360,md:420,lg:560};var c=e.json().superRefine((t,i)=>{let s=0;function o(n,r){if(++s>1e4||r>20){i.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof n=="string"&&(n.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(n))&&i.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(n))n.forEach(a=>o(a,r+1));else if(n&&typeof n=="object")for(let[a,u]of Object.entries(n))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved JSON property"}),o(u,r+1)}o(t,0),new TextEncoder().encode(JSON.stringify(t)).byteLength>65536&&i.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),l=e.record(e.string().min(1).max(128),c).superRefine((t,i)=>{(!c.safeParse(t).success||Object.keys(t).length>128||new TextEncoder().encode(JSON.stringify(t)).byteLength>65536||["__proto__","constructor","prototype"].some(s=>Object.hasOwn(t,s)))&&i.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),S=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"]),d=l.superRefine((t,i)=>{function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o)){if(n==="$savedGroup"&&!e.strictObject({id:e.uuid(),attributeKey:e.string().min(1).max(128).optional()}).safeParse(r).success&&i.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!n.startsWith("$")&&n.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&i.addIssue({code:"custom",message:"Reserved attribute path"}),n.startsWith("$")&&!S.has(n)&&i.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${n}`}),["$regex","$regexi"].includes(n)&&typeof r=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(r)||[...r.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||n==="$regexi"&&/[^\x00-\x7f]/.test(r.replace(/\\u([0-9a-f]{4})/gi,(a,u)=>String.fromCharCode(Number.parseInt(u,16)))))&&i.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(r)}catch{i.addIssue({code:"custom",message:"Invalid regular expression"})}}s(r)}}typeof t.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(t.source)&&("operator"in t||"predicates"in t||"groupId"in t)&&i.addIssue({code:"custom",message:"Obsolete condition protocol"}),s(t)}),w=e.discriminatedUnion("type",[e.strictObject({type:e.literal("condition"),condition:d}),e.strictObject({type:e.literal("list"),attributeKey:e.string().min(1).max(128),values:e.array(e.union([e.string(),e.number().finite()])).max(1e5)})]).refine(t=>t.type!=="list"||new TextEncoder().encode(JSON.stringify(t.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function $(t){let i=new Set;function s(o){if(Array.isArray(o))o.forEach(s);else if(o&&typeof o=="object")for(let[n,r]of Object.entries(o))n==="$savedGroup"&&r&&typeof r=="object"&&!Array.isArray(r)&&typeof r.id=="string"?i.add(r.id):["$inGroup","$notInGroup"].includes(n)&&typeof r=="string"?i.add(r):["$eq","$ne","$in","$nin","$ini","$nini"].includes(n)||s(r)}return s(t),[...i]}var O=e.record(e.uuid(),w).superRefine((t,i)=>{let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:"Missing saved group dependency"});return}s.add(r),a.type==="condition"&&$(a.condition).forEach(n),s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),g=e.tuple([e.number().min(0).max(1),e.number().min(0).max(1)]).refine(([t,i])=>t<=i),h=e.strictObject({attribute:e.string().optional(),seed:e.string().min(1),hashVersion:e.literal(2),ranges:e.array(g).min(1).max(100)}),j=e.strictObject({id:e.string().min(1).max(128),condition:d,gate:e.boolean().optional()}),p={id:e.string().max(128).optional(),condition:d.optional(),parentConditions:e.array(j).max(50).optional(),filters:e.array(h).max(20).optional()},v=e.union([e.strictObject({...p}),e.strictObject({...p,force:c,coverage:e.number().min(0).max(1).optional(),range:g.optional(),seed:e.string().min(1).optional(),hashAttribute:e.string().optional(),hashVersion:e.literal(2).optional()}),e.strictObject({...p,type:e.literal("experiment-ref"),experimentId:e.uuid(),values:e.record(e.string().min(1),c),meta:e.record(e.string().min(1),e.strictObject({passthrough:e.boolean()})).optional()})]),k=e.strictObject({defaultValue:c,rules:e.array(v).max(100)}),U=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),k).superRefine((t,i)=>{Object.keys(t).length>100&&i.addIssue({code:"custom",message:"Too many Features"});let s=new Set,o=new Set;function n(r){if(s.has(r)){i.addIssue({code:"custom",message:`Cyclic Feature dependency: ${r}`});return}if(o.has(r))return;let a=t[r];if(!a){i.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${r}`});return}s.add(r);for(let u of a.rules)for(let m of u.parentConditions??[])n(m.id);s.delete(r),o.add(r)}Object.keys(t).forEach(n)}),F=e.strictObject({name:e.string().max(80),reason:e.string().max(500),dateStarted:e.iso.datetime({offset:!0}),dateEnded:e.iso.datetime({offset:!0}).nullable(),coverage:e.number().min(0).max(1),variationWeights:e.array(e.number().min(0).max(1)).min(2).max(20).refine(t=>Math.abs(t.reduce((i,s)=>i+s,0)-1)<=.01),condition:d,savedGroups:e.array(e.strictObject({match:e.enum(["any","all","none"]),ids:e.array(e.uuid()).min(1)})).max(50),namespace:e.strictObject({id:e.uuid(),ranges:e.array(g).min(1)}).nullable(),seed:e.string().min(1).max(128)}),A=e.strictObject({key:e.string().min(1).max(128),name:e.string().min(1).max(80),hypothesis:e.string().max(2e3),status:e.enum(["draft","running","stopped"]),hashAttribute:e.string().min(1).max(128),fallbackAttribute:e.string().max(128).nullable(),hashVersion:e.literal(2),disableStickyBucketing:e.boolean(),bucketVersion:e.number().int().min(0).max(1e3),minBucketVersion:e.number().int().min(0).max(1e3),variations:e.array(e.strictObject({id:e.string().min(1),key:e.string().min(1),name:e.string().max(80),description:e.string().max(500)})).min(2).max(20),phases:e.array(F).min(1).max(100),releasedVariationId:e.string().nullable(),excludeFromPayload:e.boolean(),statusSchedule:e.strictObject({startAt:e.iso.datetime({offset:!0}).nullable(),stopAt:e.iso.datetime({offset:!0}).nullable(),stopAfter:e.strictObject({value:e.number().int().positive().max(36500),unit:e.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((t,i)=>{(t.minBucketVersion>t.bucketVersion||t.statusSchedule?.stopAt&&t.statusSchedule?.stopAfter||t.phases.some((s,o)=>{if(o===0)return!1;let n=t.phases[o-1];return!n?.dateEnded||Date.parse(s.dateStarted)<Date.parse(n.dateStarted)||Date.parse(n.dateEnded)>Date.parse(s.dateStarted)})||new Set(t.variations.map(s=>s.key)).size!==t.variations.length||new Set(t.variations.map(s=>s.id)).size!==t.variations.length||t.releasedVariationId!==null&&!t.variations.some(s=>s.id===t.releasedVariationId)||t.statusSchedule?.startAt&&t.statusSchedule?.stopAt&&Date.parse(t.statusSchedule.startAt)>=Date.parse(t.statusSchedule.stopAt)||t.phases.some(s=>s.dateEnded&&Date.parse(s.dateStarted)>=Date.parse(s.dateEnded)||s.namespace?.ranges.some(([o,n],r,a)=>o>=n||a.some(([u,m],b)=>b!==r&&o<m&&u<n)))||t.phases.some(s=>s.variationWeights.length!==t.variations.length))&&i.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var I=A.safeExtend({filters:e.array(h).optional()}),D=e.strictObject({experiments:e.record(e.uuid(),I),savedGroups:O}),E=e.strictObject({attributeName:e.string(),attributeValue:e.string(),assignments:e.record(e.string(),e.string())}),M=e.strictObject({snapshot:D,attributes:l,results:l,stickyBucketAssignmentDocs:e.record(e.string(),E)}),W=e.strictObject({variantKey:e.string().nullable(),bucketVersion:e.number().int().min(0),source:e.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:e.number().min(0).max(1).optional(),stickyBucketUsed:e.boolean().optional(),hashUsed:e.boolean().optional()});export{z as a,G as b,V as c,c as d,l as e,d as f,$ as g,E as h};
@@ -0,0 +1 @@
1
+ import{b as Wn}from"./chunk-JWTA2OCB.js";import{a as xn,b as Gn,c as dn,d as cn,e as Ue,f as Qn,h as Jn,i as jn,j as zn,k as Bn}from"./chunk-HTXB2WVI.js";import{b as kn,c as Yn}from"./chunk-KEF6HIFK.js";import{a as Ln}from"./chunk-W32FI2A2.js";import{c as Hn,e as Vn,f as Un,h as Mn,i as Fe,j as Ze,k as $n,l as Ke}from"./chunk-P6TNBX2S.js";import{K as Xe}from"./chunk-DCZWNTG2.js";import{a as Ve,d as Tn}from"./chunk-B4AELNLE.js";import{c as An,e as Sn,f as Nn,g as On,h as Fn,i as _n}from"./chunk-AQONMY2H.js";import{b as qn}from"./chunk-RDUKCMST.js";import{B as un}from"./chunk-KP4QI4RX.js";import{w as Rn}from"./chunk-5TJISOWN.js";import{t as Dn}from"./chunk-7MYS52FL.js";import{C as En}from"./chunk-MWICFZUF.js";import{a as m}from"./chunk-TL67SYPH.js";import{a as Pe}from"./chunk-DSPLGTQI.js";async function pn(t){let{session:v,load:R}=st(t);try{return await R(),v}catch(e){throw v.destroy(),e}}function st(t){let v=t.view;if(!v?.paywall)throw new m("INVALID_REQUEST","The current node is not a Paywall");let R=v.paywall.receiptId,e=v.nodeId,y=v.visit,N=v.paywall.resolution,o=v.paywall,L="document"in N?{document:N.document,offering:N.offering,capabilities:N.capabilities}:null;function d(){let i=o.resolution;return"document"in i?i:L&&{...i,document:L.document,offering:L.offering,capabilities:An(i.capabilities,L.capabilities)}}function I(i){if(!Sn(i,N))throw new m("INVALID_RESPONSE","The pinned Paywall binding changed")}let E=!1,M=new Set,ne=null;function w(){let i=d();if(i&&!E)for(let l of M)Pe(l,structuredClone(i))}async function V(){F();let i=d();if(i)return structuredClone(i);if(!ne){let l=(async()=>{if("document"in o.resolution||!t.resolvePaywall)throw new m("INVALID_RESPONSE","Public Paywall reader is unavailable");let C=await kn(t,o.resolution);return F(),I(C),L={document:C.document,offering:C.offering,capabilities:C.capabilities},w(),d()})();ne=l;let a=()=>{ne===l&&(ne=null)};l.then(a,a)}return ne.then(l=>structuredClone(l))}let s=new AbortController,T=(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).find(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_quote")?.requestId??v.paywall.purchaseRequestId,W=0,J=null,Q=new Set,D=null,j=new Map;function A(i){if(i.purchase&&i.purchase.receiptId!==R)throw new m("INVALID_RESPONSE","Purchase receipt changed");let l=i.run.paywall;return i.purchase??(l?.receiptId===R?l:null)}function F(){if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed")}function _(i,l,a){if(F(),l!==W||a!==void 0&&o.quote?.operationId!==a)return!1;let C=o.selectionGeneration??0,c=i.run.paywall;if(c?.receiptId===R){if((c.selectionGeneration??0)<(o.selectionGeneration??0))return!1;I(c.resolution)}let u=A(i),b=c?.receiptId===R&&(c.selectionGeneration??0)>C,P=b?u?.quote??null:u?.quote??o.quote,Z=u?.operation??(P?.operationId===o.quote?.operationId?o.operation:null);return o.quote&&P&&Fn(o.quote,P),P&&Z&&Nn(Z,{operationId:P.operationId,membershipId:un(P)?P.membershipId:null,...un(P)?{featureQuantities:P.featureQuantities??{}}:{}},"Purchase operation changed"),(b||P?.operationId!==o.quote?.operationId)&&(W++,c?.receiptId===R&&(T=c.purchaseRequestId)),c?.canReselect===!0&&c.purchaseRequestId===D&&!(t.pendingCommands??[t.pendingCommand]).some($=>$?.requestId===D)&&(D=null),o={...o,...c?.receiptId===R?c:{},...a!==void 0&&!b&&u?.canReselect!==void 0?{canReselect:u.canReselect}:{},quote:P,operation:_n(o.operation,Z,!0)},w(),!0}function pe(i,l,a){return new Promise((C,c)=>{let u=!1,b=()=>{clearTimeout(le),s.signal.removeEventListener("abort",$)},P=Ee=>{u||(u=!0,b(),C(Ee))},Z=Ee=>{u||(u=!0,b(),c(Ee))},$=()=>Z(new m("IDENTITY_CHANGED","Paywall presentation has closed")),le=setTimeout(()=>Z(new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a)),Math.max(0,l-Date.now()));s.signal.addEventListener("abort",$,{once:!0}),s.signal.aborted&&$(),i.then(P,Z)})}function Re(i){return new Promise(l=>{let a=()=>{clearTimeout(C),s.signal.removeEventListener("abort",a),l()},C=setTimeout(a,i);s.signal.addEventListener("abort",a,{once:!0}),s.signal.aborted&&a()})}function se(i,l){F();let a=j.get(i)??t.pendingCommands?.find(u=>u.requestId===i)??t.pendingCommand;if(a?.operation==="submit"&&a.requestId===i&&a.nodeId===e&&a.visit===y){l.type==="paywall_quote"&&a.input.type==="paywall_quote"&&a.input.predecessor&&!l.predecessor&&(l={...l,predecessor:a.input.predecessor});let u=Xe.parse(a),b=Xe.parse({...a,input:l});if(u.operation!=="submit"||b.operation!=="submit"||JSON.stringify(u.input)!==JSON.stringify(b.input))throw new m("CONFLICT","A purchase request cannot change its input");return j.set(i,u),u}let C=t.view;if(!C||C.nodeId!==e||C.visit!==y||C.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","The Paywall visit has changed");let c=Xe.parse({operation:"submit",requestId:i,nodeId:e,visit:y,revision:C.revision,input:structuredClone(l)});if(c.operation!=="submit")throw new m("INVALID_REQUEST","A purchase submission is required");return j.set(i,c),c}async function te(i,l){F();let{requestId:a,input:C}=i,c=Date.now()+3e4;Q.add(a);try{let u=await pe(t.submit(i),c,a);for(;u.run.pendingRequest?.requestId===a&&Date.now()<c&&!E&&(await Re(Math.min(1e3,c-Date.now())),!(E||Date.now()>=c));)u=await pe(t.resume(a),c,a);if(E)throw new m("IDENTITY_CHANGED","Paywall presentation has closed");if(u.run.pendingRequest?.requestId===a)throw new m("COMMAND_PENDING","The purchase command is still pending; retry the original request",202,a);if(!_(u,l,C.type==="paywall_confirm"||C.type==="paywall_cancel"?C.operationId:void 0))throw new m("PRECONDITION_FAILED","The purchase selection has changed");D===a&&(D=null)}catch(u){if(D=a,C.type==="paywall_quote"&&t.settle&&!E&&u instanceof m&&u.status!==void 0&&![401,425].includes(u.status)&&!u.retryable&&u.recovery!=="recover_operation")try{if((await pe(t.settle(a),c,a)).settlement?.state==="settled"){let P=await pe(t.get(),c,a);_(P,l)&&P.run.paywall?.purchaseRequestId===a&&o.canReselect===!0&&j.delete(a)}}catch{}throw u instanceof m&&u.code==="COMMAND_PENDING"&&u.status===void 0&&j.delete(a),u}finally{Q.delete(a)}}async function we(i){if(!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let l=i==="confirm"?"paywall_confirm":"paywall_cancel",a=[...j.values(),...t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])].find(c=>c.operation==="submit"&&c.input.type===l&&"operationId"in c.input&&c.input.operationId===o.quote.operationId),C=a?.operation==="submit"&&a.input.type===l&&"operationId"in a.input&&a.input.operationId===o.quote.operationId?a.requestId:crypto.randomUUID();if(await te(se(C,{type:i==="confirm"?"paywall_confirm":"paywall_cancel",operationId:o.quote.operationId,...i==="confirm"&&o.quote.merchantTerms?{merchantConfirmation:Rn(o.quote.merchantTerms)}:{}}),W),!o.operation)throw new m("INVALID_RESPONSE","The accepted purchase result is missing");return structuredClone(o.operation)}let G={get view(){return structuredClone(d())},get quote(){return o.quote?structuredClone(o.quote):null},get operation(){return o.operation?structuredClone(o.operation):null},get webViewUrl(){return t.webViewUrl},get locale(){return t.view?.locale??v.locale},get canReselect(){return o.canReselect===!0&&D===null},get recovery(){let i=t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[]),l=t.pendingPurchase;if(l&&(l.receiptId!==R||l.operationId!==o.quote?.operationId))return{type:"recover",operationId:l.operationId,requestId:i[0]?.requestId??null};let a=Ve({quote:o.quote,operation:o.operation,requestId:i[0]?.requestId??D??T,pending:Q.size>0||i.length>0||D!==null,destroyed:E,canReselect:o.canReselect});return a.type==="recover"&&a.requestId===null&&!E&&t.hasDurableJournal===!0&&!o.quote&&!o.operation&&(o.selectionGeneration??0)===0&&!l&&!i.length&&!Q.size&&!T?{type:"native",operationId:null}:a},get pendingCancellation(){return!E&&(t.pendingCommands??(t.pendingCommand?[t.pendingCommand]:[])).some(i=>i.operation==="submit"&&i.nodeId===e&&i.visit===y&&i.input.type==="paywall_cancel"&&i.input.operationId===o.quote?.operationId)},subscribe(i){return E?()=>{}:(M.add(i),()=>M.delete(i))},async refresh(){F();let i=W,l=await t.get();if(_(l,i),l.run.paywall?.receiptId!==R)throw new m("PRECONDITION_FAILED","Paywall presentation has changed");return V()},preview(i){let l=d();if(!l)return Promise.reject(new m("PRECONDITION_FAILED","Load the Paywall presentation first"));if(T&&T!==i.requestId&&(J||o.canReselect!==!0))return Promise.reject(new m("COMMAND_PENDING","Retry the original purchase before starting another"));let a=l.document.buttons[i.actionId],C=a?.type==="checkout"?qn(a.product,i.selection,l.capabilities):null;if(!C)return Promise.reject(new m("PRODUCT_UNAVAILABLE","Choose an available Product in this purchase area"));let c=Dn(l.document.screen,C,i.selection,l.capabilities),u=T!==i.requestId&&(o.selectionGeneration??0)>0?{operationId:o.quote?.operationId??null,generation:o.selectionGeneration??0}:void 0,b=t.view?.parameters.commerce;if(b&&typeof b=="object"&&!Array.isArray(b)&&b.intent==="subscription_change"&&!i.subscriptionChange)return Promise.reject(new m("INVALID_REQUEST","Choose the existing membership for this subscription change"));if(i.subscriptionChange&&i.nativeOffer)return Promise.reject(new m("INVALID_REQUEST","A web membership change cannot include a store offer"));if(u&&o.canReselect!==!0)return Promise.reject(new m("COMMAND_PENDING","Original purchase requires authoritative termination"));let P;try{P=se(i.requestId,{type:"paywall_quote",actionId:i.actionId,productVersionId:C,...Object.keys(c).length?{featureQuantities:c}:{},...u?{predecessor:u}:{},...i.offerId?{offerId:i.offerId}:{},...i.nativeOffer?{nativeOffer:i.nativeOffer}:{},...i.subscriptionChange?{subscriptionChange:i.subscriptionChange}:{}})}catch(le){return Promise.reject(le)}if(T===i.requestId&&J)return J;T!==i.requestId&&W++;let Z=W;T=i.requestId;let $=(async()=>{if(await te(P,Z),!o.quote)throw new m("INVALID_RESPONSE","The accepted quote is missing");return On(o.quote,{productVersionId:C,featureQuantities:c,subscriptionChange:i.subscriptionChange},"The selected purchase changed"),structuredClone(o.quote)})();return J=$,$.then(()=>{J===$&&(J=null)},le=>{J===$&&(J=null),T===i.requestId&&t.pendingCommand?.requestId!==i.requestId&&le instanceof m&&le.status!==void 0&&le.status<500&&![401,425].includes(le.status)&&(T=null)}),$},confirm:()=>we("confirm"),cancel:()=>we("cancel"),async read(){if(F(),!o.quote)throw new m("INVALID_REQUEST","A quoted purchase is required");let i=o.quote.operationId,l=W,a=t.pendingCommands?.find(P=>P.operation==="submit"&&(P.input.type==="paywall_confirm"||P.input.type==="paywall_cancel")&&P.input.operationId===i)??t.pendingCommand;a?.operation==="submit"&&(a.input.type==="paywall_confirm"||a.input.type==="paywall_cancel")&&a.input.operationId===i&&await t.settle?.(a.requestId);let C=await t.get(void 0,{receiptId:R,operationId:i});F();let c=A(C);if(c?.quote&&c.quote.operationId!==i||c?.operation&&c.operation.operationId!==i)throw new m("INVALID_RESPONSE","Purchase operation changed");let u=_(C,l,i),b=u?o.operation:c?.operation;if(!b)throw new m("INVALID_RESPONSE","The current purchase result is missing");return u&&Q.size===0&&!(t.pendingCommands?.length??(t.pendingCommand?1:0))&&(D=null),structuredClone(b)},destroy(){E=!0,S(),M.clear(),s.abort(),j.clear()}},S=t.subscribe(i=>{E||i.nodeId!==e||i.visit!==y||i.paywall?.receiptId!==R||(i.paywall.selectionGeneration??0)<(o.selectionGeneration??0)||(I(i.paywall.resolution),o={...o,resolution:i.paywall.resolution},w())});return{session:G,load:V}}function Xn(t){let v=new Set,R=new Set,e=null;async function y(d,I){let E=!1;for(;!t.stopped&&t.key===d&&t.client.pendingCommand?.requestId===I;){if(!t.client.settle)throw new m("COMMAND_PENDING","The original display acknowledgement is still pending");await t.client.settle(I),E=!0,t.client.pendingCommand?.requestId===I&&await new Promise(M=>setTimeout(M,1500))}t.stopped||t.key!==d||(E&&await t.client.get(),!(t.stopped||t.key!==d)&&v.add(d))}function N(d,I){e=I;let E=()=>{e===I&&(e=null),R.delete(d)};return I.then(E,M=>{E(),t.busy||t.fail(M)}),I}function o(d){if(t.reviewing||v.has(d)||R.has(d)||t.stopped)return;R.add(d);let I=async()=>{if(t.reviewing||t.stopped||t.key!==d||v.has(d)){R.delete(d);return}if(t.busy||t.client.pendingCommand){setTimeout(()=>{I()},250);return}let E=(async()=>{if(t.staleRead){if(await t.staleRead,t.stopped||t.key!==d)return;if(t.client.pendingCommand){setTimeout(()=>{I()},250);return}}let M=t.client.view,ne=t.expected(),w=ne.requestId;try{await t.client.submit({operation:"shown",...ne})}catch(V){if(!(V instanceof m)||V.code!=="CONFLICT"||V.status!==409||t.client.pendingCommand)throw V;await t.client.get();let s=t.client.view;if(t.stopped||t.reviewing||t.key!==d||!s||!M||s.id!==M.id||s.source.versionId!==M.source.versionId||s.nodeId!==ne.nodeId||s.visit!==ne.visit||s.revision<=ne.revision||s.stopped||!s.screen&&(!s.paywall||s.paywall.receiptId!==M.paywall?.receiptId)||!["running","waiting"].includes(s.status)||t.client.pendingCommand)throw V;let q=t.expected();w=q.requestId,await t.client.submit({operation:"shown",...q})}await y(d,w)})();N(d,E)};I()}function L(){if(e)return e;let d=t.client.pendingCommand;if(d?.operation!=="shown")return null;let I=t.key;return R.add(I),N(I,(async()=>{await t.client.retry(),await y(I,d.requestId)})())}return{report:o,settled:L,get inFlight(){return e}}}function Zn(t){let v={},R=new Map;async function e(y){let N=t.client.view,o=N?.screen,L=o?.customerData.nodes[y.nodeId];if(t.stopped||t.busy||!N||!o||!L)return;if(!["refresh","next","previous","filter","sources_next","sources_previous"].includes(y.action)){let V=t.document,s=V?En(V,y.nodeId):null,q=s?.type==="customer_data"?s.data.outputs?.[y.action]:void 0;q&&o.outputs.includes(q)?await t.perform(()=>t.client.submit({operation:"submit",...t.expected(),input:{type:"screen",output:q,answers:t.answers,selection:y.value?{[y.nodeId]:y.value}:{}}})):await t.onIntent?.(y,N);return}let I=y.action.startsWith("sources_")?L.resources.find(V=>V.key===y.value):null;if(y.action.startsWith("sources_")&&!I)throw new m("INVALID_REQUEST","Choose a current resource");let E=`${N.visit}:${y.nodeId}:${I?.key??""}`,M=R.get(E)??[null],w=v[y.nodeId]??{page:1,after:null,filter:"all",...I?{resourceKey:I.key}:{}};if(y.action==="filter"){let V=y.value;if(!V||!(L.source==="offer_history"?["all","issued","reserved","redeemed","expired","revoked"]:["all","purchase","refund","source","usage","debt","settlement"]).includes(V))throw new m("INVALID_REQUEST","Unknown data filter");w={page:1,after:null,filter:V},M.splice(0,M.length,null)}else if(y.action==="next"||y.action==="sources_next"){let V=I?.sources.at(-1),s=I?V?{kind:"ledger",cursor:{at:V.detail[0],id:V.id,type:"source"}}:null:o.dataCursors[y.nodeId];if(!s||!I&&!L.hasNext)return;M[w.page]=s,w={...w,page:w.page+1,after:s}}else if(y.action==="previous"||y.action==="sources_previous"){if(w.page<=1)return;w={...w,page:w.page-1,after:M[w.page-2]??null}}R.set(E,M),v={...v,[y.nodeId]:w},await t.perform(()=>t.client.get({nodeId:N.nodeId,visit:N.visit,revision:N.revision,components:v}))}return{get queries(){return v},intent:e,reset(){v={},R.clear()}}}function Kn(t){let{doc:v,holder:R,reviewHolder:e,mountScreenPreview:y}=t,N=!1,o,L=0,d=null,I="",E,M=new Map,ne=s=>s?`${s.id}:${s.nodeId}:${s.visit}:${s.revision}:${s.paywall?.quote?.operationId??""}`:"";async function w(s){if(t.stopped||!t.client.review||N&&s===o&&E?.active)return;let q=!N||s!==o;N||(I=ne(t.client.view),M.set(I,structuredClone(t.answers))),N=!0,o=s,R.hidden=!0,t.suspend(!0),e.hidden=!1;let T=++L;q&&(E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),E=Ze(e,t.loadingOptions,"funnel",()=>{V()}));let W=q?E:void 0;try{if(W?.start(!1,t.client.view?.locale),T!==L||t.stopped)return;let J=t.client.review(s),Q=await(W?.wait(J,Fe)??J);if(t.stopped||T!==L||!N)return;if(!Q.review)throw new m("INVALID_RESPONSE","Historical projection is missing");d?.destroy(),d=null,W||e.replaceChildren();let D=v.createElement("div"),j=W?Ke(D,e):()=>{};e.append(D);let A=Q.run.locale.startsWith("zh"),F=t.chrome;D.style.cssText=F.history;let _=v.createElement("p");_.textContent=A?"\u53EA\u8BFB\u56DE\u770B":"Read-only history",_.style.cssText=F.historyTitle,D.append(_);let pe=v.createElement("p");pe.style.cssText=F.historyNote,pe.textContent=Q.review.pages.length?A?"\u9009\u62E9\u4E00\u9875\u67E5\u770B\u5F53\u65F6\u7684\u5185\u5BB9\uFF0C\u56DE\u770B\u4E0D\u4F1A\u6539\u52A8\u4EFB\u4F55\u4FE1\u606F\u3002":"Choose a page to see it as it was. Nothing here can be changed.":A?"\u8FD8\u6CA1\u6709\u53EF\u56DE\u770B\u7684\u9875\u9762\u3002":"There are no earlier pages yet.",D.append(pe);let Re=Q.review.page?.receiptId,se=v.createElement("div");se.style.cssText=F.historyPages;for(let[G,S]of Q.review.pages.entries()){let i=v.createElement("button");i.type="button",i.textContent=A?`\u7B2C ${G+1} \u9875`:`Page ${G+1}`;let l=Re!==void 0&&S.receiptId===Re;i.style.cssText=l?F.primary:F.secondary,l&&i.setAttribute("aria-current","page"),Ue(i,()=>t.chrome.focus),i.onclick=()=>{w(S.receiptId)},se.append(i)}if(se.childElementCount&&D.append(se),Q.review.page){let G=Q.review.page,S=v.createElement("div");S.inert=!0,S.style.cssText=F.historyPage,D.append(S),d=y(S,{mode:"live",rendererUrl:t.client.webViewUrl,title:G.document.name,onAction:()=>{},onAnswers:()=>{},onCustomerDataIntent:()=>{},onRendered:()=>{T===L&&!t.stopped&&W?.present(j)},onError:l=>{if(T!==L||t.stopped)return;let a=new Error(l);W?.finish("error",a),d?.destroy(),d=null,D.remove(),t.fail(a)},onEscape:()=>{V()}});let i=d;if(i.update(G.document,Q.run.locale,{serverInput:{bindings:G.inputs,answers:G.answers,values:G.values}}),await i.ready,t.stopped||T!==L||!N)return}let te=A?{issued:"\u5DF2\u9886\u53D6",reserved:"\u5DF2\u9884\u7559",redeemed:"\u5DF2\u4F7F\u7528",expired:"\u5DF2\u8FC7\u671F",revoked:"\u5DF2\u64A4\u9500",unknown:"\u72B6\u6001\u5F85\u786E\u8BA4"}:{issued:"Issued",reserved:"Reserved",redeemed:"Used",expired:"Expired",revoked:"Revoked",unknown:"Status unconfirmed"},we=v.createElement("div");we.style.cssText=F.historyRecords;for(let G of[...Q.review.coupons.map((S,i)=>`${A?"\u4F18\u60E0\u5238":"Coupon"} ${i+1}: ${te[S.status]}`),...Q.review.purchases.map((S,i)=>`${A?"\u8D2D\u4E70":"Purchase"} ${i+1}: ${Bn(S.status,A)}`)]){let S=v.createElement("p");S.textContent=G,S.style.margin="0",we.append(S)}we.childElementCount&&D.append(we),Q.review.page||W?.present(j),t.client.view&&await t.enqueue(t.client.view)}catch(J){if(T!==L||t.stopped)return;W?.finish("error",J),d?.destroy(),d=null,e.replaceChildren(),t.fail(J)}}async function V(){if(!N||t.stopped||!t.client.review)return;let s=++L;E?.finish("dismissed");try{if(await t.client.review(),t.stopped||s!==L)return;N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1;let q=t.client.view;ne(q)!==I?(M.set(I,structuredClone(t.answers)),t.resetScreen()):(M.delete(I),t.suspend(!1)),q&&await t.enqueue(q)}catch(q){if(s!==L||t.stopped)return;d?.destroy(),d=null,e.replaceChildren(),t.fail(q)}}return{get active(){return N},get receipt(){return o},open:w,exit:V,get drafts(){return new Map([...M].map(([s,q])=>[s,structuredClone(q)]))},stop(){N=!1,L++,E?.finish("dismissed"),d?.destroy(),d=null,e.replaceChildren(),e.hidden=!0,R.hidden=!1}}}var fn=5e3;async function at(t,v,R){let e=v,y=e.prepared&&Wn(e.prepared),N=()=>{};function o(){e.prepared&&e.prepared.state!=="adopted"&&y?.release()}let L=()=>e.prepared?.state==="shown"&&!!y?.modal,d=e.client.identitySignal,I;try{I=await Promise.all([import("./screen-renderer-RDXKWHYE.js"),import("./paywall-PZ4BBEFG.js")]),e.signal?.throwIfAborted(),d?.throwIfAborted()}catch(n){throw o(),n}let[{mountScreenPreview:E},{showPaywall:M}]=I,ne=(typeof INDIANA_NATIVE_SHELL_BUILD>"u"||!INDIANA_NATIVE_SHELL_BUILD)&&e.appManifestRelease?Yn({client:e.client,appManifestRelease:e.appManifestRelease,onError:e.onError}):void 0;ne?.start();let w=t.ownerDocument,V=Mn(w),s=w.createElement("section"),q=w.createElement("div"),T=w.createElement("div"),W=w.createElement("div"),J=w.createElement("button");W.hidden=!0,J.type="button";let Q=w.createElement("p"),D=w.createElement("p"),j=w.createElement("button"),A=w.createElement("button"),F=w.createElement("button"),_=w.createElement("dialog"),pe,Re=!1;s.dataset.indianaFunnel="",s.dataset.longplayCloseOwner="sdk",s.setAttribute("aria-busy","false"),Q.setAttribute("role","status"),D.setAttribute("role","alert"),D.hidden=!0,j.type=A.type=F.type="button",T.append(j,J,Q,D,F,A),s.append(q,W,T),t.append(s);let se=Gn,te=dn(se),we="",G=(w.documentElement.lang||"").startsWith("zh"),S,i="",l;for(let n of[j,J,F,A])Ue(n,()=>te.focus);function a(){let n=G?"\u5173\u95ED":"Close";A.parentElement===_?(A.textContent="\xD7",A.setAttribute("aria-label",n),Un(A,se)):(A.textContent=n,A.removeAttribute("aria-label"),A.style.cssText=te.link+";margin-inline-start:auto")}function C(n){let r=n?.screen?.content.document.theme??se,p=JSON.stringify([r.primary,r.background,r.text,r.radius,r.font,A.parentElement===_]);if(p===we)return;we=p,se=r;let H=A.parentElement===_;te=dn(se,H),s.style.cssText=te.root+";min-width:0"+(H?";display:flex;flex-direction:column;min-height:100%":""),T.style.cssText=te.bar+(H?";margin-top:auto":""),T.hidden&&(T.style.display="none"),j.style.cssText=J.style.cssText=te.secondary,F.style.cssText=te.primary,Q.style.cssText=te.status,D.style.cssText=te.alert,a(),cn(j)}function c(){T.hidden=j.hidden&&J.hidden&&F.hidden&&D.hidden&&!Q.textContent&&(A.hidden||A.parentElement!==T),T.style.display=T.hidden?"none":"flex",S?.responsive&&l!==void 0&&S.setContentHeight(l+T.getBoundingClientRect().height)}C();let u=null,b=null,P=null,Z="",$="",le=!1,Ee="",en="",Me="",g=!1,ue=0,$e=!1,mn="",nn=null,tn=Promise.resolve(),wn=!e.client.view,z=R,Te,_e,xe="",Ge,de=!1,qe=null,ve=!1,Qe=()=>e.client.pendingCommand?.operation==="close",ce=null,Y=null,yn=Ln({document:w,run:async()=>{(!b?.observing||e.client.pendingCommand)&&await on()},delay:()=>{if(!(g||!P||!["running","waiting"].includes(P.status)&&!e.client.pendingCommand)&&!(b?.observing&&!e.client.pendingCommand))return P.pendingRequest||e.client.pendingCommand?1500:fn},hiddenDelay:()=>!g&&e.client.pendingCommand?15e3:void 0}),K=null;function rn(){return Y&&e.client.hasDurableJournal===!0&&K?.acknowledged===!0&&K.operationId===Y.operationId&&e.client.view?.id===K.runId&&e.client.view?.status==="closed"&&e.client.view.revision===K.revision+1&&!(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0))&&!e.client.pendingPurchase?Y:null}function hn(n){let r=n.run.paywall;if(K&&n.settlement?.requestId===K.requestId&&n.settlement.state==="settled"&&n.settlement.operationId===null&&n.run.id===K.runId&&n.run.status==="closed"&&!n.run.pendingRequest&&n.run.revision===K.revision+1&&n.run.nodeId===K.nodeId&&n.run.visit===K.visit&&r?.receiptId===K.receiptId&&r.selectionGeneration===K.selectionGeneration&&(r.quote?.operationId??null)===K.operationId&&(r.operation?.operationId??r.quote?.operationId??null)===K.operationId){let p=K.operationId===null&&r.selectionGeneration===0&&!r.quote&&!r.operation&&!r.purchaseRequestId,H=Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect});(p||r.canReselect===!0&&H.type==="native")&&(K.acknowledged=!0)}}let De=null,Je=new Set,ye={},Ae=!1,fe=(n,r=null)=>{g||(De=r,Ae=!1,D.textContent=Qn(n,G),D.hidden=!1,F.hidden=e.client.pendingCommand===null,c(),Pe(e.onError,n))},gn=()=>{g||(De=null,D.textContent=jn(G),D.hidden=!1,F.hidden=!0,c())};function ke(){let n=e.client.view;if(!n)throw new m("INVALID_REQUEST","No current Run is available");return{requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:n.revision}}let O=Kn({client:e.client,doc:w,holder:q,reviewHolder:W,mountScreenPreview:E,loadingOptions:e,get chrome(){return te},get stopped(){return g},get answers(){return ye},suspend(n){b?.setSuspended(n)},resetScreen(){Z="",$="",Ee=""},enqueue:he,fail:fe}),Le=Xn({client:e.client,expected:ke,fail:fe,get stopped(){return g},get reviewing(){return O.active},get key(){return Z},get busy(){return ue},get staleRead(){return nn}}),je=Zn({client:e.client,expected:ke,perform:Ne,onIntent:e.onCustomerDataIntent,get stopped(){return g},get busy(){return ue},get document(){return u?.document},get answers(){return ye}}),ze=n=>`${n.id}:${n.nodeId}:${n.visit}`,Se=n=>n&&(n.screen||n.paywall)?ze(n):"";function Ie(){let n=e.client.view;j.disabled=!O.active&&(ue>0||!!e.client.pendingCommand||!n?.canBack||n.stopped||!["running","waiting"].includes(n.status)||!Se(n)||$!==Se(n)),j.hidden=!O.active&&!n?.canBack,cn(j);let r=!!b&&!O.active;A.hidden=r&&!z?.active||Re&&!O.active,J.hidden=!e.client.review||!O.active&&!n?.canBack,r&&(Q.textContent=""),c()}async function vn(n){if(!n)return;let r=e.client.view;await n;let p=e.client.view;if(!r||!p||p.id!==r.id||p.nodeId!==r.nodeId||p.visit!==r.visit||p.stopped||!["running","waiting"].includes(p.status))throw new m("PRECONDITION_FAILED","The screen changed while its display was acknowledged")}async function Ne(n,r=!1,p){if(!((ue||ve||ce||Y)&&!r||g||O.active&&!r)){ue++,s.setAttribute("aria-busy","true"),D.hidden=!0,De=null,Ae=!1,Ie();try{if(r||await vn(Le.inFlight),g)return;let H=await n();g||await he(e.client.view??H.run)}catch(H){p?.(H)&&e.client.pendingCommand===null?gn():fe(H,e.client.pendingCommand?.requestId??null)}finally{ue=Math.max(0,ue-1),s.setAttribute("aria-busy",String(ue>0)),g||(F.hidden=e.client.pendingCommand===null,Ie())}}}function He(){yn.schedule()}async function on(){if(!(g||$e||ue)){if(O.active){await O.open(O.receipt);return}$e=!0;try{let n=e.client.pendingCommand;n&&e.client.settle&&await e.client.settle(n.requestId);let r=e.client.view,p=je.queries,H=await e.client.get(r?.screen&&Object.keys(p).length?{nodeId:r.nodeId,visit:r.visit,revision:r.revision,components:p}:void 0);Ae&&!g&&(Ae=!1,D.hidden=!0,c()),!g&&p===je.queries&&await he(e.client.view??H.run)}catch(n){fe(n),Ae=!g}finally{$e=!1}}}function Be(n,r,p){if(z?.active){let ae=z;return ae.setDismissHandler(()=>In(ae)),ae}let H=Ze(t,e,"funnel",()=>In(H),xn);return z=H,H.start(n,r,p),H}function In(n){g||de||(de=!0,n.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):ie())}function sn(){clearTimeout(Ge?.timeout),Ge=void 0}function be(){Re=!1,sn(),Te?.abort(),Te=void 0,u?.destroy(),u=null,b?.destroy(),b=null,_e?.(),_e=void 0,_.open&&_.close(),q.replaceChildren(),q.style.cssText="",l=void 0,Z="",$="",le=!1,Ee="",Me=""}function bn(){let n=w.defaultView;S?.responsive&&n&&u?.resizeViewport?.(n.innerHeight,n.innerWidth)}function an(){S?.destroy(),S=void 0,i=""}function We(n){let r=n.screen?.presentation;if(!r||r.type==="inline"){_.open&&_.close(),an(),A.parentElement!==T&&T.append(A),s.parentElement!==t&&t.append(s);for(let ae of["flex","display","flex-direction","justify-content"])q.style.removeProperty(ae);C(n),c();return}s.parentElement!==_&&(_.append(A,s),t.append(_)),q.style.flex="1 0 auto",q.style.display="flex",q.style.flexDirection="column",q.style.justifyContent="center",C(n);let p=n.screen.content.document,H=JSON.stringify([r,we]);if(H!==i){an(),i=H;let ae={sm:420,md:640,lg:900},ge="size"in r&&!r.backdrop?",0 0 0 100vmax #16142566":"";_.style.cssText=`box-sizing:border-box;padding:0;border:0;overflow:auto;background:${se.background};color:${se.text};`+(r.type==="fullscreen"?"width:100vw;height:100dvh;max-width:100vw;max-height:100dvh;margin:0;border-radius:0":`width:${ae[r.size]}px;max-width:calc(100vw - 32px);max-height:calc(100dvh - 32px);box-shadow:0 24px 80px #0003${ge};`+(r.type==="sheet"?"margin:auto auto 0;border-radius:14px 14px 0 0":"border-radius:14px")),S=Hn(_,{presentation:r,theme:p.theme,pages:p.pages},bn),S.latch()}c(),_.setAttribute("aria-label",(pe?.screen===n.screen?.content.document.name?pe?.label:void 0)??u?.document?.name??n.screen?.content.document.name??"Funnel")}async function et(n){if(g||de||ve&&(Qe()||["running","waiting"].includes(n.status))||(P=n,De&&e.client.pendingCommand?.requestId!==De&&(D.hidden=!0,De=null),G=n.locale.startsWith("zh"),J.textContent=G?"\u56DE\u770B":"History",j.textContent=O.active?G?"\u8FD4\u56DE\u5F53\u524D":"Return to current":G?"\u8FD4\u56DE":"Back",a(),F.textContent=G?"\u91CD\u8BD5":"Retry",F.hidden=e.client.pendingCommand===null,Q.textContent=n.pendingRequest?G?"\u6B63\u5728\u5904\u7406":"Processing":n.instruction?.type==="wait"?G?"\u7B49\u5F85\u4E2D":"Waiting":"",Ie(),mn!==`${n.revision}:${n.visit}:${n.status}:${n.stopped}`&&(mn=`${n.revision}:${n.visit}:${n.status}:${n.stopped}`,Pe(e.onState,structuredClone(n))),g||de))return;if((!n.pendingRequest||ve&&n.status==="closed")&&["closed","ineligible","failed"].includes(n.status)){ie();return}if(n.stopped&&L()){ie();return}if(n.stopped||e.client.configurationReady===!1){O.stop(),o(),be(),z?.finish("skipped"),s.hidden=!0,He();return}if(s.hidden=!1,O.active){He();return}let r=Se(n),p=e.client.view;if(p&&p.revision>n.revision&&Se(p)!==r)return;let H=!n.instruction&&!n.pendingRequest&&n.nodeType==="screen"&&["running","waiting"].includes(n.status);r!==Z&&(Z&&z?.finish("dismissed"),be(),Z=r,ye={...n.answers},je.reset());let ae=ze(n);if(xe===ae){s.hidden=!0;return}if(H&&!r){s.hidden=!0;let U=e.prepared?.state==="shown"?null:Be(!0,n.locale);!g&&!de&&Ge?.key!==ae&&(sn(),Ge={key:ae,timeout:setTimeout(()=>{let h=e.client.view;if(g||!U?.active&&e.prepared?.state!=="shown"||!h||ze(h)!==ae)return;xe=ae;let B=new Error("Funnel screen preparation timed out");U?.finish("error",B),o(),be(),fe(B)},Fe)}),He();return}sn();let X=U=>{let h=e.client.view;return!g&&!de&&!qe&&!U.aborted&&e.client.configurationReady!==!1&&!!h&&!h.stopped&&!["closed","ineligible","failed"].includes(h.status)&&Se(h)===r},ge=(U,h)=>{X(h)&&(xe=r,z?.finish("error",U),be(),s.hidden=!0,fe(U))};if(r||((n.instruction&&n.instruction.type!=="evaluate_segment"||!["running","waiting"].includes(n.status))&&o(),We(n),n.instruction?.type!=="event"&&n.instruction?.type!=="open_url"&&z?.finish("skipped")),n.screen){o();let U=n.screen.content;if(!u){let x=n.screen.presentation.type!=="inline",re=Be(x,n.locale);if(g||de)return;let ee=(Te=new AbortController).signal;We(n),_e=x?$n(_):Ke(s,t),u=E(q,{mode:"live",closeActions:Array.from(new Set([...e.closeActions??[],...U.document.actions.filter(f=>f.type==="event"&&f.close).map(f=>f.id)])),onAuthoredClose(f){X(ee)&&(Re=f,Ie())},rendererUrl:e.client.webViewUrl,title:U.document.name,...x?{hostPresentation:()=>S?.type??n.screen.presentation.type}:{},onResize:f=>{l=f,S?.responsive&&S.setContentHeight(f+T.getBoundingClientRect().height)},onAction(f,me={},ot={}){if(O.active||!X(ee)||$!==r)return;ye={...ye,...ot};let ln=n.screen?.inputs??[],Pn=Object.fromEntries(ln.filter(({variable:Oe})=>Object.hasOwn(ye,Oe)).map(({variable:Oe})=>[Oe,ye[Oe]]));if(zn(ln,Pn).length){gn();return}Ne(()=>e.client.submit({operation:"submit",...ke(),input:{type:"screen",output:f,answers:Pn,selection:me}}),!1,Oe=>Jn(Oe,ln))},onAnswers:f=>{O.active||!X(ee)||$!==r||(ye={...ye,...f})},onCustomerDataIntent:f=>{O.active||!X(ee)||$!==r||je.intent(f).catch(fe)},onEscape:()=>{!X(ee)||$!==r||O.active||ce||Y||Ce()},onError:f=>{let me=new Error(f);$===r?fe(me):ge(me,ee)},onRendered:f=>{if(!(!X(ee)||$===r))try{re.present(me=>{_e?.(),_e=void 0,f&&(pe={screen:U.document.name,label:f},_.setAttribute("aria-label",f)),x&&(_.showModal(),S?.responsive&&_.focus({preventScroll:!0}),!me&&e.loading!=="host"&&Vn(_,S?.type??n.screen.presentation.type,S?.responsive)),$=r,le=x,Ie()}),X(ee)&&Le.report(r)}catch(me){ge(me,ee)}}}),bn()}let h={capabilities:n.screen.capabilities,customerData:n.screen.customerData,parameters:n.parameters,serverInput:{bindings:n.screen.inputs,answers:ye,values:n.screen.values}},B=JSON.stringify([U,n.locale,h.parameters,n.screen.inputs,n.screen.values]);if(B!==Ee)u.update(U.document,n.locale,h),Ee=B,en=JSON.stringify(h.capabilities),Me=JSON.stringify(h.customerData);else{let x=JSON.stringify(h.capabilities);x!==en&&(u.updateCapabilities(h.capabilities),en=x),JSON.stringify(h.customerData)!==Me&&(u.updateCustomerData(h.customerData),Me=JSON.stringify(h.customerData))}let oe=u;if(oe)try{await(z?.wait(oe.ready)??oe.ready)}catch(x){Te&&ge(x,Te.signal)}}else if(n.paywall&&!b){let U=n.paywall.resolution,h="document"in U?U.document:null,B=y,oe=null,x=(Te=new AbortController).signal,re={loading:"host",signal:x,canInteract:()=>X(x)&&!O.active&&!ce&&!Y,beforeAction:async()=>{ue++;try{await vn(Le.settled()),D.hidden=!0,De=null,Ae=!1,c()}finally{ue=Math.max(0,ue-1)}},start:()=>pn(e.client),onObservationChange:He,onPurchase:e.onPurchase,onCheckoutUrl:e.onCheckoutUrl,resumeCheckout:e.resumeCheckout,allowNewPurchase:e.allowNewPurchase,checkoutNavigation:e.checkoutNavigation,terminateCheckout:e.terminateCheckout,confirmOnHostedCheckout:e.confirmOnHostedCheckout,resolveOfferId:e.resolveOfferId,resolveSubscriptionChange:e.resolveSubscriptionChange,claimCoupon:e.claimCoupon,onEvent:e.onEvent,onOpenUrl:f=>e.onOpenUrl?e.onOpenUrl({receiptId:n.paywall.receiptId,url:f,openIn:"same_window"}):w.defaultView?.location.assign(f),onAction:async f=>{if(O.active)return;let me=await e.client.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:n.nodeId,visit:n.visit,revision:e.client.view?.revision??n.revision,input:{type:"screen",output:f,answers:{}}});await he(e.client.view??me.run)},onError:f=>{$===r?fe(f):ge(f,x)}},ee={quoteError:f=>Pe(e.onError,f),present(f){X(x)&&(oe?.present(()=>{f(),$=r,le=!!q.querySelector("dialog[open]"),Ie()}),X(x)&&Le.report(r))},async dismiss(){if(!(g||x.aborted||O.active||ce||Y||!ve&&!X(x))){if(ve=!0,(e.resumeCheckout||e.terminateCheckout)&&rt()){P=e.client.view,ie();return}await Ce()}}};if(B){let f=await B.adopt(n,{options:re,handoff:ee,start:()=>pn(e.client)});f&&X(x)&&!g?(We(n),b=f,z?.active&&z.present(()=>{}),$=r,le=B.modal,Ie(),Le.report(r),O.active&&b.setSuspended(!0)):(f?.destroy(),o())}if(g||de)return;if(!b){if(oe=Be(!0,n.locale,h),g||de)return;We(n);let f=await M(q,re,ee).catch(me=>(ge(me,x),null));!X(x)&&!(ve&&!g&&!x.aborted)?f?.host?.destroy():f&&(b=f.host,b?.setSuspended(O.active))}}if(g||de)return;Ie();let k=n.instruction;if(k&&(k.type==="open_url"||k.type==="event")&&!Je.has(k.receiptId)){let U=w.createElement("button");U.type="button",U.style.cssText=te.primary,Ue(U,()=>te.focus),q.style.cssText=te.stage,U.textContent=k.type==="open_url"?`${G?"\u524D\u5F80":"Continue to"} ${new URL(k.url).host}`:G?"\u7EE7\u7EED":"Continue",U.onclick=()=>{let h=ke(),B=k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="new_window"?nt(k.url):null;Ne(async()=>{let oe="success";if(k.type==="open_url")if(e.onOpenUrl)try{oe=await e.onOpenUrl({receiptId:k.receiptId,url:k.url,openIn:k.openIn})===!1?"failed":"opened"}catch(re){Pe(e.onError,re),oe="failed"}else oe=k.openIn==="new_window"&&!B?"failed":"opened";if(k.type==="event"){if(!e.onEvent)throw new m("EVENT_HANDLER_REQUIRED","Provide the event handler");await e.onEvent(k.event)}if(g||e.client.view?.nodeId!==h.nodeId||e.client.view.visit!==h.visit)throw new m("PRECONDITION_FAILED","The client action visit changed");let x=await e.client.submit({operation:"submit",...h,input:{type:"client_action",receiptId:k.receiptId,outcome:oe}});return Je.add(k.receiptId),k.type==="open_url"&&!e.onOpenUrl&&k.openIn==="same_window"&&w.defaultView?.location.assign(k.url),x})},z?.active?z.present(()=>q.replaceChildren(U)):q.replaceChildren(U)}!n.pendingRequest&&n.status==="completed"&&!Je.has(`complete:${n.id}`)&&(Je.add(`complete:${n.id}`),Pe(e.onComplete,structuredClone(n))),He()}function nt(n){let r=w.defaultView?.open(n,"_blank")??null;return r&&(r.opener=null),r}function he(n){return Ie(),tn=tn.catch(()=>{}).then(async()=>{try{await et(n)}catch(r){throw z?.active&&(xe=ze(n),z.finish("error",r),be(),s.hidden=!0),r}}),tn}let tt=e.client.subscribe(n=>{if(!wn){if(n.stopped&&(le||L())&&!ve){P=n,ie();return}!ve&&(n.stopped||e.client.configurationReady===!1||Z&&$!==Z&&(Se(n)!==Z||["closed","ineligible","failed"].includes(n.status)))&&(be(),z?.finish("dismissed"),s.hidden=!0),he(n).catch(fe)}}),it=e.client.subscribeError?.(fe);function rt(){let n=e.client.view,r=n?.paywall;return!!r?.operation&&!!n&&["running","waiting"].includes(n.status)&&Tn(Ve({quote:r.quote,operation:r.operation,requestId:r.purchaseRequestId,pending:!1,destroyed:!1,canReselect:r.canReselect}))}function Ce(n){if(qe)return qe;if(g||!n&&(ce||Y))return Promise.resolve();let r=!n&&Qe();return!r&&e.client.view&&!["running","waiting"].includes(e.client.view.status)?(P=e.client.view,ie(),Promise.resolve()):(qe=Ne(async()=>{let p=r?await e.client.retry():await e.client.submit({operation:"close",...n??ke()});return n&&hn(p),p},!0).then(()=>{let p=e.client.view;p?.status==="closed"&&!Qe()&&(P=p,ie())}).finally(()=>{qe=null}),qe)}function ie(){ne?.destroy(),!g&&(g=!0,N(),o(),e.signal?.removeEventListener("abort",ie),d?.removeEventListener("abort",ie),z?.finish("dismissed"),yn.destroy(),tt(),it?.(),be(),an(),O.stop(),_.remove(),s.remove(),V(),Pe(e.onDismiss,P?structuredClone(P):null))}j.onclick=()=>{if(!j.disabled){if(O.active){O.exit();return}Ne(()=>e.client.submit({operation:"back",...ke()}))}},J.onclick=()=>{O.open()},A.onclick=()=>{z?.active?z.dismiss():ce||Ce()},F.onclick=()=>{Qe()?Ce():Ne(()=>e.client.retry())},_.addEventListener("cancel",n=>{n.preventDefault(),z?.active?z.dismiss():ce||Ce()}),e.signal?.addEventListener("abort",ie,{once:!0}),d?.addEventListener("abort",ie,{once:!0});let Ye=!1;y&&(N=y.onClose(()=>{g||de||(de=!0,z?.finish("dismissed"),be(),s.hidden=!0,e.client.view?Ce().finally(ie):Ye=!0)}));let Cn={destroy:ie,refresh:on,get recovery(){let n=rn();if(n)return n;if(!g&&!ue&&!ve&&!ce&&b){let r=b.recovery;if(r.type!=="native")return r}return{type:"recover",operationId:e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,requestId:e.client.pendingCommand?.requestId??null}},prepareFallback(){if(ce)return ce;let n=rn();if(n)return Promise.resolve(n);let r=e.client.pendingPurchase?.operationId??e.client.view?.paywall?.quote?.operationId??Y?.operationId??null,p=()=>({type:"recover",operationId:r,requestId:e.client.pendingCommand?.requestId??null});if(e.client.hasDurableJournal!==!0){let k=b?.recovery;return Promise.resolve(k&&k.type!=="native"&&k.type!=="cancel"?k:p())}let H=(e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[])).some(k=>k.operation==="close");if(g&&!(H||Y&&e.client.view?.status==="closed")||ue||$e||qe||O.active||!b&&!Y&&!H)return Promise.resolve(p());let ae=b,X=(async()=>{try{if(!Y&&H){let h=await e.client.retry();return await he(e.client.view??h.run),p()}if(!Y){let h=await ae.prepareFallback();if(h.type!=="native")return h;if(e.client.hasDurableJournal!==!0)return p();Y=h}let k=e.client.pendingCommands??(e.client.pendingCommand?[e.client.pendingCommand]:[]);if(k.length){let h=k.find(oe=>oe.operation==="close");if(!h||!K||h.requestId!==K.requestId)return p();let B=await e.client.retry();hn(B),await he(e.client.view??B.run)}else{let h=e.client.view,B=h?.paywall;if(!h||!B||B.selectionGeneration===void 0||(B.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&B.canReselect!==!0)return p();let oe=B.selectionGeneration,x=await e.client.get();await he(e.client.view??x.run);let re=e.client.view,ee=re?.paywall;if(!re||!ee||!["running","waiting"].includes(re.status)||re.stopped||re.id!==h.id||re.nodeId!==h.nodeId||re.visit!==h.visit||ee.receiptId!==B.receiptId||ee.selectionGeneration!==oe||(ee.quote?.operationId??null)!==Y.operationId||Y.operationId!==null&&ee.canReselect!==!0||e.client.pendingPurchase||(e.client.pendingCommands?.length??(e.client.pendingCommand?1:0)))return p();let f=ke();K={runId:re.id,operationId:Y.operationId,revision:f.revision,requestId:f.requestId,nodeId:re.nodeId,visit:re.visit,receiptId:ee.receiptId,selectionGeneration:oe,acknowledged:!1},await Ce(f)}let U=rn();return U?(ie(),U):p()}catch(k){return fe(k),p()}})();ce=X;let ge=()=>{ce===X&&(ce=null)};return X.then(ge,ge),X},review:O.open,exitReview:O.exit,get unappliedDrafts(){return O.drafts}};try{let n=e.client.view;if(n)((e.client.viewAgeMs??fn)>=fn||n.instruction?.type==="evaluate_segment")&&(nn=on().finally(()=>{nn=null})),await he(n);else{if(s.hidden=!0,g)throw new DOMException("Presentation cancelled","AbortError");let r=Ye||e.prepared?.state==="shown"?null:Be(e.client.view?.screen?.presentation.type!=="inline",e.client.view?.locale);if(g||de&&!Ye)throw new DOMException("Presentation cancelled","AbortError");let p=e.client.get(),H=await(r?r.wait(p,Fe):lt(p,Fe));if(wn=!1,Ye)return g||await Ce().finally(ie),Cn;await he(e.client.view??H.run)}}catch(n){throw z?.finish("error",n),ie(),n}return Cn}function lt(t,v){let R;return Promise.race([t,new Promise((e,y)=>{R=setTimeout(()=>y(new Error("Presentation data timed out")),v)})]).finally(()=>clearTimeout(R))}function Bt(t,v,R){return at(t,v,R)}export{at as a,Bt as b};
@@ -1 +1 @@
1
- import{a as p}from"./chunk-OOD2VDDP.js";import{b as r}from"./chunk-RGEBK6UF.js";import{a as i,b as s}from"./chunk-CILM5XMH.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
1
+ import{g as p}from"./chunk-6XRXHFM6.js";import{b as r}from"./chunk-GPJF3T43.js";import{a as i,b as s}from"./chunk-WPFTSHP2.js";var b=r.string().regex(/^[a-f0-9]{64}$/),j=r.strictObject({scope:r.strictObject({projectId:r.uuid(),environmentId:r.uuid(),environment:p}),customerId:r.uuid()});function l(u){let n=e=>{if(Array.isArray(e))return`[${e.map(n).join(",")}]`;if(e!==null&&typeof e=="object"){let c=Object.getPrototypeOf(e);if(c!==Object.prototype&&c!==null)throw new TypeError("Commerce protocol digests require JSON objects");return`{${Object.entries(e).filter(([,o])=>o!==void 0).sort(([o],[t])=>o<t?-1:o>t?1:0).map(([o,t])=>`${JSON.stringify(o)}:${n(t)}`).join(",")}}`}if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return JSON.stringify(e);throw new TypeError("Commerce protocol digests require JSON values")};return i(s(new TextEncoder().encode(n(u))))}export{b as a,j as b,l as c};
@@ -0,0 +1 @@
1
+ import{b as Q}from"./chunk-LSVTH3TS.js";import{a as j,b as Z,c as x}from"./chunk-5JRBCW6V.js";import{a as L,b as F,c as H,j as l}from"./chunk-6XRXHFM6.js";import{b as e}from"./chunk-GPJF3T43.js";var fe=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],G=e.enum(fe),K=e.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","subscription.change.closed","invoice.paid","refund.updated"]);var W=e.enum(["replace","stack_native"]);var o=e.string().min(1).max(200),c=e.iso.datetime({offset:!0}),i=e.number().int().nonnegative().max(1e8),y=e.string().regex(/^[A-Z]{3}$/),m=e.strictObject({priceId:e.uuid(),productVersionId:e.uuid(),productId:o,quantity:e.number().int().min(1).max(1e6),unitAmountMinor:i,totalMinor:i,interval:e.enum(["week","month","year","one_off"]),intervalCount:e.number().int().min(1).max(52),kind:e.enum(["fixed","prepaid","seat"]),tiers:e.strictObject({mode:e.enum(["graduated","volume"]),tiers:e.array(e.strictObject({upTo:e.number().int().positive().nullable(),unitAmountMinor:i,flatAmountMinor:i.optional()})).min(2).max(12)}).nullable()}),I=e.strictObject({grantId:e.uuid(),couponId:e.uuid(),amountMinor:i,applicationPolicy:W.optional(),applicableProductIds:e.array(o).min(1).max(100).optional(),terms:e.discriminatedUnion("type",[e.strictObject({type:e.literal("percent"),percentOff:e.number().gt(0).max(100)}),e.strictObject({type:e.literal("amount"),amountOffMinor:i,currency:y})]),duration:e.discriminatedUnion("type",[e.strictObject({type:e.literal("once")}),e.strictObject({type:e.literal("forever")}),e.strictObject({type:e.literal("repeating"),months:e.number().int().min(1).max(36)})])}),E={provider:e.literal("merchant"),executor:e.literal("merchant"),operationId:e.uuid(),customerId:e.uuid(),configurationRevision:e.number().int().nonnegative(),connectionRevision:e.number().int().nonnegative(),currency:y,expiresAt:c},ge=e.strictObject({...E,type:e.literal("purchase"),mode:e.enum(["payment","subscription"]),lineItems:e.array(m).min(1).max(100),catalogAmountMinor:i,nativeDiscountMinor:i.optional(),discount:I.nullable(),trialPeriodDays:e.number().int().min(1).max(730).nullable(),automaticTax:e.boolean()}).refine(t=>t.lineItems.reduce((n,r)=>n+r.totalMinor,0)===t.catalogAmountMinor&&(t.discount?.amountMinor??0)+(t.nativeDiscountMinor??0)<=t.catalogAmountMinor&&new Set(t.lineItems.map(n=>n.priceId)).size===t.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),S=e.strictObject({...E,type:e.literal("subscription_change"),subscriptionId:e.uuid(),merchantSubscriptionId:o,membershipId:e.uuid(),subscriptionAction:e.enum(["update","cancel","schedule","release"]),supersedesOperationId:e.uuid().nullable(),change:e.discriminatedUnion("type",[e.strictObject({type:e.literal("cancel")}),e.strictObject({type:e.literal("uncancel")}),e.strictObject({type:e.literal("plan"),productVersionId:e.uuid(),featureQuantities:e.record(e.uuid(),e.number().int().min(0).max(1e4)).refine(t=>Object.keys(t).length<=100).optional()}),e.strictObject({type:e.literal("seats"),licenseKey:o,quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("quantity"),internal_feature_id:e.uuid(),quantity:e.number().int().nonnegative().max(1e6)}),e.strictObject({type:e.literal("billing_cycle"),billingCycleAnchor:e.union([e.literal("now"),e.number().int().positive()])})]),timing:e.enum(["immediate","renewal"]),effectiveAt:c,creditMinor:i,debitMinor:i,totalMinor:i,discountMinor:i,discount:I.nullable().optional(),taxMinor:i,proration:e.enum(["none","create_prorations","always_invoice"]),lineItems:e.array(m.extend({quantity:e.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:e.array(e.uuid()).max(100),sourceLineItems:e.array(m).min(1).max(100).optional()}),xe=e.strictObject({...E,type:e.literal("refund"),invoiceId:e.uuid(),merchantInvoiceId:o,amountMinor:i.refine(t=>t>0),mode:e.enum(["full","partial"]),entitlementAction:e.enum(["retain","revoke"]),cancelSubscriptions:e.array(o).max(100)}),Y=e.discriminatedUnion("type",[ge,S,xe]);function Je(t){let n=new Set;if(t.type==="purchase")n.add(t.mode==="subscription"?"purchase.subscription":"purchase.one_time"),t.lineItems.some(r=>r.kind==="prepaid")&&n.add("purchase.prepaid"),t.lineItems.some(r=>r.kind==="seat")&&n.add("purchase.seats"),t.lineItems.some(r=>r.tiers!==null)&&n.add("purchase.tiered"),t.trialPeriodDays!==null&&n.add("purchase.trial"),t.automaticTax&&n.add("tax.automatic"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`);else if(t.type==="refund")n.add(`refund.${t.mode}`),t.entitlementAction==="revoke"&&n.add("refund.revoke");else{let r=t.change.type;r==="cancel"?n.add(`subscription.cancel.${t.timing}`):r==="uncancel"?n.add("subscription.resume"):r==="plan"?n.add(`subscription.plan.${t.timing}`):n.add(`subscription.${r}`),t.proration!=="none"&&n.add("subscription.proration"),t.discount&&n.add(`discount.${t.discount.terms.type}.${t.discount.duration.type}`)}return[...n].sort()}function Ye(t){return t.type==="purchase"?t.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:t.type==="subscription_change"?["subscription.change.completed","subscription.change.closed","subscription.observed",...t.change.type==="cancel"||t.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...t.entitlementAction==="revoke"&&t.cancelSubscriptions.length?["subscription.observed"]:[]]}var ye=e.strictObject({phase:e.enum(["execution","payment","fulfillment","recording"]),code:L,reason:H.optional(),recovery:F,retryable:e.boolean()}).refine(t=>t.reason!=="RESULT_UNKNOWN"||!t.retryable&&t.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ie=e.strictObject({type:e.literal("redirect"),url:e.url().startsWith("https://"),expiresAt:c}),B={operationId:e.uuid(),customerId:e.uuid(),merchantExecutionId:o,fulfillmentStatus:e.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:e.enum(["not_ready","pending","accepted","failed"]),updatedAt:c,problem:ye.nullable(),pollAfterMs:e.number().int().min(1e3).max(6e4).nullable()},k=e.discriminatedUnion("type",[e.strictObject({...B,type:e.literal("purchase"),merchantOrderId:o.nullable(),paymentStatus:e.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:e.url().refine(t=>new URL(t).protocol==="https:").nullable(),checkoutExpiresAt:c.nullable()}).refine(t=>!t.checkoutUrl||["not_started","pending"].includes(t.paymentStatus)&&t.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),e.strictObject({...B,type:e.literal("subscription_change"),status:e.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:o,scheduledFor:c.nullable(),nextAction:Ie.optional()}).refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"A scheduled change retains its future effective time"),e.strictObject({...B,type:e.literal("refund"),status:e.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:o.nullable()}).refine(t=>t.status!=="succeeded"||t.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ee=e.discriminatedUnion("lookup",[e.strictObject({lookup:e.literal("found"),operationId:e.uuid(),customerId:e.uuid(),execution:k,readAt:c}),e.strictObject({lookup:e.literal("not_received"),operationId:e.uuid(),customerId:e.uuid(),execution:e.null(),readAt:c})]).refine(t=>!t.execution||t.execution.operationId===t.operationId&&t.execution.customerId===t.customerId,"Lookup must retain the original Customer and operation"),te=e.strictObject({merchantPriceId:o,productId:o,kind:e.enum(["fixed","prepaid"]),currency:y,unitAmountMinor:i,interval:e.enum(["one_off","day","week","month","year"]),intervalCount:e.number().int().min(1).max(100)}),X={merchantItemId:o,quantity:e.number().int().positive().max(1e6)},Se=t=>t.priceId??JSON.stringify(t.nativePrice),T=e.strictObject({merchantSubscriptionId:o,revision:e.number().int().positive(),status:e.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:c,periodEndsAt:c,cancelAtPeriodEnd:e.boolean(),hasDiscounts:e.boolean(),items:e.array(e.union([e.strictObject({...X,priceId:e.uuid()}),e.strictObject({...X,nativePrice:te})])).min(1).max(100)}).refine(t=>Date.parse(t.periodEndsAt)>Date.parse(t.periodStartsAt)&&new Set(t.items.map(Se)).size===t.items.length&&new Set(t.items.map(n=>n.merchantItemId)).size===t.items.length,"Subscription periods and Price identities must be unambiguous"),J={merchantLineId:o,quantity:e.number().int().nonnegative().max(1e6),subtotalMinor:e.number().int().min(-1e8).max(1e8),discountMinor:i,taxMinor:i,totalMinor:e.number().int().min(-1e8).max(2e8),periodStartsAt:c.nullable(),periodEndsAt:c.nullable()},R=e.strictObject({merchantInvoiceId:o,reason:e.enum(["renewal","adjustment"]).optional(),currency:y,subtotalMinor:i,discountMinor:i,taxMinor:i,totalMinor:i,paidMinor:i,periodStartsAt:c.nullable(),periodEndsAt:c.nullable(),lines:e.array(e.union([e.strictObject({...J,priceId:e.uuid()}),e.strictObject({...J,nativePrice:te})]).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&(t.subtotalMinor<0?t.discountMinor===0&&t.taxMinor===0:t.discountMinor<=t.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(t=>t.subtotalMinor-t.discountMinor+t.taxMinor===t.totalMinor&&t.discountMinor<=t.subtotalMinor&&t.paidMinor===t.totalMinor&&new Set(t.lines.map(n=>n.merchantLineId)).size===t.lines.length&&t.lines.reduce((n,r)=>n+r.subtotalMinor,0)===t.subtotalMinor&&t.lines.reduce((n,r)=>n+r.discountMinor,0)===t.discountMinor&&t.lines.reduce((n,r)=>n+r.taxMinor,0)===t.taxMinor&&t.lines.reduce((n,r)=>n+r.totalMinor,0)===t.totalMinor,"A paid Invoice retains the complete financial amounts"),p={eventId:e.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:e.uuid(),occurredAt:c},Me=e.strictObject({...p,type:e.literal("purchase.completed"),operationId:e.uuid(),merchantOrderId:o,paymentStatus:e.enum(["paid","trialing","no_payment_required"]),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable(),subscription:T.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),_e=e.strictObject({...p,type:e.literal("purchase.closed"),operationId:e.uuid(),status:e.enum(["failed","expired","canceled"])}),Oe=e.strictObject({...p,type:e.literal("subscription.observed"),operationId:e.uuid().nullable(),subscription:T}),ve=e.strictObject({...p,type:e.literal("subscription.change.completed"),operationId:e.uuid(),status:e.enum(["scheduled","applied"]),scheduledFor:c.nullable(),subscription:T.refine(t=>t.items.every(n=>"priceId"in n),"An operation result retains its quoted Price identities"),invoice:R.refine(t=>t.lines.every(n=>"priceId"in n),"An operation result retains its quoted Price identities").nullable()}),Ae=e.strictObject({...p,type:e.literal("subscription.change.closed"),operationId:e.uuid(),merchantSubscriptionId:o,merchantInvoiceId:o.nullable(),status:e.enum(["failed","expired","canceled"])}),je=e.strictObject({...p,type:e.literal("invoice.paid"),merchantSubscriptionId:o.nullable(),invoice:R}),Pe=e.strictObject({...p,type:e.literal("refund.updated"),operationId:e.uuid().nullable(),merchantInvoiceId:o.optional(),merchantRefundId:o,status:e.enum(["pending","succeeded","failed"]),amountMinor:i.refine(t=>t>0),currency:y}),et=[Me.refine(t=>t.paymentStatus!=="paid"||t.invoice!==null,"A paid purchase includes its Invoice"),_e,Oe.refine(t=>t.operationId===null||t.subscription.items.every(n=>"priceId"in n),"Native Price references cannot replace an operation's quoted Prices"),ve.refine(t=>t.status==="scheduled"==(t.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),Ae,je,Pe.refine(t=>t.operationId!==null||t.merchantInvoiceId!==void 0,"A native refund names its Invoice")];var z=e.strictObject({days:e.number().int().min(1).max(730),cardRequired:e.boolean()}),ot=e.object({...z.shape,featureAllowances:e.record(e.uuid(),e.number().int().min(0).max(1e9)),creditAmounts:e.record(e.uuid(),l)}).strict(),at=e.object({id:e.uuid(),planVersionId:e.uuid(),slot:e.string(),cardRequired:e.boolean(),status:e.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:e.iso.datetime().nullable(),endsAt:e.iso.datetime().nullable(),createdAt:e.iso.datetime()}).strict();var qe=e.number().int().positive().max(2e8),ne=e.number().int().min(0).max(2e8),re=t=>t.mode==="partial"==(t.amountMinor!==void 0),P=e.strictObject({mode:e.enum(["full","partial"]),amountMinor:qe.optional(),entitlementAction:e.enum(["retain","revoke"])});var a=e.string().min(1).max(200),b=e.iso.datetime({offset:!0}),f=ne,ie=f.maxValue,C=e.number().int().min(-ie).max(ie),q=e.string().regex(/^[A-Z]{3}$/),oe=e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),ae=e.array(a).max(100).refine(t=>new Set(t).size===t.length),Ce=e.strictObject({merchantProductId:a,merchantPriceId:a,productVersionId:e.uuid().optional(),quantity:l.refine(t=>/[1-9]/.test(t))}),D={subject:Z,operationId:e.uuid(),configurationRevision:oe,connectionRevision:oe,expiresAt:b},w=e.discriminatedUnion("action",[e.strictObject({...D,action:e.literal("purchase"),mode:e.enum(["payment","subscription"]),currency:q,items:e.array(Ce).min(1).max(100),offerRefs:ae}),e.strictObject({...D,action:e.literal("subscription_change"),currency:q,merchantSubscriptionId:a,change:S.shape.change,timing:S.shape.timing,proration:S.shape.proration,offerRefs:ae}),e.strictObject({...D,action:e.literal("refund"),currency:q,merchantInvoiceId:a,mode:P.shape.mode,amountMinor:P.shape.amountMinor,entitlementAction:P.shape.entitlementAction}).refine(re,"Only a partial refund chooses amountMinor")]),ft=e.strictObject({request:w,requestedAt:b,preparationAllowed:e.boolean()}).refine(t=>!t.preparationAllowed||Date.parse(t.requestedAt)<Date.parse(t.request.expiresAt),"Preparation authority must be within its original validity"),Be=e.strictObject({merchantLineId:a,merchantPriceId:a.nullable(),quantity:l.refine(t=>/[1-9]/.test(t)),subtotalMinor:C,discountMinor:f,taxMinor:f.nullable(),totalMinor:C.nullable()}).refine(t=>t.taxMinor===null==(t.totalMinor===null)&&(t.totalMinor===null||t.totalMinor===t.subtotalMinor-t.discountMinor+t.taxMinor),"A quote line retains exact known totals; unknown tax is not zero"),Ee=e.strictObject({items:e.array(e.strictObject({merchantPriceId:a,quantity:l.refine(t=>/[1-9]/.test(t)),interval:m.shape.interval.exclude(["one_off"]),intervalCount:m.shape.intervalCount,amountMinor:m.shape.totalMinor,amountAfterOfferMinor:m.shape.totalMinor.optional()})).min(1).max(100),trial:z.nullable(),discount:I.nullable().optional(),discountExpiresAt:b.nullable().optional(),initialAmountMinor:m.shape.totalMinor.optional()}),ce=e.strictObject({request:w,requestDigest:j,merchantQuoteId:a,quoteTermsDigest:j,termsVersion:a,sourceRevisions:e.array(e.strictObject({reference:a,revision:a})).max(100),observedAt:b,expiresAt:b,currency:q,automaticTax:e.boolean(),lines:e.array(Be).max(100),subscriptionTerms:Ee.nullable(),subtotalMinor:C,discountMinor:f,nativeDiscountMinor:f.optional(),discount:I.nullable().optional(),taxMinor:f.nullable(),totalMinor:C.nullable(),effectiveAt:b.nullable(),expectedEffects:e.array(e.strictObject({reference:a,kind:e.enum(["grant","revoke","change"]),description:e.string().min(1).max(1e3),quantity:l.nullable(),unit:a.nullable()}).refine(t=>t.quantity===null==(t.unit===null),"Quantified effects name their native unit")).max(100),requiredConsents:e.array(e.strictObject({reference:a,version:a,summary:e.string().min(1).max(1e3)})).max(20)}),U=ce.superRefine((t,n)=>{let{quoteTermsDigest:r,...u}=t,h=t.lines.every(s=>s.taxMinor!==null),A=t.request.action==="purchase"&&t.request.mode==="subscription"!=(t.subscriptionTerms!==null),be=t.subscriptionTerms!==null&&(t.request.action==="refund"||t.request.action==="subscription_change"&&t.request.change.type==="cancel");(t.requestDigest!==x(t.request)||t.quoteTermsDigest!==x(u)||t.currency!==t.request.currency||A||be||t.lines.length===0&&(t.request.action!=="subscription_change"||t.subtotalMinor!==0||t.discountMinor!==0||t.taxMinor!==0||t.totalMinor!==0)||Date.parse(t.observedAt)>=Date.parse(t.expiresAt)||Date.parse(t.expiresAt)>Date.parse(t.request.expiresAt)||new Set(t.lines.map(s=>s.merchantLineId)).size!==t.lines.length||new Set(t.sourceRevisions.map(s=>s.reference)).size!==t.sourceRevisions.length||new Set(t.requiredConsents.map(s=>s.reference)).size!==t.requiredConsents.length||t.subtotalMinor!==t.lines.reduce((s,g)=>s+g.subtotalMinor,0)||t.discountMinor!==t.lines.reduce((s,g)=>s+g.discountMinor,0)||t.taxMinor!==null!==h||!h&&!t.automaticTax||t.taxMinor===null!=(t.totalMinor===null)||h&&(t.taxMinor!==t.lines.reduce((s,g)=>s+g.taxMinor,0)||t.totalMinor!==t.subtotalMinor-t.discountMinor+t.taxMinor)||t.request.action!=="subscription_change"&&(t.subtotalMinor<0||t.totalMinor!==null&&t.totalMinor<0)||t.request.action==="refund"&&(t.taxMinor===null||t.totalMinor===null||t.totalMinor<=0||t.request.mode==="partial"&&t.totalMinor!==t.request.amountMinor))&&n.addIssue({code:"custom",message:"Merchant terms must retain the original selection, scope, validity, digest and totals"})});function gt(t,n,r,u){return t.request.operationId===n&&t.request.action===r&&t.currency===u}function xt(t){return x(w.parse(t))}function yt(t){return x(ce.omit({quoteTermsDigest:!0}).parse(t))}var ke=e.strictObject({quoteTermsDigest:j,consents:e.array(e.strictObject({reference:a,version:a})).max(20)});function It(t){return{quoteTermsDigest:t.quoteTermsDigest,consents:t.requiredConsents.map(({reference:n,version:r})=>({reference:n,version:r}))}}var Te=ke.extend({operationId:e.uuid()}).refine(t=>new Set(t.consents.map(n=>n.reference)).size===t.consents.length);function St(t,n){let r=U.parse(t),u=Te.parse(n);return u.operationId===r.request.operationId&&u.quoteTermsDigest===r.quoteTermsDigest&&u.consents.length===r.requiredConsents.length&&r.requiredConsents.every(h=>u.consents.some(A=>A.reference===h.reference&&A.version===h.version))}var M=3,At="/integrations/indiana",jt="X-Indiana-Merchant-Bridge-Version",Re=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],ze=e.enum(Re),Pt={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},$=e.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ue=e.string().regex(/^[A-Za-z0-9_-]{1,64}$/),De=e.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(t=>"AEIMQUYcgkosw048".includes(t.at(-1)),"Use canonical base64url for a 32-byte key"),we=e.strictObject({keyId:ue,signingSecret:De}),Ue=e.string().max(300).superRefine((t,n)=>{try{let r=new URL(t);if(r.protocol!=="https:"||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.port&&r.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(r.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(r.hostname))throw new Error("invalid origin")}catch{n.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(t=>new URL(t).origin),me=e.array(ze).max(10).refine(t=>new Set(t).size===t.length,"Capabilities must be unique"),V=e.strictObject({bridgeVersion:e.literal(M),projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),capabilities:me,catalog:e.enum(["endpoint","static","none"]),billingEvents:e.array(K).max(7),profiles:e.array(G).max(32).refine(t=>new Set(t).size===t.length,"Profiles must be unique")}).superRefine((t,n)=>{let r=u=>t.capabilities.includes(u);r("catalog")!==(t.catalog!=="none")&&n.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(r("billing_records")!==t.billingEvents.length>0||new Set(t.billingEvents).size!==t.billingEvents.length)&&n.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),de=e.strictObject({origin:Ue,requiredCapabilities:me}),$e=e.strictObject({revision:e.number().int().nonnegative(),checkedAt:e.iso.datetime(),outcome:e.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:e.strictObject({ping:e.enum(["passed","failed","not_checked"]),authentication:e.enum(["passed","failed","not_checked"]),catalog:e.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:V.nullable()}).superRefine((t,n)=>{t.outcome==="valid"!=(t.manifest!==null)&&n.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),qt=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"]),execution:e.enum(["indiana","record_only"]),accountId:e.string().nullable(),revision:e.number().int().nonnegative(),authentication:e.strictObject({keyId:ue}).nullable(),secretStoreConfigured:e.boolean().optional(),connection:de.nullable(),check:$e.nullable()});var se=e.strictObject({projectId:e.uuid(),environmentId:e.uuid()}),Ct=e.discriminatedUnion("action",[se.extend({action:e.literal("save"),revision:e.number().int().nonnegative(),connection:de,authentication:we.optional()}),se.extend({action:e.literal("check"),revision:e.number().int().nonnegative()})]),_=e.strictObject({projectId:e.uuid(),environmentId:e.uuid(),environment:e.enum(["sandbox","live"])});function Bt(t){return e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:$,scope:_,data:t})}var le=e.strictObject({nativeUserId:e.string().min(1).max(128),session:Q.strict()}),pe=e.strictObject({nativeUserId:e.string().min(1).max(128),presentation:e.strictObject({customerId:e.uuid(),decisionId:e.uuid(),offeringVersionId:e.uuid(),paywallVersionId:e.uuid(),variant:e.string().min(1).max(128)}).nullable()}),he=e.strictObject({decisionId:e.uuid(),eventId:e.uuid()}),O=e.strictObject({operationId:e.uuid(),customerId:e.uuid()}),Et=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),command:e.string().min(1).max(64),scope:_,error:e.strictObject({code:e.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:e.string().min(1).max(500),retryable:e.boolean(),recovery:e.string().min(1).max(80)})});var wt=e.strictObject({scope:_,operationId:e.uuid(),customerId:e.uuid(),confirmedAt:e.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:e.boolean(),instruction:Y,merchantTerms:U.optional()}).refine(t=>t.operationId===t.instruction.operationId&&t.customerId===t.instruction.customerId&&(!t.merchantTerms||t.merchantTerms.request.operationId===t.operationId&&t.merchantTerms.request.subject.customerId===t.customerId&&t.merchantTerms.request.action===t.instruction.type&&t.merchantTerms.currency===t.instruction.currency&&Object.entries(t.scope).every(([n,r])=>t.merchantTerms.request.subject.scope[n]===r)),"Authority must refer to the original Customer and operation"),N=k,d=e.string().min(1).max(120),Ve=e.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),Ne=e.strictObject({revision:d,updatedAt:e.iso.datetime(),provider:e.literal("merchant"),items:e.array(e.strictObject({merchantProductId:d,productVersionId:e.uuid(),name:e.string().min(1).max(255),kind:e.enum(["subscription","credit_pack"]),merchantPriceId:d,currency:e.string().regex(/^[a-z]{3}$/),amountMinor:e.number().int().nonnegative().max(1e8),interval:e.enum(["one_time","month","year"]),intervalCount:e.literal(1),includedCredits:e.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:e.enum(["none","month"]),creditPolicyId:d,available:e.boolean()}).superRefine((t,n)=>{(t.kind==="credit_pack"&&(t.interval!=="one_time"||t.creditReset!=="none")||t.kind==="subscription"&&t.interval==="one_time"||t.available&&t.amountMinor===0)&&n.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Le=e.strictObject({customerId:e.uuid(),revision:e.string().min(1).max(128),observedAt:e.iso.datetime(),subscriptions:e.array(e.strictObject({merchantSubscriptionId:d,merchantProductId:d,productVersionId:e.uuid().nullable(),status:e.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:e.iso.datetime().nullable(),currentPeriodEndsAt:e.iso.datetime().nullable(),cancelAtPeriodEnd:e.boolean(),scheduledChange:e.strictObject({effectiveAt:e.iso.datetime(),merchantProductId:d}).nullable()})).max(100),purchaseHistory:e.strictObject({complete:e.boolean(),hasPaidPurchase:e.boolean(),lastPaidAt:e.iso.datetime().nullable()}),balances:e.array(e.strictObject({bucketId:d,key:d,available:Ve,expiresAt:e.iso.datetime().nullable(),nextResetAt:e.iso.datetime().nullable()})).max(100)}),v=e.strictObject({}),Fe={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":v,"session.create":v,"catalog.read":v,"customer.commerce.read":v,"presentation.resolve":v,"presentation.report":he,"purchase.execute":O,"operation.read":O,"subscription.change":O,"refund.execute":O},Ut={"bridge.ping":e.strictObject({challenge:e.uuid()}),"bridge.describe":V,"session.create":le,"catalog.read":Ne,"customer.commerce.read":Le,"presentation.resolve":pe,"presentation.report":e.strictObject({queued:e.literal(!0)}),"purchase.execute":N,"operation.read":ee,"subscription.change":N,"refund.execute":N},$t=e.strictObject({bridgeVersion:e.literal(M),requestId:e.uuid(),scope:_,command:$,data:e.unknown()}).superRefine((t,n)=>{Fe[t.command].safeParse(t.data).success||n.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});export{W as a,ge as b,S as c,xe as d,Je as e,Ye as f,ye as g,k as h,ee as i,p as j,et as k,z as l,qe as m,ne as n,re as o,P as p,ft as q,U as r,gt as s,xt as t,yt as u,ke as v,It as w,St as x,M as y,At as z,jt as A,Re as B,Pt as C,we as D,Ue as E,V as F,_ as G,Bt as H,le as I,pe as J,he as K,O as L,Et as M,wt as N,N as O,Le as P,Fe as Q,Ut as R,$t as S};
@@ -1 +1 @@
1
- import{e as w,f as b}from"./chunk-EREQZWGI.js";import{n as h,s as u}from"./chunk-P23JOPR5.js";import{a as y}from"./chunk-PZOQV6MU.js";import{a as n}from"./chunk-WLGLQJ6M.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-RV6UAUK2.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
1
+ import{e as w,f as b}from"./chunk-PBZSOTKZ.js";import{n as h,s as u}from"./chunk-HLCDAU5A.js";import{a as y}from"./chunk-LUGZNBIW.js";import{a as n}from"./chunk-TL67SYPH.js";import{a as g}from"./chunk-3VUPVXAV.js";import{b as f}from"./chunk-ZICZN6WO.js";function p(r,s){let a=typeof r=="string"?new TextEncoder().encode(r):r;return a.byteLength===s.byteLength&&u(a)===s.sha256}async function _(r,s){let a=w.parse(s),{artifact:i,environmentId:P}=a.content,m=new y(r.baseUrl??f).origin,e=new y(i.url,m);if(e.origin!==m||e.username||e.password||e.search||e.hash||e.pathname!==`/api/v1/configuration/${P}/artifacts/${i.sha256}`)throw new n("INVALID_RESPONSE","Public Paywall locator is not trusted");let o=new AbortController,d,I=new Promise((t,l)=>{d=setTimeout(()=>{let c=new n("TIMEOUT","Public Paywall read timed out");o.abort(c),l(c)},h.initializationMs)}),E=(async()=>{let t=await(r.fetch??globalThis.fetch)(e,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:o.signal});if(o.signal.aborted&&(t.body?.cancel().catch(()=>{}),o.signal.throwIfAborted()),!t.ok||!t.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(t.headers.get("content-length"))>i.byteLength)throw t.body?.cancel().catch(()=>{}),new n("INVALID_RESPONSE","Public Paywall is unavailable");let l=await g(t,i.byteLength,{signal:o.signal,error:c=>new n("INVALID_RESPONSE",c==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!p(l,i))throw new n("INVALID_RESPONSE","Public Paywall digest or size changed");return b(a,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))})();try{return await Promise.race([E,I])}finally{clearTimeout(d)}}export{p as a,_ as b};
@@ -0,0 +1 @@
1
+ import{b as r}from"./chunk-GPJF3T43.js";var R=r.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"]),H=r.enum([...R.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED","SENSITIVE_OUTPUT_REQUIRED"]),j=r.enum([...R.options,"stale_revision"]),v=r.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"]),x=r.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","FUNNEL_PAUSED"]),L={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 S={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",CUSTOMER_SESSION_REQUIRED:"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",PURCHASE_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",PURCHASE_STORAGE_CONFLICT:"resolve_conflict",PURCHASE_STORAGE_INVALID:"recover_operation",EXECUTION_POLICY_REFUSED:"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",ROUTE_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",COUPON_UNAVAILABLE:"reload_state",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 g(e,o){if(e==="CONFLICT"&&o===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&o===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION"||e==="SENSITIVE_OUTPUT_REQUIRED")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(S,e)){let n=S[e];return{retryable:n==="retry_same_request",recovery:n}}let t=R.safeParse(e);return t.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:L[t.data].recovery}:{retryable:!1,recovery:"contact_support"}}function Q(e,o){let t=R.safeParse(e);if(t.success)return e==="CONFLICT"?[409,412,425].includes(o):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(o):e==="INVALID_REQUEST"?[400,405,415,422].includes(o):e==="NOT_CONFIGURED"?[501,503].includes(o):L[t.data].status===o;let n={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],SENSITIVE_OUTPUT_REQUIRED:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(n,e)&&(n[e]?.includes(o)??!1)}function P(e,o=Date.now()){if(e===null)return;let t=e.trim();if(/^\d+$/.test(t)){let s=Number(t);return Number.isSafeInteger(s)?s:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(t))return;let n=Date.parse(t);return Number.isFinite(n)?Math.max(0,Math.ceil((n-o)/1e3)):void 0}var y=r.object({retryable:r.boolean(),recovery:v,reason:x.optional(),retryAfterSeconds:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),b=r.object({requestId:r.uuid().optional(),error:r.object({code:r.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:r.string(),...y.partial().shape})}),z=r.object({error:b.shape.error.extend({requestId:r.uuid().optional()})}),Y=r.object({error:r.string(),code:r.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:r.uuid(),...y.shape});function $(e,o,t={}){let n=g(e,o),s=t.reason==="RESULT_UNKNOWN"?"recover_operation":t.recovery??n.recovery,A=n.retryable&&t.retryable!==!1&&s!=="recover_operation",i=A?P(t.retryAfter??null):void 0;return{...n,retryable:A,recovery:s,...i===void 0?{}:{retryAfterSeconds:i},...t.reason?{reason:t.reason}:{}}}var V=r.enum(["sandbox","live"]),W=r.object({projectId:r.string().min(1),environment:V}).strict();var J=r.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),u=r.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),M=r.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let o=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return o==="-0"?"0":o}),p=u.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),D=r.string().min(1).max(64),B=r.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),C=r.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),ee=r.record(D,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(([o,t])=>[o,String(t)]))),U=r.record(D,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"),I=e=>{let o=e.startsWith("-");o&&(e=e.slice(1));let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");let s=BigInt(t)*BigInt("1000000")+BigInt(n.padEnd(6,"0"));return o?-s:s},h=r.array(r.object({upTo:p.nullable(),cost:u}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((o,t)=>{let n=e[t-1]?.upTo;return o.upTo!==null&&(t===0||n!=null&&I(o.upTo)>I(n))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),G=r.object({key:C,match:U,priority:r.number().int().default(0),cost:u.optional(),tiers:h.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),F=r.object({key:C,match:U,factor:p.optional(),add:M.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"})),k=r.object({units:p.default("1"),cost:u,tiers:h.optional(),dimensions:r.array(G).max(12).optional(),multipliers:r.array(F).max(4).optional()}).strict().superRefine((e,o)=>{let t=e.dimensions??[],n=e.multipliers??[];(new Set(t.map(i=>i.key)).size!==t.length||new Set(n.map(i=>i.key)).size!==n.length)&&o.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[i,a]of t.entries())for(let c of t.slice(i+1))Object.keys(a.match).length===Object.keys(c.match).length&&a.priority===c.priority&&!Object.keys(a.match).some(E=>c.match[E]!==void 0&&c.match[E]!==a.match[E])&&o.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let s=[e.cost,...(e.tiers??[]).map(i=>i.cost),...t.flatMap(i=>[...i.cost===void 0?[]:[i.cost],...(i.tiers??[]).map(a=>a.cost)])],A=I(e.units);for(let i of s)for(let a=0;a<1<<n.length;a++){let c=n.filter((N,_)=>a&1<<_);if(c.some((N,_)=>c.slice(_+1).some(d=>Object.keys(N.match).some(l=>d.match[l]!==void 0&&d.match[l]!==N.match[l]))))continue;let E=I(i),O=BigInt("1"),f=BigInt("0");for(let[N,_]of n.entries())a&1<<N&&(E*=I(_.factor??"1"),O*=BigInt("1000000"),f+=I(_.add??"0"));let T=(E+f*O)*BigInt("1000000"),m=O*A;(T<BigInt("0")||T%m!==BigInt("0")||T/m>BigInt("999999999999999999"))&&o.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"})}}),re=k.safeExtend({featureKey:B});export{R as a,v as b,x as c,Q as d,b as e,$ as f,V as g,W as h,J as i,u as j,M as k,B as l,ee as m};
@@ -0,0 +1 @@
1
+ import{C as K,b as U,d as D,v as _}from"./chunk-MWICFZUF.js";import{a as z,c as F}from"./chunk-CWD36SJO.js";import{d as $}from"./chunk-3SXPCVIP.js";import{i as C,j as m,l as O,m as g}from"./chunk-6XRXHFM6.js";import{b as e}from"./chunk-GPJF3T43.js";var I=m.refine(t=>/[1-9]/.test(t),"Quantity must be positive"),j=e.string().min(1).max(120),R=e.enum(["cap","overflow"]),p=(t,n)=>{let[i,u=""]=t.split(".");if(i===void 0||i==="")throw new Error("Invalid decimal value");return BigInt(i)*10n**BigInt(n)+BigInt(u.padEnd(n,"0"))},A=t=>{try{return t()}catch{return!1}},le=e.discriminatedUnion("operation",[e.object({operation:e.literal("quote"),overageBehavior:R.optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g}).strict(),e.object({operation:e.literal("consume"),overageBehavior:R.optional(),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:m,properties:g,idempotencyKey:j}).strict(),e.object({operation:e.literal("reserve"),occurredAt:e.iso.datetime({offset:!0}).optional(),internal_feature_id:e.uuid(),entityId:e.uuid().optional(),quantity:I,properties:g,idempotencyKey:j,expiresInSeconds:e.number().int().min(1).max(86400)}).strict(),e.object({operation:e.literal("confirm"),operationId:e.uuid(),quantity:I,properties:g.optional(),idempotencyKey:j}).strict(),e.object({operation:e.literal("refund"),operationId:e.uuid(),quantity:I,idempotencyKey:j}).strict(),e.object({operation:e.literal("release"),operationId:e.uuid(),idempotencyKey:j}).strict()]),J=e.object({internal_credit_feature_id:e.uuid().nullable(),internal_metered_feature_id:e.uuid(),dimension:e.string().min(1).max(64),counterKey:e.string().min(1).max(240),cycleStart:e.iso.datetime({offset:!0}),unitCost:m,units:I,amount:C,tier:e.number().int().min(1).max(12).nullable()}).strict(),Q=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function N(t,n){let i=t.reduce((u,a)=>u+p(a.units,12),0n)-p(n,12);return t.some(u=>u.funding==="balance")?i>=-100n&&i<=100n:i===0n}var v=e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q.refine(t=>/[1-9]/.test(t)),amount:C}),e.strictObject({funding:e.literal("unbilled"),units:Q.refine(t=>/[1-9]/.test(t))}),e.object({funding:e.literal("prepaid"),sourceId:e.uuid(),units:I,amount:C,pricing:e.array(J).min(1).max(12)}).strict().refine(t=>A(()=>t.pricing.reduce((n,i)=>n+p(i.units,6),0n)===p(t.units,6)&&t.pricing.reduce((n,i)=>n+p(i.amount,12),0n)===p(t.amount,12)&&t.pricing.every(n=>p(n.unitCost,6)*p(n.units,6)===p(n.amount,12))),"Frozen pricing must conserve allocated units and amounts"),e.object({funding:e.literal("postpaid"),invoiceLineId:e.uuid().nullable(),units:I,authorizationId:e.uuid()}).strict()]),B=e.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),de=e.object({allowed:e.boolean(),internal_feature_id:e.uuid(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),reason:B.nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.allowed?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"A quote must conserve its accepted units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0&&/[1-9]/.test(t.quantity):t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Explicit overage behavior must retain the requested quantity"),me=e.object({id:e.uuid(),internal_feature_id:e.uuid(),kind:e.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,requestedQuantity:m.optional(),overageBehavior:R.optional(),accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),createdAt:e.iso.datetime({offset:!0}),reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:e.iso.datetime({offset:!0}).nullable(),allocations:e.array(v).max(500)}).strict().refine(t=>A(()=>t.accepted?t.reason===null&&N(t.allocations,t.quantity):t.reason!==null&&t.allocations.length===0),"An operation must conserve its requested units").refine(t=>A(()=>t.overageBehavior===void 0?t.requestedQuantity===void 0:t.kind==="consume"&&t.requestedQuantity!==void 0&&p(t.requestedQuantity,6)>=p(t.quantity,6)&&(t.overageBehavior==="cap"||t.requestedQuantity===t.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(t=>/[1-9]/.test(t.quantity)||t.kind==="consume","Only consumption can record a zero cost event").refine(t=>t.allocations.every(n=>n.funding!=="postpaid"||n.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(t=>t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null)&&(t.kind!=="reserve"||!t.accepted||t.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var X=e.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Y=e.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),T=e.strictObject({internal_feature_id:e.uuid(),entityId:e.uuid().nullable()}),ye=T.extend({quantity:m,expectedRevision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:e.string().min(1).max(120),properties:g.refine(t=>Object.keys(t).length<=13&&!Object.keys(t).some(n=>n.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),V=T.extend({operationId:e.uuid().nullable(),usage:m,capacity:X.nullable(),remaining:Y.nullable(),withinLimit:e.boolean(),revision:e.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:e.iso.datetime({offset:!0}).nullable()}).strict().superRefine((t,n)=>{let i=u=>{let a=u.startsWith("-"),[s,r=""]=(a?u.slice(1):u).split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return(a?-1n:1n)*(BigInt(s)*10n**12n+BigInt(r.padEnd(12,"0")))};(t.capacity===null!=(t.remaining===null)||(t.capacity===null?!t.withinLimit:t.remaining===null||i(t.remaining)!==i(t.capacity)-i(t.usage)||t.withinLimit!==i(t.remaining)>=0n)||t.revision===0!=(t.operationId===null)||t.operationId===null!=(t.updatedAt===null))&&n.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var y=e.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),f=e.iso.datetime({offset:!0}),ee=e.enum(["access","metered","credit"]),q={internal_feature_id:e.uuid(),key:O,name:e.string().min(1).max(120),kind:ee},we=e.object({customerId:e.uuid(),snapshotAt:f,memberships:e.array(e.object({id:e.uuid(),productId:e.string().min(1).max(255),productVersionId:e.uuid(),billingProductVersionId:e.uuid(),version:e.number().int().positive(),key:e.string().min(1).max(64),name:e.string().min(1).max(120),groupId:e.string().max(255).nullable(),membershipType:e.enum(["main","addon"]),status:e.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:e.boolean(),accessEnabled:e.boolean(),renewalChange:e.object({productVersionId:e.uuid(),name:e.string().min(1).max(120),version:e.number().int().positive(),effectiveAt:f,benefitsAppliedAt:f.nullable(),timing:e.enum(["immediate","renewal"]),changeKind:e.enum(["plan","seats","quantity"]),feature:e.strictObject({internal_feature_id:e.uuid(),name:e.string().min(1).max(80),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).optional(),seat:e.object({key:e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:e.number().int().min(0).max(1e4),toQuantity:e.number().int().min(0).max(1e4)}).strict().nullable(),status:e.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(t=>t.changeKind==="seats"==(t.seat!==null)&&t.changeKind==="quantity"==(t.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:e.object({phase:e.enum(["paid","trial"]),startsAt:f,endsAt:f.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:e.boolean(),balances:e.array(e.object({...q,usageType:e.enum(["consumable","non_consumable"]).nullable(),accessible:e.boolean(),unlimited:e.boolean(),available:y,held:y,debt:y,nextExpiresAt:f.nullable(),usage:V.nullable()}).strict().refine(t=>t.kind==="metered"==(t.usageType!==null)&&(t.accessible||t.available==="0"&&t.held==="0")&&(t.usageType==="non_consumable"?t.usage!==null&&t.usage.internal_feature_id===t.internal_feature_id&&t.unlimited===(t.usage.capacity===null)&&t.available===(t.usage.remaining===null||t.usage.remaining.startsWith("-")?"0":t.usage.remaining)&&t.held==="0"&&t.debt==="0":t.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:e.boolean()}).strict(),Z=e.enum(["source","usage","transaction","invoice","debt","settlement"]),E=e.object({at:f,id:e.uuid(),type:Z}).strict(),ke=e.object({type:Z.nullable(),resourceKey:O.optional(),kind:e.enum(["purchase","refund"]).optional(),topup:e.boolean().optional(),from:e.iso.date().nullable(),to:e.iso.date().nullable(),after:E.nullable(),limit:e.number().int().min(1).max(50)}).strict().refine(t=>!t.from||!t.to||t.from<=t.to,"Date range is reversed"),w={id:e.uuid(),occurredAt:f},te=e.discriminatedUnion("type",[e.strictObject({...w,type:e.literal("invoice"),status:e.string().min(1).max(80),paid:y,refunded:y,currency:z,externalId:e.string().nullable()}),e.object({...w,...q,type:e.literal("source"),reason:e.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:y,unlimited:e.boolean(),status:e.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:f,expiresAt:f.nullable(),orderId:e.uuid().nullable(),parentSourceId:e.uuid().nullable()}).strict(),e.object({...w,type:e.literal("usage"),internal_feature_id:e.uuid(),name:e.string().min(1).max(120),kind:e.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:e.uuid().nullable(),quantity:m,accepted:e.boolean(),reason:e.enum([...B.options,"expired"]).nullable(),properties:g,reservationStatus:e.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:f.nullable(),charges:e.array(e.discriminatedUnion("funding",[e.strictObject({funding:e.literal("balance"),sourceId:e.uuid(),rolloverId:e.uuid().nullable(),units:Q,amount:y}),e.strictObject({funding:e.literal("unbilled"),units:Q}),e.object({...q,funding:e.literal("prepaid"),amount:y}).strict(),e.object({funding:e.literal("postpaid"),invoiceId:e.uuid(),invoiceLineId:e.uuid(),authorizationId:e.uuid(),units:m,currency:z}).strict()])).max(500)}).strict().refine(t=>(t.kind==="set_usage"||t.kind==="consume"&&t.quantity==="0"?t.accepted&&t.reason===null&&t.charges.length===0&&t.reservationStatus===null:t.accepted?t.reason===null&&t.charges.length>0:t.reason!==null&&t.charges.length===0)&&t.originalId!==null===["confirm","refund","release","expire"].includes(t.kind)&&t.expiresAt!==null==(t.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),e.object({...w,type:e.literal("transaction"),purpose:e.enum(["product","invoice"]),productVersionId:e.uuid().nullable(),productName:e.string().min(1).max(120).nullable(),productVersion:e.number().int().positive().nullable(),invoiceId:e.uuid().nullable(),orderId:e.uuid(),originalId:e.uuid().nullable(),kind:e.enum(["purchase","refund"]),amountMinor:e.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(t=>t.currency===null==(t.amountMinor===null)&&(t.purpose==="product"?t.productVersionId!==null&&t.productName!==null&&t.productVersion!==null&&t.invoiceId===null:t.productVersionId===null&&t.productName===null&&t.productVersion===null&&t.invoiceId!==null)&&t.kind==="refund"==(t.originalId!==null)&&(t.kind!=="refund"||t.amountMinor===null||t.amountMinor>0),"Payment fact provenance is incomplete"),e.object({...w,...q,type:e.literal("debt"),sourceId:e.uuid(),transactionId:e.uuid(),amount:y}).strict(),e.object({...w,...q,type:e.literal("settlement"),sourceId:e.uuid(),debtId:e.uuid(),kind:e.enum(["payment","usage_refund","payment_return"]),amount:y}).strict()]),je=e.object({customerId:e.uuid(),rows:e.array(te).max(50),nextCursor:E.nullable()}).strict().refine(t=>new Set(t.rows.map(n=>n.type+n.id)).size===t.rows.length,"A page cannot repeat a fact").refine(t=>{let n=t.rows.at(-1);return!t.nextCursor||!!(n&&n.id===t.nextCursor.id&&n.type===t.nextCursor.type&&n.occurredAt===t.nextCursor.at)},"Cursor must name the final displayed fact");var Ce=e.discriminatedUnion("kind",[e.object({kind:e.literal("ledger"),cursor:E}).strict(),e.object({kind:e.literal("billing"),cursor:e.uuid()}).strict()]),ne=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ie=e.record(e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),e.union([e.string().max(500),e.boolean(),e.array(e.string().max(500)).max(50)])).refine(t=>Object.keys(t).length<=40,"Too many answers"),re=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function L(t,n=0){return n>20?!0:!!t&&typeof t=="object"&&(Array.isArray(t)?t.some(i=>L(i,n+1)):Object.entries(t).some(([i,u])=>["__proto__","constructor","prototype"].includes(i)||re.test(i)||L(u,n+1)))}var ae=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,ze=e.record(ne,$).refine(t=>Object.keys(t).length<=20,"Too many parameters").refine(t=>!L(t)&&!ae.test(JSON.stringify(t)),"Credentials cannot be screen parameters");var W=e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),oe=e.array(e.object({variable:W,componentId:W,required:e.boolean()}).strict()).max(40).refine(t=>new Set(t.map(n=>n.variable)).size===t.length&&new Set(t.map(n=>n.componentId)).size===t.length,"Input bindings must be unique"),Re=e.object({bindings:oe,answers:ie,values:e.record(e.string(),$).optional()}).strict();function H(t,n,i=1){if(t==="free")return"";if(t==="one_time")return n.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let u=n.split("-")[0]??"en",a={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"]},s={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},r=t==="week"?`/${s[u]??s.en}`:(a[u]??a.en)[t==="month"?0:1];return i===1?r:`/${i} ${r.slice(1)}${u==="en"?"s":""}`}function De(t,n){let i=[],u={};_(t,a=>{if(a.hidden)return!1;if(a.type!=="quantity_picker")return;let s=a.bind?.plan?[a.bind.plan]:[];a.bind?.picker&&_(t,r=>{if(r.type==="plan_picker"&&r.id===a.bind?.picker&&s.push(...r.planIds??[]),r.type==="stack"&&r.interaction?.type==="select"&&r.interaction.pickerId===a.bind?.picker)for(let o of r.children)o.type==="stack"&&o.bind?.plan&&s.push(o.bind.plan)}),s.length||i.push(`Quantity control ${a.id} needs a Product binding`);for(let r of new Set(s)){let o=n[r]?.prepaid?.find(c=>c.internalFeatureId===a.internalFeatureId)?.terms,d=u[r]??=new Set;(!o||d.has(a.internalFeatureId)||a.minimumQuantity<o.minimumQuantity||a.maximumQuantity>o.maximumQuantity)&&i.push(`Quantity control ${a.id} must match its Product's prepaid Feature and bounds`),d.add(a.internalFeatureId)}});for(let[a,s]of Object.entries(n))for(let r of s.prepaid??[])u[a]?.has(r.internalFeatureId)||i.push(`Product ${a} needs a quantity control for ${r.internalFeatureId}`);return i}function Ke(t,n,i,u){let a=u.plans[n];if(!a?.available)throw new Error("Selected Product is unavailable");let s={};if(_(t,r=>{if(r.hidden)return!1;if(r.type!=="quantity_picker"||r.hidden||(r.bind?.plan??(r.bind?.picker?i[r.bind.picker]:void 0))!==n)return;if(u.quantities?.[r.id]?.available===!1)throw new Error("This prepaid Feature is unavailable");let d=a.prepaid?.find(l=>l.internalFeatureId===r.internalFeatureId)?.terms,c=i[r.id];if(!d||typeof c!="number"||!Number.isSafeInteger(c)||c<Math.max(d.minimumQuantity,r.minimumQuantity)||c>Math.min(d.maximumQuantity,r.maximumQuantity)||(c-r.minimumQuantity)%r.step!==0||s[r.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");s[r.internalFeatureId]=c}),(a.prepaid??[]).some(r=>s[r.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return s}function ue(t,n,i){let u=t.terms.prices.find(a=>a.currency===n);if(!u||i<t.terms.minimumQuantity||i>t.terms.maximumQuantity)throw new Error("Quantity or currency is unavailable");return{amountMinor:U({quantity:i,unitAmountMinor:u.amountMinor,...u.pricing?{pricing:u.pricing}:{}}),allowance:D(t.includedAmount,t.terms.units,i)}}function Ne(t,n,i,u){let a=!1;if(_(t,o=>{o.type==="quantity_picker"&&(a=!0)}),!a)return n;let s=structuredClone(n);s.quantities={};let r=new Map;_(t,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker")return;let d=o.bind?.plan??(o.bind?.picker?i[o.bind.picker]??s.pickers[o.bind.picker]?.selected:void 0),c=typeof d=="string"?s.plans[d]:void 0,l=c?.prepaid?.find(G=>G.internalFeatureId===o.internalFeatureId),k=Math.max(o.minimumQuantity,l?.terms.minimumQuantity??0),x=Math.min(o.maximumQuantity,l?.terms.maximumQuantity??0),b=i[o.id]??o.defaultQuantity,h=typeof b=="number"&&Number.isSafeInteger(b)?b:o.defaultQuantity,S=!!l&&!!c?.available&&n.quantities?.[o.id]?.available!==!1&&h>=k&&h<=x&&(h-o.minimumQuantity)%o.step===0,P=s.quantities[o.id]={minimum:k,maximum:Math.max(k,x),step:o.step,value:h,label:"",available:S};if(!S||!l||!c?.currency||c.amountMinor===void 0)return;let M=ue(l,c.currency,h);P.label=`${new Intl.NumberFormat(u).format(Number(M.allowance))} ${l.name}${["week","month","year"].includes(l.reset)?H(l.reset,u,l.resetCount):l.reset==="lifetime"?"":` / ${l.resetCount} ${l.reset}`}`,M.amountMinor!==0&&r.set(String(d),(r.get(String(d))??c.amountMinor)+M.amountMinor)});for(let[o,d]of r){let c=s.plans[o];if(!c?.currency)continue;let l=F(d,c.currency,u);c.price=l;for(let[k,x]of Object.entries(s.nodes)){let b=K(t,k),h=S=>{if(S.price&&(S.price={...S.price,current:l,original:null}),b?.type==="text"){let P=t.strings.locales[u]?.[b.text]??t.strings.locales[t.strings.defaultLocale]?.[b.text];P?.includes("{{plan.price")&&(S.text=P.replace(/\{\{\s*plan.price\s*\}\}/g,l).replace(/\{\{\s*plan.price_per_month\s*\}\}/g,F(Math.round(d/((c.interval==="year"?12:1)*(c.intervalCount??1))),c.currency,u)))}};x.byPlan?.[o]&&h(x.byPlan[o]),(x.base.planVersionId===o||b&&"bind"in b&&b.bind?.plan===o)&&h(x.base)}}return s}export{le as a,J as b,Q as c,de as d,me as e,T as f,ye as g,V as h,y as i,we as j,ke as k,je as l,Ce as m,ie as n,ze as o,oe as p,Re as q,H as r,De as s,Ke as t,Ne as u};
@@ -0,0 +1 @@
1
+ import{b as _e}from"./chunk-RJY5CUTB.js";import{a as M}from"./chunk-V65FSNYO.js";import{D as ee,F as Ne,c as Re,e as D,j as Ee,u as ke,v as qe,x as Fe,z as Ae}from"./chunk-ANXDWUPK.js";import{a as Se,b as Ce,c as ve}from"./chunk-NVF54BDR.js";import{K as x}from"./chunk-DCZWNTG2.js";import{a as te}from"./chunk-B4AELNLE.js";import{i as ne}from"./chunk-AQONMY2H.js";import{A as X,C as Z,E as Pe}from"./chunk-KP4QI4RX.js";import{w as de}from"./chunk-5TJISOWN.js";import{b as Oe}from"./chunk-LUGZNBIW.js";import{a as l}from"./chunk-TL67SYPH.js";import{h as W}from"./chunk-6XRXHFM6.js";import{b as be}from"./chunk-ZICZN6WO.js";import{b as n}from"./chunk-GPJF3T43.js";import{a as pe}from"./chunk-DSPLGTQI.js";var g=x.options,Qe=n.discriminatedUnion("operation",[g[1].omit({customerToken:!0}),g[2].omit({customerToken:!0}),g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0}),g[8].omit({customerToken:!0}),Ee.omit({customerToken:!0})]),me=n.strictObject({receiptId:n.uuid(),operationId:n.uuid()}),nt=n.discriminatedUnion("operation",[n.strictObject({operation:n.literal("find_purchase")}),n.strictObject({operation:n.literal("recover_start"),intent:n.enum(["lookup","resume","start"]),start:n.strictObject({requestId:g[0].shape.requestId,funnelId:g[0].shape.funnelId,locale:g[0].shape.locale,parameters:g[0].shape.parameters})}),n.strictObject({operation:n.literal("recover_run"),runId:n.uuid(),funnelId:n.uuid()}),n.strictObject({operation:n.literal("recover_purchase"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("terminate_checkout"),runId:n.uuid(),funnelId:n.uuid(),purchase:me}),n.strictObject({operation:n.literal("settle_command"),runId:n.uuid(),funnelId:n.uuid(),requestId:n.uuid(),command:n.discriminatedUnion("operation",[g[3].omit({customerToken:!0}),g[4].omit({customerToken:!0}),g[5].omit({customerToken:!0}),g[6].omit({customerToken:!0}),g[7].omit({customerToken:!0})]).optional()}).refine(a=>!a.command||a.requestId===a.command.requestId),n.strictObject({operation:n.literal("run_command"),runId:n.uuid(),funnelId:n.uuid(),command:Qe})]),re=n.strictObject({runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),startRequestId:n.uuid(),runExpiresAt:n.iso.datetime({offset:!0}),status:D.shape.run.shape.status}),j={scope:W,customerId:n.uuid()},je=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("unknown"),target:n.null(),view:n.null(),access:n.null()}),n.strictObject({...j,outcome:n.literal("resolved"),target:re,view:D.shape.run.nullable(),access:n.discriminatedUnion("type",[n.strictObject({type:n.literal("customer")}),n.strictObject({type:n.literal("operation_only"),cause:n.enum(["run_terminal","run_expired","run_revoked","issuer_unavailable"])})])})]).superRefine((a,d)=>{a.outcome==="resolved"&&(a.access.type==="customer"!=(a.view!==null)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Recovery view and original Run binding differ"})}),Te=n.strictObject({...j,target:re,view:D.shape.run.nullable(),settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),acceptance:n.enum(["accepted","not_accepted","unknown"]),receiptPhase:n.enum(["accepted","processing","done"]).nullable(),basis:n.enum(["receipt","run_terminal","position_advanced","none"]),receiptId:n.uuid().nullable(),operationId:n.uuid().nullable()}),purchase:D.shape.purchase.unwrap().nullable()}).superRefine((a,d)=>{let m=a.settlement;(m.acceptance==="accepted"!=(m.receiptPhase!==null)||m.acceptance==="accepted"&&m.basis!=="receipt"||m.acceptance==="unknown"&&(m.state!=="unknown"||m.basis!=="none")||m.acceptance!=="accepted"&&(m.operationId!==null||m.receiptId!==null)||m.acceptance==="not_accepted"&&(m.state!=="settled"||!["run_terminal","position_advanced"].includes(m.basis))||a.purchase&&(a.purchase.receiptId!==m.receiptId||a.purchase.operation&&a.purchase.operation.operationId!==m.operationId||a.purchase.quote&&a.purchase.quote.operationId!==m.operationId)||a.view&&(a.view.id!==a.target.runId||a.view.source.id!==a.target.funnelId||a.view.source.versionId!==a.target.versionId||a.view.status!==a.target.status||a.view.runExpiresAt!==a.target.runExpiresAt||a.view.credentialExpiresAt!==null))&&d.addIssue({code:"custom",message:"Original command settlement binding differs"})}),Ue=n.strictObject({...j,target:re,purchase:D.shape.purchase.unwrap()}).superRefine((a,d)=>{(!a.purchase.operation||typeof a.purchase.canReselect!="boolean"||a.purchase.quote&&a.purchase.quote.operationId!==a.purchase.operation.operationId)&&d.addIssue({code:"custom",message:"Original purchase proof is incomplete"})}),xe=n.discriminatedUnion("outcome",[n.strictObject({...j,outcome:n.literal("none")}),n.strictObject({...j,outcome:n.literal("blocked")}),n.strictObject({...j,outcome:n.literal("found"),target:re,start:n.strictObject({locale:g[0].shape.locale,parameters:g[0].shape.parameters}),purchase:me})]);var Ye=x.options[0].refine(a=>!a.customer&&!a.customerData),Je=n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),terminal:n.enum(["complete","native"]).nullable()}),De=n.strictObject({schemaVersion:n.literal(1),baseUrl:n.url(),scope:W,customerId:n.uuid(),sessionId:n.uuid(),start:Ye,allowed:n.array(n.enum(["merchant","record_only","indiana","native"])),run:n.strictObject({id:n.uuid(),versionId:n.uuid(),status:Re.shape.status,revision:n.number().int().nonnegative(),runExpiresAt:n.iso.datetime({offset:!0}).optional()}).optional(),purchases:n.array(Je).max(100),operationCommand:n.strictObject({operationId:n.uuid(),intent:n.literal("confirm")}).optional(),journal:n.strictObject({revision:n.number().int().nonnegative(),entry:ke.nullable()})});function He(a){return Fe({...a,namespace:"purchases",identity:[a.scope.projectId,a.scope.environment,a.customerId]})}function Le(a){let d=new URL(a.baseUrl??be).href,m=()=>new l("PURCHASE_STORAGE_INVALID","Purchase recovery storage is unavailable or invalid; native fallback is not authorized");async function P(){a.assertCurrent();try{let v=await a.storage.read();if(a.assertCurrent(),!Number.isSafeInteger(v.revision)||v.revision<0)throw m();let s=v.entry===null?null:De.parse(v.entry);if(s&&(s.baseUrl!==d||s.customerId!==a.customerId||s.scope.projectId!==a.scope.projectId||s.scope.environment!==a.scope.environment))throw new l("SCOPE_MISMATCH","Purchase recovery belongs to another Customer or environment");if(s?.journal.entry&&(s.journal.entry.scope.projectId!==s.scope.projectId||s.journal.entry.scope.environment!==s.scope.environment||s.journal.entry.funnelId!==s.start.funnelId||s.journal.entry.runId!==s.run?.id||s.journal.entry.versionId!==s.run?.versionId)||s?.operationCommand&&!s.purchases.some(E=>E.operationId===s.operationCommand?.operationId))throw m();return{revision:v.revision,entry:s}}catch(v){throw v instanceof l?v:m()}}async function z(v){for(let s=0;s<8;s++){let E=await P(),O=v(structuredClone(E.entry));if(JSON.stringify(O)===JSON.stringify(E.entry))return O;O&&De.parse(O),a.assertCurrent();let R;try{R=await a.storage.write(E.revision,O)}catch{throw m()}if(a.assertCurrent(),R!==null){if(!Number.isSafeInteger(R)||R<=E.revision)throw m();return O}}throw new l("PURCHASE_STORAGE_CONFLICT","Another consumer changed this purchase; recover the original attempt")}return{read:P,update:z,baseUrl:d}}var Ke=5*6e4;function $e(a,d){let m=a.purchases.find(P=>P.type==="checkout");if(!a.actions.includes("continue_checkout")||m?.type!=="checkout"||d!==void 0&&m.operationId!==d)throw new l("PURCHASE_PENDING","No single resumable Checkout is confirmed");return m.checkoutUrl}function kt(a){let d={...a,scope:{...a.scope},executionPolicy:structuredClone(a.executionPolicy)},m=d.session.snapshot();if(!m)throw new l("CUSTOMER_SESSION_REQUIRED","Purchase recovery requires a verified Customer session");let{customerId:P,sessionId:z}=m,v=!1,s=null,E,O=null,R=!1,F,B,Q,k={mode:"idle",status:"idle",actions:["start"],purchases:[]},S=new Map,T=new Map,fe=new AbortController,Y=new Set,H=Oe(d),J=_e(H.request);function L(e){return{code:e instanceof l?e.code:"PURCHASE_RECOVERY_BLOCKED",message:e instanceof Error?e.message:"The original purchase requires server confirmation",...e instanceof l&&e.status!==void 0?{status:e.status}:{}}}function y(){if(v||d.session.snapshot()?.customerId!==P)throw new l("IDENTITY_CHANGED","The original purchase Customer changed")}let h=Le({...d,customerId:P,assertCurrent:y,storage:d.storage??He({baseUrl:d.baseUrl,scope:d.scope,customerId:P})}),Ve=d.session.subscribeIdentity(he);function he(){v||(v=!0,clearTimeout(Q),fe.abort(new l("IDENTITY_CHANGED","Purchase consumer was destroyed")),Ve(),s?.reset(),s=null,O=null,H.dispose(),Y.clear(),S.clear(),T.clear())}function C(e){y();let t=JSON.stringify(e)!==JSON.stringify(k);k=e,clearTimeout(Q),(e.mode==="operation"||e.mode==="run"&&!e.actions.includes("close"))&&["waiting_result","fulfillment","recording"].includes(e.status)&&(Q=setTimeout(()=>{U().catch(()=>{})},5e3)),t&&pe(d.onRecovery,structuredClone(e));for(let r of t?Y:[]){if(v)break;pe(r,structuredClone(e))}return structuredClone(e)}function I(e){if(y(),!e||e.start.requestId!==E)throw new l("PURCHASE_STORAGE_CONFLICT","This purchase was superseded; the old consumer cannot dispatch")}function b(e){let t=[...e.purchases],r=e.journal.entry?.purchase;return r&&!t.some(o=>o.operationId===r.operationId)&&t.push({receiptId:r.receiptId,operationId:r.operationId,terminal:null}),t}function A(e){return e.run&&!["running","waiting"].includes(e.run.status)&&!e.journal.entry?.command&&!e.journal.entry?.closeCommand&&!e.operationCommand&&b(e).every(t=>t.terminal!==null)}function _(e,t){let r=e.journal.entry?.command??e.journal.entry?.closeCommand,o=b(e).map(w=>{let le=S.get(w.operationId);return w.terminal&&!le?{type:w.terminal,operationId:w.operationId}:te({quote:le?.quote??null,operation:le??null,requestId:r?.requestId??null,pending:!1,destroyed:!1,canReselect:T.get(w.operationId)===!0})}),u=o.filter(w=>!["complete","native"].includes(w.type)),i=u[0],c=u.length===1&&i?.operationId?S.get(i.operationId):void 0;if(c&&(i?.type==="checkout"||i?.type==="cancel"))try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote)}catch(w){return{mode:t,status:"blocked",actions:["refresh",...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[]],purchases:o,error:L(w)}}let f;if(t==="operation"&&!r&&i?.type==="cancel"&&c?.quote&&!c.problem&&!c.confirmedAt)try{ee({allowed:e.allowed.filter(w=>d.executionPolicy.allowed.includes(w))},c.quote),Date.parse(c.quote.expiresAt)>Date.now()&&(f={operationId:c.operationId,quote:c.quote})}catch{}let p=o.length>0&&u.length===0,N=A(e)||t==="operation"&&p&&!r&&!e.operationCommand?"complete":i?.type==="checkout"?"checkout":i?.type==="fulfillment"?"fulfillment":i?.type==="recording"?"recording":r||e.operationCommand||i&&i.type!=="cancel"||t==="operation"&&!f?"waiting_result":"ready";return{mode:t,status:N,purchases:o,...f?{confirmation:structuredClone(f)}:{},actions:["refresh",...A(e)?["start"]:[],...t==="run"&&e.run&&["running","waiting"].includes(e.run.status)?["close"]:[],...e.operationCommand?["retry"]:f?["confirm"]:[],...u.length===1&&i?.type==="checkout"?["continue_checkout"]:[]]}}function oe(e){let t=te({quote:e?.quote??null,operation:e??null,requestId:null,pending:!1,destroyed:!1,canReselect:e&&T.get(e.operationId)===!0});return t.type==="complete"||t.type==="native"?t.type:null}function ae(e){if(!e.operation)return;let t=X.parse({...e.operation,...e.operation.quote?{}:e.quote?{quote:e.quote}:{}});if(t.merchantExecution&&t.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");let r=ne(S.get(t.operationId)??null,t);S.set(t.operationId,r),r===t&&T.set(t.operationId,e.canReselect===!0)}async function Ge(e){y();for(let r of[e.purchase,e.run.paywall])r&&ae(r);let t=await h.update(r=>{if(I(r),r.run&&(r.run.id!==e.run.id||r.run.versionId!==e.run.source.versionId))throw new l("SCOPE_MISMATCH","The original purchase Run changed");let o=b(r);for(let u of[e.purchase,e.run.paywall]){let i=u?.operation?.operationId??u?.quote?.operationId;if(!u||!i)continue;let c=o.find(p=>p.operationId===i);if(c&&c.receiptId!==u.receiptId)throw new l("INVALID_RESPONSE","The original purchase Receipt changed");let f=oe(S.get(i));c?c.terminal??=f:o.push({receiptId:u.receiptId,operationId:i,terminal:f})}return{...r,purchases:o,run:r.run&&(r.run.revision>e.run.revision||!["running","waiting"].includes(r.run.status)&&["running","waiting"].includes(e.run.status))?r.run:{id:e.run.id,versionId:e.run.source.versionId,status:e.run.status,revision:e.run.revision,runExpiresAt:e.run.runExpiresAt}}});I(t),t.run&&!["running","waiting"].includes(t.run.status)&&b(t).some(r=>!r.terminal)&&(t=await V(t,!t.journal.entry?.command&&!t.journal.entry?.closeCommand,new Set([e.purchase?.operation?.operationId,e.run.paywall?.operation?.operationId].filter(r=>!!r)))),I(t),C(_(t,"run"))}function Me(){return{async read(){let{entry:e}=await h.read();return I(e),structuredClone(e.journal)},async write(e,t){let r=null;return await h.update(o=>{if(I(o),o.operationCommand&&t?.command&&t.command.operation!=="close")throw new l("PURCHASE_PENDING","Recover the original Operation command before dispatching a Run mutation");return r=null,o.journal.revision!==e?o:(r=e+1,{...o,journal:{revision:r,entry:t}})}),r}}}async function V(e,t=!1,r=new Set){I(e);let o=b(e);for(let i of o){if(i.terminal)continue;let c=r.has(i.operationId)?S.get(i.operationId):void 0;if(c??=await se(e,i),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original Operation changed");if(c.merchantExecution&&c.merchantExecution.customerId!==P)throw new l("SCOPE_MISMATCH","Purchase execution belongs to another Customer");if(t&&!e.operationCommand&&te({quote:c.quote??null,operation:c,requestId:null,pending:!1,destroyed:!1}).type==="cancel"){let f=Z(c)?await J.update({operationId:i.operationId,intent:"cancel"}):await J.attach({operationId:i.operationId,intent:"cancel"});if(c=X.parse(f.operation),y(),c.operationId!==i.operationId)throw new l("INVALID_RESPONSE","Original cancellation Operation changed");c=await se(e,i)}S.set(i.operationId,ne(S.get(i.operationId)??null,c))}let u=await h.update(i=>{I(i);let c=i.operationCommand&&S.get(i.operationCommand.operationId);return{...i,...c&&(c.confirmedAt||c.merchantExecution||!Pe(c))?{operationCommand:void 0}:{},purchases:b(i).map(f=>({...f,terminal:f.terminal??oe(S.get(f.operationId))}))}});return I(u),u}async function G(e){y();let t=await H.request("funnels",e);return y(),t}async function ze(e){try{return await G(e)}catch(t){if(e.operation!=="recover_start"||e.intent!=="start"||!(t instanceof l)||t.status!==400||t.code!=="INVALID_REQUEST")throw t;return G({...e,intent:"resume"})}}async function Be(){let e=M(xe,await G({operation:"find_purchase"}));if(e.customerId!==P||e.scope.projectId!==d.scope.projectId||e.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(e.outcome!=="found")return e.outcome;let{target:t,purchase:r}=e;return await h.update(o=>o&&!A(o)?o:{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:{operation:"start",requestId:t.startRequestId,funnelId:t.funnelId,...e.start},allowed:[...d.executionPolicy.allowed],run:{id:t.runId,versionId:t.versionId,status:t.status,revision:0,runExpiresAt:t.runExpiresAt},purchases:[{...r,terminal:null}],journal:{revision:0,entry:null}}),"found"}let K;function ie(e){let t=K;if(t&&(!t.outcome||e&&t.outcome==="none"&&Date.now()-t.at<Ke))return t.job;let r={at:Date.now(),job:Be().then(o=>(r.outcome=o,r.at=Date.now(),o),o=>{throw K===r&&(K=void 0),o})};return K=r,r.job}async function se(e,t,r="recover_purchase"){let o=M(Ue,await G({operation:r,runId:e.run.id,funnelId:e.start.funnelId,purchase:{receiptId:t.receiptId,operationId:t.operationId}}));if(ue(e,o),o.purchase.receiptId!==t.receiptId||o.purchase.operation?.operationId!==t.operationId)throw new l("INVALID_RESPONSE","Original purchase reference changed");return ae(o.purchase),S.get(t.operationId)}async function Ie(e){for(let t of[e.journal.entry?.command,e.journal.entry?.closeCommand]){if(!t)continue;let r=M(Te,await G({operation:"settle_command",runId:e.run.id,funnelId:e.start.funnelId,requestId:t.requestId,...t.operation==="resume"?{}:{command:t}}));if(ue(e,r),r.settlement.requestId!==t.requestId)throw new l("INVALID_RESPONSE","Original command settlement changed");r.purchase&&ae(r.purchase);let o=await h.update(u=>{I(u);let i=b(u),{receiptId:c,operationId:f}=r.settlement;if(c&&f){let N=i.find(w=>w.operationId===f);if(N&&N.receiptId!==c)throw new l("INVALID_RESPONSE","Original Receipt changed");N||i.push({receiptId:c,operationId:f,terminal:oe(S.get(f))})}let p=r.settlement.state==="settled"?qe(u.journal.entry,t.requestId):u.journal.entry;return{...u,purchases:i,journal:p===u.journal.entry?u.journal:{revision:u.journal.revision+1,entry:p}}});I(o),e=o}return e}function ue(e,t){if(t.customerId!==P||t.scope.projectId!==d.scope.projectId||t.scope.environment!==d.scope.environment||t.target.funnelId!==e.start.funnelId||t.target.startRequestId!==e.start.requestId||e.run&&(t.target.runId!==e.run.id||t.target.versionId!==e.run.versionId))throw new l("SCOPE_MISMATCH","The original recovery binding changed")}async function ce(e,t){if(I(e),e.run&&(e=await Ie(e)),!b(e).length&&A(e))return C(_(e,"operation"));if(!b(e).length)return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(t)});R=!0;let r=await V(e);return C(_(r,"operation"))}async function $(e,t=!1,r=!0){if(E=e.start.requestId,O=structuredClone({requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}),!s){let o=e.run?{operation:"recover_run",runId:e.run.id,funnelId:e.start.funnelId}:{operation:"recover_start",intent:t?"start":"lookup",start:{requestId:e.start.requestId,funnelId:e.start.funnelId,locale:e.start.locale,parameters:e.start.parameters}},u;try{u=await ze(o)}catch(p){if(!e.run&&p instanceof l&&(p.status===void 0||p.status>=500))return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:L(p)});throw p}let i=M(je,u);if(i.customerId!==P||i.scope.projectId!==d.scope.projectId||i.scope.environment!==d.scope.environment)throw new l("SCOPE_MISMATCH","Recovery Customer or environment changed");if(i.outcome==="unknown")return C({mode:"blocked",status:"blocked",actions:["refresh","retry"],purchases:k.purchases,error:{code:"RESULT_UNKNOWN",message:"The original Start outcome remains unknown; retry only its original input"}});ue(e,i);let c=await h.update(p=>(I(p),{...p,run:{id:i.target.runId,versionId:i.target.versionId,status:i.target.status,revision:i.view?.revision??p.run?.revision??0,runExpiresAt:i.target.runExpiresAt}}));if(I(c),e=c,i.access.type==="operation_only")return ce(e,new l("RUN_RECONCILIATION_REQUIRED","Only the original command and Operation can be recovered"));e=await Ie(e);let f=i.view;if(f.locale!==e.start.locale||!Ae(f.parameters,e.start.parameters))throw new l("INVALID_RESPONSE","The original Start input changed");s=Ne({...d,customerRun:{runId:i.target.runId,customerId:P,startRequestId:e.start.requestId},funnelId:e.start.funnelId,funnelExecutionPolicy:{allowed:e.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},funnelCommandStorage:Me(),onAcceptedResponse:Ge},{scope:i.scope,run:f})}try{await s.get(),s.view?.pendingRequest?.requestId===e.start.requestId&&!s.pendingCommands?.length&&await s.resume(s.view.pendingRequest.requestId);for(let u of s.pendingCommands??[])u.operation!=="close"&&await s.settle?.(u.requestId);s.pendingCommands?.length&&await s.retry(),y();let o=(await h.read()).entry;return I(o),C(_(o,"run"))}catch(o){if(y(),r&&o instanceof l&&(o.status===401||o.status===409&&o.reason==="STATE_CHANGED")){s.reset(),s=null;let u=(await h.read()).entry;return I(u),$(u,!1,!1)}throw o}}function q(e,t="read",r){if(y(),F)return t==="read"||t===B?F:F.then(()=>q(e,t,r),()=>q(e,t,r));clearTimeout(Q);let o=e().catch(u=>{throw!v&&!r?.(u)&&C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:k.purchases,error:L(u)}),u});return F=o,B=t,o.then(()=>{F===o&&(F=void 0,B=void 0)},()=>{F===o&&(F=void 0,B=void 0)}),o}function U(){return q(async()=>{let{entry:e}=await h.read();if(!e||A(e)){if(await ie(!1)==="blocked")return we();({entry:e}=await h.read())}return e?(E&&e.start.requestId!==E&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R&&E===e.start.requestId?ce(e,k.error):$(e)):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})})}function we(){return C({mode:"blocked",status:"blocked",actions:["refresh"],purchases:[],error:L(new l("PURCHASE_PENDING","Check the outstanding purchases before starting another"))})}async function ye(){let e=await U();return e.mode==="operation"&&!e.actions.includes("confirm")&&!e.actions.includes("retry")?e:q(async()=>{let t=(await h.read()).entry;if(I(t),!R){if(!s?.view?.paywall?.quote)throw new l("PURCHASE_PENDING","Read the original quote before confirming");let p=s.view.paywall.operation;if(p?.confirmedAt||p?.merchantExecution||p&&!(Z(p)?["prepared","quoted"].includes(p.status):p.status==="pending"))return C(_(t,"run"));if(s.pendingCommands?.length)await s.retry();else{let w=s.view;await s.submit({operation:"submit",requestId:crypto.randomUUID(),nodeId:w.nodeId,visit:w.visit,revision:w.revision,input:{type:"paywall_confirm",operationId:w.paywall.quote.operationId,...w.paywall.quote.merchantTerms?{merchantConfirmation:de(w.paywall.quote.merchantTerms)}:{}}})}let N=(await h.read()).entry;return I(N),C(_(N,"run"))}let r=t.operationCommand?.operationId??k.confirmation?.operationId,o=r&&S.get(r);if(!r||!o||t.journal.entry?.command||t.journal.entry?.closeCommand)throw new l("PURCHASE_PENDING","The original Run command must be settled before Operation confirmation");ee({allowed:t.allowed.filter(p=>d.executionPolicy.allowed.includes(p))},o.quote),await h.update(p=>{if(I(p),p.journal.entry?.command||p.journal.entry?.closeCommand||p.operationCommand&&p.operationCommand.operationId!==r)throw new l("PURCHASE_PENDING","Another original command is pending");return{...p,operationCommand:{operationId:r,intent:"confirm"}}});let u={operationId:r,intent:"confirm",...o.quote?.merchantTerms?{merchantConfirmation:de(o.quote.merchantTerms)}:{}},i=Z(o)?await J.update(u):await J.attach(u),c=X.parse(i.operation);if(y(),i.operation.operationId!==r)throw new l("INVALID_RESPONSE","Original confirmation Operation changed");S.set(r,ne(o,c));let f=(await h.read()).entry;return I(f),C(_(await V(f,!1,new Set([r])),"operation"))},"confirm")}async function ge(){y();let{entry:e}=await h.read();return e?A(e)?"finished":"pending":"none"}return{get controller(){return s},get recovery(){return structuredClone(k)},get attempt(){return y(),structuredClone(O)},get identitySignal(){return fe.signal},get customerId(){return P},retained:ge,async findPurchase(){let e=await ge();if(e==="pending")return e;let t=await ie(!0);return y(),t==="none"?e:t},async readPaywall(e){y();let t=Se(e),[r,{readPaywallContent:o},{validateResourceCheck:u}]=await Promise.all([Ce(H.request,"resolvePaywall"),import("./paywall-content-5IWLT7YD.js"),import("./check-response-OIBVUP72.js")]);y();let i=r.request.parse({selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale}),c=await ve(H.request,r,i);u(i,c.paywall.check,c.scope);let f=await o(d,c.paywall);if(y(),t.paywallVersionId?f.id!==t.paywallVersionId:f.paywallId!==t.paywallId)throw new l("INVALID_RESPONSE","The requested Paywall changed");return f},start(e){let t=x.parse({...structuredClone(e),operation:"start",requestId:e.requestId??crypto.randomUUID()});if(t.operation!=="start"||t.customer||t.customerData)throw new l("INVALID_REQUEST","A Customer-owned Funnel start is required");return q(async()=>{let r=(await h.read()).entry;if((!r||A(r))&&await ie(!0)==="blocked")return we();let o=await h.update(u=>{if(u&&!A(u)){if(u.start.funnelId!==t.funnelId)throw new l("PURCHASE_PENDING","Recover the original Funnel before starting another purchase");return u}return{schemaVersion:1,baseUrl:h.baseUrl,scope:d.scope,customerId:P,sessionId:z,start:t,allowed:[...d.executionPolicy.allowed],purchases:[],journal:{revision:0,entry:null}}});if(!o)throw new l("PURCHASE_STORAGE_INVALID","Original start was not retained");return E!==o.start.requestId&&(s?.reset(),s=null,S.clear(),T.clear(),R=!1),R?ce(o,k.error):$(o,!0)},`start:${t.funnelId}`)},refresh:U,confirm:ye,retry:()=>R?ye():q(async()=>{let{entry:e}=await h.read();return e?$(e,!0):C({mode:"idle",status:"idle",actions:["start"],purchases:[]})},"retry"),async close(){return s?.view?q(async()=>{if(!s?.view)throw new l("PURCHASE_PENDING","Recover the original Run before closing");if(s.pendingCommands?.find(r=>r.operation==="close"))await s.retry();else if(["running","waiting"].includes(s.view.status)){let r=s.view;await s.submit({operation:"close",requestId:crypto.randomUUID(),nodeId:r.nodeId,visit:r.visit,revision:r.revision})}let t=(await h.read()).entry;return I(t),C(_(t,"run"))},"close"):U()},async continueCheckout(e,t){let r=t?await q(async()=>{let{entry:o}=await h.read();if(I(o),!o.run||!b(o).some(i=>i.operationId===t&&!i.terminal))throw new l("PURCHASE_PENDING","The original Checkout changed");let u=await V(o);return C(_(u,R?"operation":"run"))},`continue:${t}`,o=>o instanceof l&&o.code==="PURCHASE_PENDING"):await U();y(),await e($e(r,t))},async terminateCheckout(e){let t=await U();if(!t.purchases.find(o=>o.type==="checkout"&&o.operationId===e)||!t.actions.includes("continue_checkout"))throw new l("PURCHASE_PENDING","The original Checkout has changed");return q(async()=>{let{entry:o}=await h.read();I(o);let u=b(o).find(c=>c.operationId===e&&!c.terminal);if(!u||!o.run)throw new l("PURCHASE_PENDING","The original Checkout has changed");await se(o,u,"terminate_checkout");let i=await V(o,!1,new Set([e]));return C(_(i,R?"operation":"run"))},`terminate:${e}`,o=>o instanceof l&&["CAPABILITY_UNAVAILABLE","NOT_CONFIGURED"].includes(o.code))},subscribe(e){return Y.add(e),()=>{Y.delete(e)}},destroy:he}}export{He as a,$e as b,kt as c};
@@ -1,4 +1,4 @@
1
- import{a as $,b as N,c as J,d as q}from"./chunk-C2KT5ZFU.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-RV6UAUK2.js";import{b as C,c as O,e as j}from"./chunk-O4KXODTJ.js";import{a as _}from"./chunk-DSPLGTQI.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
1
+ import{a as $,b as N,c as J,d as q}from"./chunk-O6CUNETH.js";import{a as P}from"./chunk-3VUPVXAV.js";import{a as D}from"./chunk-ZICZN6WO.js";import{a as _}from"./chunk-DSPLGTQI.js";import{b as C,c as O,e as j}from"./chunk-C4NG6RVA.js";async function B(e,t,o,n={}){let r=n.message??"Invalid SDK JSON response",s=e.headers.get("content-length");if(!e.ok||!/^application\/json(?:;|$)/i.test(e.headers.get("content-type")??"")||s!==null&&(!/^\d+$/.test(s)||Number(s)>t)||!e.body)throw e.body?.cancel().catch(()=>{}),Error(r);let u;try{u=await P(e,t,{signal:o,error:()=>Error(r)})}catch(p){throw o.aborted?Error(r):p}return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u))}async function G(e,t){if(!e?.body)return;let o=new AbortController,n=()=>o.abort(t?.reason);t?.addEventListener("abort",n,{once:!0}),t?.aborted&&n();let r=setTimeout(()=>o.abort(Error("Exposure response timeout")),2e3);try{return await P(e,16384,{signal:o.signal,error:()=>Error("Exposure response budget")})}finally{clearTimeout(r),t?.removeEventListener("abort",n)}}var be=2*1024*1024,V=256*1024;async function Y(e,t,o,n){let r=()=>{},s=new Promise((u,p)=>{r=()=>p(n.reason),n.addEventListener("abort",r,{once:!0}),n.aborted&&r()});try{let u=e(t,{...o,signal:n});return u.then(p=>{n.aborted&&p.body?.cancel().catch(()=>{})},()=>{}),await Promise.race([u,s])}finally{n.removeEventListener("abort",r)}}async function M(e,t,o,n=!1){if(new TextEncoder().encode(o).byteLength>65536)throw Error("Exposure request budget");let r=new URL(t);r.searchParams.set("sdkVersion",D.version);let s=new AbortController,u=setTimeout(()=>s.abort(Error("Exposure request timeout")),5e3);try{let p=await Y(e,r.href,{method:"POST",headers:{"Content-Type":"text/plain"},body:o,credentials:"omit",keepalive:n,redirect:"error"},s.signal),a=await G(p,s.signal),c;try{c=a&&JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}catch{}return{response:p,receipt:c}}finally{clearTimeout(u)}}function H(e){let t,o=!1;return{async read(n,r){if(o)throw Error("Experiment client stopped");t?.abort(Error("Experiment request superseded"));let s=new AbortController;t=s;let{signal:u}=s,p=setTimeout(()=>s.abort(Error("Experiment request timeout")),5e3);try{let a=await Y(e,n,{cache:"no-cache",credentials:"omit",redirect:"error"},u),c=await B(a,r,u);return u.throwIfAborted(),c}finally{clearTimeout(p),t===s&&(t=void 0)}},destroy(){o=!0,t?.abort(Error("Experiment client stopped")),t=void 0}}}var Q=20,ie=65536,se=5e3,ae=5,K=e=>new TextEncoder().encode(JSON.stringify(e)).length;function ce(e,t){let o=e,n=r=>Number.isSafeInteger(r)&&r>=0;return!!o&&typeof o=="object"&&n(o.inserted)&&n(o.duplicates)&&n(o.skipped)&&Array.isArray(o.rejected)&&o.inserted+o.duplicates+o.skipped+o.rejected.length===t&&o.rejected.every(r=>!!r&&typeof r=="object"&&n(r.index)&&r.index<t&&typeof r.reason=="string")&&new Set(o.rejected.map(r=>r.index)).size===o.rejected.length}function F(e){let t=[],o,n,r=(a,c)=>{try{e.log?.(`${e.label} ${a}`,c)}catch{}};function s(a){o===void 0&&!n&&t.length&&(o=setTimeout(()=>{p()},a))}async function u(a,c){let g,f;try{({response:g,receipt:f}=await M(e.fetch,e.endpoint,JSON.stringify({events:a}),c))}catch(h){return r("not sent",{error:h}),!1}return g.status===408||g.status===429||g.status>=500?(r("not sent",{status:g.status}),!1):g.ok?ce(f,a.length)?(f.rejected.length&&r("rejected",{rejected:f.rejected}),!0):(r("not acknowledged",{status:g.status}),!1):(r("rejected",{status:g.status,events:a.length}),!0)}function p(a=!0){if(n)return n;clearTimeout(o),o=void 0;let c=[],g=K({events:[]});for(;t.length&&c.length<Q;){let m=K(t[0].event)+(c.length?1:0);if(c.length&&g+m>ie)break;c.push(t.shift()),g+=m}if(!c.length)return Promise.resolve();let f=1e3,h=u(c.map(m=>m.event),a).then(m=>{if(m)return;f=se;let y=c.filter(b=>++b.attempts<ae);y.length<c.length&&r("dropped after retries",{events:c.length-y.length}),t.unshift(...y)}).finally(()=>{n===h&&(n=void 0),s(f)});return n=h,h}return{push(a){t.push({event:structuredClone(a),attempts:0}),t.length>=Q?p():s(1e3)},flush:p}}/*!
2
2
  Portions ported from GrowthBook sdk-js @ ed29827 (GrowthBook.ts auto experiments, util.ts mergeQueryStrings,
3
3
  plugins/auto-attributes.ts). Copyright (c) GrowthBook, Inc. MIT License.
4
4
  */function ue(e,t){let o,n;try{o=new URL(e),n=new URL(t)}catch{return t}return o.searchParams.forEach((r,s)=>{n.searchParams.has(s)||n.searchParams.set(s,r)}),n.toString()}function de(e,t){let o=navigator.userAgent,n=new URLSearchParams(t.search),r={};for(let s of["source","medium","campaign","term","content"]){let u=n.get(`utm_${s}`);u!==null&&(r[`utm${s[0].toUpperCase()}${s.slice(1)}`]=u)}return{id:e,deviceId:e,url:t.href,path:t.pathname,host:t.host,query:t.search,pageTitle:typeof document>"u"?"":document.title,browser:/Edg/.test(o)?"edge":/Chrome/.test(o)?"chrome":/Firefox/.test(o)?"firefox":/Safari/.test(o)?"safari":"unknown",deviceType:/Mobi/.test(o)?"mobile":"desktop",...r}}function le(e){let t=e;if(!(!!t&&typeof t=="object"&&typeof t.environmentId=="string"&&typeof t.trackExposures=="boolean"&&/^[a-f0-9]{64}$/.test(t.generation??"")&&Array.isArray(t.experiments)&&t.experiments.length<=100&&t.experiments.every(n=>!!n&&!["namespace","status","url","groups"].some(r=>Object.hasOwn(n,r))&&(n.hashVersion===void 0||n.hashVersion===2)&&typeof n.key=="string"&&Array.isArray(n.variations)&&n.variations.length>=2&&n.variations.every(r=>!!r&&typeof r.urlRedirect=="string")&&(n.urlPatterns===void 0||Array.isArray(n.urlPatterns)))&&!!t.savedGroups&&typeof t.savedGroups=="object"&&!Array.isArray(t.savedGroups)))throw new Error("Invalid page experiment payload");return t}function Te(e){if(e.configuration&&e.configuration.scope.environmentId!==e.environmentId)throw new Error("Page configuration belongs to another App environment");let t=J(e.baseUrl);if(!/^[0-9a-f-]{36}$/i.test(e.environmentId))throw new Error("environmentId must be the App environment ID");let o=e.fetch??globalThis.fetch.bind(globalThis),n=H(async(i,d)=>{let l=await o(i,d);if(!l.ok)throw l.body?.cancel().catch(()=>{}),new Error(`Page experiments unavailable (${l.status})`);return l}),r=e.log?(i,d)=>_(e.log,i,d):void 0,s=`${t}/api/v1/page-experiments/${e.environmentId}`,u=$(e.deviceIdCookie??"indiana_did"),p=N(),a=null,c={...e.attributes??{}},g="",f=!1,h=!1,m=0,y=0,b=new Map,S=F({endpoint:`${s}/events`,fetch:o,log:r,label:"Exposure"}),k=S.flush,E={trackedExperiments:new Set,log:r,onExperimentViewed:(i,d)=>{e.trackExposures===!1||a?.trackExposures===!1||S.push({eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),deviceId:u,...p?{sessionId:p}:{},url:location.href,pageTitle:document.title.slice(0,512),experimentKey:i.key,variationKey:d.key})}},z=()=>{E.url=location.href,E.attributes={...de(u,location),...c}};function W(i){if(!e.disableCrossOriginUrlRedirects)return!1;try{let d=new URL(location.href);return i.variations.some(l=>{if(!l.urlRedirect)return!1;let v=new URL(l.urlRedirect);return v.protocol!==d.protocol||v.host!==d.host})}catch{return!0}}function X(i,d){let l=e.configuration?.snapshot?.generation,v=y,te=location.href;g=i;let re=e.navigate??(w=>location.replace(w)),ne=e.navigateDelay??(e.navigate?0:100),oe=e.maxNavigateDelay??1e3;Promise.all([Promise.race([d,new Promise(w=>setTimeout(w,oe))]),new Promise(w=>setTimeout(w,ne))]).then(()=>{!f&&v===y&&location.href===te&&(!e.configuration||e.configuration.fresh&&e.configuration.snapshot?.generation===l)&&re(i)})}function x(){if(!(!a||f||e.configuration&&!e.configuration.fresh)){z();for(let i of a.experiments){if(W(i)){r?.("Auto experiment blocked",{id:i.key});continue}let d;try{d=j(i,E)}catch(l){r?.("Skipping page experiment",{id:i.key,error:String(l)});continue}if(b.set(i.key,d),!!d.inExperiment){if(d.value.urlRedirect){let l=i.persistQueryString?ue(location.href,d.value.urlRedirect):d.value.urlRedirect;C(l,i.urlPatterns??[])?r?.("Skipping redirect because original URL matches redirect URL",{id:i.key}):l!==g&&X(l,k())}break}}}}let R="",Z=()=>{location.href!==R&&(y++,R=location.href,g="",x())},T,L;function ee(){T??=q(Z),addEventListener("pagehide",I)}let I=()=>{k()};async function A(){if(f)return!1;let i=++m,d;try{d=e.configuration?await e.configuration.pageExperiments():await n.read(s,V)}catch(v){if(f||i!==m)return!1;throw v}if(f||i!==m)return!1;let l=le(d);if(l.environmentId.toLowerCase()!==e.environmentId.toLowerCase())throw new Error("Page experiment payload scope changed");return a?.trackExposures===!1&&l.trackExposures&&E.trackedExperiments?.clear(),a=l,E.savedGroups=O(l.savedGroups),!0}function U(){f||(L??=e.configuration?.subscribe(()=>{!f&&e.configuration?.fresh&&A().then(i=>{i&&x()}).catch(i=>r?.("Page configuration unavailable",{error:String(i)}))}),ee(),R=location.href)}return{async start(){h||f||(h=!0,await A()&&(U(),x()))},async refresh(){await A()&&(y++,h&&U(),g="",x())},setAttributes(i){y++,g="",c={...i},x()},getResults(){return new Map(b)},get generation(){return a?.generation??null},destroy(){f||(f=!0,m++,n.destroy(),L?.(),T?.(),removeEventListener("pagehide",I),a=null,b.clear(),k())}}}export{be as a,H as b,F as c,ue as d,de as e,le as f,Te as g};
@@ -0,0 +1 @@
1
+ import{b as nn}from"./chunk-67SIVUOS.js";import{d as We,e as ce}from"./chunk-PBZSOTKZ.js";import{c as qe,d as je,e as K,l as Ze}from"./chunk-HLCDAU5A.js";import{A as Je,F as He,G as Qe,H as z,I as Ye,J as le,K as G,a as Me,c as Y,g as Z,h as Ge,i as Ue,m as $e}from"./chunk-DCZWNTG2.js";import{a as de,b as Xe}from"./chunk-CALDEF4M.js";import{a as j,b as _e,c as ke,e as De,h as Ve,i as Le,l as Be}from"./chunk-ASL7TJFU.js";import{b as tn}from"./chunk-B4AELNLE.js";import{A as ie,B as ae,z as oe}from"./chunk-KP4QI4RX.js";import{b as W}from"./chunk-LUGZNBIW.js";import{a as Q}from"./chunk-LSVTH3TS.js";import{m as Ke,n as ue,o as ze,p as se}from"./chunk-7MYS52FL.js";import{g as Ee,m as Ce,w as re}from"./chunk-MWICFZUF.js";import{b as Pe,d as L,e as Ae,f as Te}from"./chunk-3SXPCVIP.js";import{a as f}from"./chunk-TL67SYPH.js";import{h as V}from"./chunk-6XRXHFM6.js";import{b as en}from"./chunk-ZICZN6WO.js";import{b as n}from"./chunk-GPJF3T43.js";import{c as Ne,f as Oe}from"./chunk-C4NG6RVA.js";function rn(e){return Sn({...e,namespace:"commands",identity:[e.runToken]})}function Sn(e){let t,u,r=()=>new f("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),o=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,u=e.locks??globalThis.navigator?.locks,!t||!u||!globalThis.crypto?.subtle)throw r();let c=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??en).href,...e.identity])),a=new Uint8Array(await crypto.subtle.digest("SHA-256",c));return`indiana.funnel.${e.namespace}.v1.`+Array.from(a,i=>i.toString(16).padStart(2,"0")).join("")});o.catch(()=>{});async function m(c){try{let a=await o;return await u.request(a,{mode:"exclusive"},()=>c(a))}catch(a){throw a instanceof f?a:r()}}function d(c){let a=t.getItem(c);if(a===null)return{revision:0,entry:null};if(a.length>1048576)throw r();let i=JSON.parse(a);if(!i||typeof i!="object"||!("revision"in i)||!("entry"in i)||!Number.isSafeInteger(i.revision)||Number(i.revision)<0)throw r();return{revision:Number(i.revision),entry:i.entry}}return{read:()=>m(d),write:(c,a)=>m(i=>{if(d(i).revision!==c)return null;if(!Number.isSafeInteger(c+1))throw r();let y=JSON.stringify({revision:c+1,entry:a});if(y.length>1048576)throw r();return t.setItem(i,y),c+1})}}var on=n.strictObject({type:n.literal("funnel"),id:n.uuid(),versionId:n.uuid()});var M=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Rn=n.enum(["running","waiting","completed","closed","ineligible","failed"]),Fn=n.discriminatedUnion("type",[$e,n.strictObject({type:n.literal("wait"),receiptId:n.uuid(),kind:n.enum(["timer","event","operation"]),deadline:n.iso.datetime({offset:!0}).nullable(),eventName:M.optional()}),n.strictObject({type:n.literal("open_url"),receiptId:n.uuid(),url:He,openIn:Qe}),n.strictObject({type:n.literal("event"),receiptId:n.uuid(),event:M})]),En={id:M,presentation:Pe,outputs:n.array(M).max(250),inputs:se,values:n.record(n.string(),L).optional(),offeringKey:j.optional(),capabilities:Ee,customerData:Ce,dataCursors:n.record(M,Ke.nullable())},Cn=n.strictObject({...En,content:n.strictObject({type:n.literal("document"),document:re})}),pe=n.strictObject({id:n.uuid(),source:on,revision:n.number().int().nonnegative(),visit:n.number().int().nonnegative(),nodeId:M,nodeType:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Rn,stopped:n.boolean(),canBack:n.boolean(),authenticated:n.boolean(),locale:n.string().min(1).max(35),answers:ue,parameters:ze,variables:n.record(n.string(),L),output:L.nullable(),screen:Cn.nullable(),paywall:n.strictObject({receiptId:n.uuid(),resolution:n.union([We,ce]),quote:oe.nullable(),operation:ie.nullable(),purchaseRequestId:n.uuid().nullable(),selectionGeneration:n.number().int().nonnegative().optional(),canReselect:n.boolean().optional()}).nullable(),instruction:Fn.nullable(),pendingRequest:n.strictObject({requestId:n.uuid(),authenticationRequired:n.boolean()}).nullable(),runExpiresAt:n.iso.datetime({offset:!0}),credentialExpiresAt:n.iso.datetime({offset:!0}).nullable()}),Pn=n.strictObject({scope:V,run:pe,settlement:n.strictObject({requestId:n.uuid(),state:n.enum(["pending","unknown","settled"]),operationId:n.uuid().nullable(),receiptId:n.uuid().nullable().optional()}).optional(),purchase:n.strictObject({receiptId:n.uuid(),quote:oe.nullable(),operation:ie.nullable(),canReselect:n.boolean().optional()}).optional(),review:n.strictObject({activeOperationId:n.uuid().nullable(),pages:n.array(n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative()})).max(100),page:n.strictObject({receiptId:n.uuid(),nodeId:M,visit:n.number().int().nonnegative(),document:re,answers:ue,inputs:se,values:n.record(n.string(),L).optional()}).nullable(),coupons:n.array(n.strictObject({grantId:n.uuid(),status:n.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:n.string().nullable()})).max(100),purchases:n.array(n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),status:n.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:n.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:n.uuid().optional()}),an=Pn.extend({run:pe.extend({paywall:pe.shape.paywall.unwrap().extend({resolution:ce}).nullable()})});var un="X-Indiana-Server-Key";var Nn=n.strictObject({selector:n.string().min(1).max(2048),action:n.enum(["set","append","remove"]),attribute:n.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:n.string().max(5e4).optional(),parentSelector:n.string().max(2048).optional(),insertBeforeSelector:n.string().max(2048).optional()}),On=n.strictObject({variation:n.string().min(1).max(128),description:n.string().max(2e3).default(""),css:n.string().max(1e5).default(""),js:n.string().max(1e5).default(""),domMutations:n.array(Nn).max(200).default([]),iam:Ge.optional(),renderGuard:Z.optional()}),me=On.omit({variation:!0,description:!0,iam:!0}),An=qe.omit({variations:!0,active:!0}).extend({changeId:n.string().regex(/^[a-f0-9]{64}$/),variations:n.tuple([me,me]).rest(me).refine(e=>e.length<=20)}),sn=n.strictObject({trackExposures:n.boolean(),environmentId:n.uuid(),generation:n.string().regex(/^[a-f0-9]{64}$/),experiments:n.array(An).max(100),savedGroups:je});var $=n.string().regex(/^[a-f0-9]{64}$/),Ot=n.strictObject({iam:$,executionContracts:n.union([n.tuple([n.literal("funnel-run/1")]),n.tuple([n.literal("funnel-process/1")])]).default(["funnel-run/1"])}),Tn=n.strictObject({release:$,render:Z,button:n.strictObject({selector:n.string().min(1).max(512),elementKey:n.string().min(1).max(256),tag:n.enum(["button","a","input"])}).nullable()}),At=n.strictObject({scope:V.extend({environmentId:n.uuid()}),release:$,validatedAt:n.iso.datetime({offset:!0}),validUntil:n.iso.datetime({offset:!0}),entries:n.array(n.strictObject({id:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),event:n.enum(["screen_enter","button_click"]),delivery:Ue.optional(),target:Tn})).max(4e3)}),Tt=n.strictObject({operation:n.literal("entry_start"),funnelId:n.uuid(),versionId:n.uuid(),entryId:n.uuid(),release:$,requestId:n.uuid(),locale:n.string().min(1).max(35).default("en")}),_t=n.strictObject({scope:V,suppressed:n.literal(!0),reason:n.enum(["frequency","in_progress"]),retryAt:n.iso.datetime({offset:!0}).nullable()}),kt=n.strictObject({experimentId:n.uuid(),splitNodeId:n.string().min(1).max(128)}),_n=n.strictObject({experimentId:n.uuid(),experimentKey:n.string().min(1).max(128),variationKey:n.string().min(1).max(128),inExperiment:n.boolean(),generation:n.string().min(1).max(256)}),fe=n.strictObject({operation:n.literal("page_experiments"),release:$,usedReceiptIds:n.array(n.uuid()).max(20).default([]),customerToken:n.string().regex(Q).optional()}),ln=n.strictObject({scope:V,runId:n.uuid(),assignments:n.array(_n.extend({receiptId:n.uuid()})).max(100),payload:sn});var U=n.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),dn=n.strictObject({entry:U,nodes:n.array(n.strictObject({id:U,type:n.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:n.record(n.string(),U),writes:n.record(j,j),resources:n.strictObject({screenId:U.optional(),paywallVersionId:n.uuid().optional(),couponId:n.uuid().optional(),couponIds:n.array(n.uuid()).max(20).optional(),experimentId:n.uuid().optional(),featureKey:n.string().optional(),offeringVersionId:n.uuid().optional()})})).min(1).max(500)}),cn={scope:V,funnelId:n.uuid(),versionId:n.uuid(),evaluationRevision:n.number().int().nonnegative(),expiresAt:n.iso.datetime({offset:!0}).nullable(),topology:dn},X=n.discriminatedUnion("evaluationMode",[n.strictObject({...cn,evaluationMode:n.literal("local"),growth:K,conditions:n.record(U,n.array(n.strictObject({condition:Te,port:n.string()})))}),n.strictObject({...cn,evaluationMode:n.literal("remote")})]),kn=X.options[0].extend({evaluation:n.strictObject({maxTransitions:n.number().int().min(1).max(1e4),variables:n.record(j,ke),outputSchema:_e,terminals:n.record(U,n.strictObject({outcome:n.enum(["completed","closed","ineligible","failed"]),output:Je.nullable()}))})});function Dn(e){return dn.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let u={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":u.next=t.next;break;case"screen":Object.assign(u,t.outputs),r.screenId=t.screenId;{let m=e.screens.find(d=>d.id===t.screenId);m?.type==="paywall"&&(r.paywallVersionId=m.paywallVersionId)}break;case"condition":t.cases.forEach((m,d)=>{u[`case:${d}`]=m.target}),u.default=t.default;break;case"split":Object.assign(u,t.routes),u.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let m of["success","cancel","unavailable","failure"])u[m]=t[m];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=n.uuid().parse(t.action.coupon.value.id));break;case"external_page":u.opened=t.opened,u.failed=t.failed;break;case"wait":t.wait.type==="duration"?u.elapsed=t.wait.elapsed:(u.received=t.wait.received,u.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let o=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return o?.type==="feature"&&(r.featureKey=o.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:u,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ge(e){let t=le.parse(e.document),u=e.evaluationMode==="local"?K.parse(e.payload):null;if(u&&(u.scope.projectId!==e.scope.projectId||u.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:u?.expiresAt??null,topology:Dn(t)};return X.parse(e.evaluationMode==="remote"?r:{...r,growth:Ze(t,u),conditions:Object.fromEntries(t.graph.nodes.filter(o=>o.type==="condition").map(o=>[o.id,o.cases.map((m,d)=>({condition:m.condition,port:`case:${d}`}))]))})}function Kt(e){let t=ge(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let u=le.parse(e.document);return kn.parse({...t,evaluation:{maxTransitions:u.execution.maxTransitions,variables:u.variables,outputSchema:u.outputSchema,terminals:Object.fromEntries(u.graph.nodes.flatMap(r=>{let o=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:o&&o.type!=="literal"&&o.type!=="feature"&&o.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:o??null}]]}))}})}var Ie=32,Vn=522240;function ve(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var Ln=n.strictObject({nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),revision:n.number().int().nonnegative()}),ye=n.record(n.string(),L),Mn=n.strictObject({id:n.uuid(),nodeId:n.string().min(1).max(64),visit:n.number().int().nonnegative(),input:n.strictObject({schemaVersion:z.shape.schemaVersion,kind:z.shape.kind,selector:z.shape.selector,contract:z.shape.contract}),context:ye,removed:n.array(n.string()).max(100),attributes:ye,removedAttributes:n.array(n.string()).max(100),result:Ye,offeringVersionId:n.uuid().nullable(),events:n.strictObject({entered:n.string().regex(/^[1-9][0-9]{0,18}$/),decision:n.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),Yt=n.strictObject({schemaVersion:n.literal(1),mode:n.enum(["local","remote"]),versionId:n.uuid(),generation:n.number().int().positive(),base:Ln,context:ye,steps:n.array(Mn).min(1).max(Ie)}).refine(e=>Y(e)<=Vn,"Segment exceeds its byte budget");var qn=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function J(e){return Array.isArray(e)?e.some(J):!e||typeof e!="object"?!1:Object.entries(e).some(([t,u])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&J(u):!qn.test(t))}function pn(e,t,u,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(c=>c.id===t.screenId&&c.type==="paywall")))return"customer_required";let o=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(o&&["bundle","selection","offering"].includes(o.type)||t.type==="condition"&&t.cases.some(c=>J(c.condition)))return"customer_required";let m=JSON.stringify([t,t.type==="screen"?e.screens.find(c=>c.id===t.screenId):null]);for(let[c,a]of Object.entries(e.variables))if(a.source.type==="attribute"&&a.source.key!=="funnelParticipantId"&&(m.includes(`variables.${c}`)||m.includes(JSON.stringify(c))))return"customer_required";if(t.type==="split"){let c=u.experiments?.[t.experimentId];if((c?.hashAttribute??"id")!=="funnelParticipantId"||J(c?.condition)||c?.parentConditions?.length)return"customer_experiment_required"}let d=t.type==="feature"?t.featureKey:o?.type==="feature"?o.featureKey:void 0;return d&&u.features?.[d]?.rules?.some(c=>(c.hashAttribute??"id")!=="funnelParticipantId"||J(c.condition)||c.parentConditions?.length)?"customer_experiment_required":null}var he=class extends Error{constructor(u,r){super(r);this.code=u;this.name="FunnelLocalCalculationError"}code},ee=(e,t)=>new he(e,t),jn=e=>({experiments:e.experiments,features:e.features});function we(e,t=ee){let u=new Map(e.topology.nodes.map(d=>[d.id,d])),r=Ne(e.growth.savedGroups),o=jn(e.growth);function m(d,c){if(!Object.hasOwn(e.growth.features,d))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Oe(d,c).value}return{nodes:u,savedGroups:r,features:o.features,feature:m,evaluate(d,c){let a=u.get(d);if(!a)throw t("NOT_FOUND","Funnel node is unavailable");let i,g;if(a.type==="condition"){let v=e.conditions[a.id];if(!v)throw t("INVALID_RESPONSE","Local condition rules are unavailable");i=de({id:a.id,name:a.id,type:"condition",cases:v.map(h=>({condition:h.condition,target:a.outputs[h.port]})),default:a.outputs.default},c,o.experiments).port}else if(a.type==="feature"){if(!a.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");g=m(a.resources.featureKey,c),i="next"}else if(a.type==="split"){if(!(a.resources.experimentId?e.growth.experiments[a.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let h=de({id:a.id,name:a.id,type:"split",experimentId:a.resources.experimentId,routes:a.outputs,notParticipating:a.outputs.notParticipating},c,o.experiments);g=h.value,i=h.port}else if(["offering","end","output"].includes(a.type)&&a.resources.featureKey)g=m(a.resources.featureKey,c),i=a.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let y=a.outputs[i]??(i==="value"?a.id:void 0);if(!y)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:d,port:i,target:y,...g===void 0?{}:{value:g}}}}}function lr(e,t,u,r=ee){return be(e,r)(t,u)}function be(e,t){let u=X.parse(e);if(u.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=u.expiresAt?Date.parse(u.expiresAt):null,o=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};o();let m=we(u,t);return(d,c)=>(o(),Gn(m,d,c))}function Gn(e,t,u){let r=Ae.parse(u.attributes??{}),{saveStickyBucketAssignmentDoc:o,onFeatureUsage:m,onExperimentViewed:d}=u,c={attributes:r,...o?{saveStickyBucketAssignmentDoc:a=>o(structuredClone(a))}:{},...m?{onFeatureUsage:(a,i)=>m(a,structuredClone(i))}:{},...d?{onExperimentViewed:(a,i)=>d(structuredClone(a),structuredClone(i))}:{},features:e.features,savedGroups:e.savedGroups,...u.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(u.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function cr(e,t,u,r=ee){return mn(be(e,r),t,u)}function mn(e,t,u){let r=[],o=[],m=[],d=e(t,{...u.attributes?{attributes:u.attributes}:{},stickyBucketAssignmentDocs:u.sticky,saveStickyBucketAssignmentDoc(c){let a=r.findIndex(y=>y.next.attributeName===c.attributeName&&y.next.attributeValue===c.attributeValue),i=c.attributeName+"||"+c.attributeValue,g={expected:u.sticky[i]??null,next:c};a<0?r.push(g):r[a]=g},onExperimentViewed(c,a){a.inExperiment&&a.hashUsed&&!a.passthrough&&o.push(L.parse({key:c.key,variationId:a.variationId,keyUsed:a.key,hashAttribute:a.hashAttribute,hashValue:a.hashValue}))},onFeatureUsage(c,a){m.push(L.parse({feature:c,value:a.value,source:a.source,...a.ruleId?{ruleId:a.ruleId}:{}}))}});return{port:d.port,...d.value===void 0?{}:{value:d.value},sticky:r,exposures:o,features:m}}function fn(e,t,u,r=ee){let o=u,m=new Map(t.graph.nodes.map(O=>[O.id,O])),d=structuredClone(u.variables),c=structuredClone(o.sticky),a=[],i=u.nodeId,g=u.visit,y=!1,v,h=O=>pn(t,O,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},o.attributes.funnelCustomerBound===!0),b=O=>(v??=be(e,r),mn(v,O,{attributes:Be({declarations:t.variables,attributes:o.attributes,parameters:u.parameters,answers:u.answers,results:d,savedGroups:{}}),sticky:c}));for(let O=0;O<Ie;O++){let s=m.get(i);if(!s||!ve(s)||h(s))break;if(g>=t.execution.maxTransitions&&(g>t.execution.maxTransitions||s.type!=="end"&&s.type!=="output")){if(!a.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let p,x;if(["condition","feature","split"].includes(s.type)||s.type==="offering"&&s.configuration.source==="feature")p=b(s.id),s.type==="offering"&&(p.value={type:"offering_version",id:String(p.value)}),s.type==="condition"?x=p.port==="default"?s.default:s.cases[Number(p.port.slice(5))]?.target:s.type==="split"?x=p.port==="notParticipating"?s.notParticipating:s.routes[p.port]:(s.type==="feature"||s.type==="offering")&&(x=s.next);else if(p={port:"next",sticky:[],exposures:[],features:[]},(s.type==="entry"||s.type==="coupon"||s.type==="coupons")&&(x=s.next),s.type==="offering"&&s.configuration.source==="fixed"&&(p.value={type:"offering_version",id:s.configuration.versionId},x=s.next),s.type==="end"||s.type==="output"){let S=s.type==="end"?s.output:s.value;if(p=S?.type==="feature"?b(s.id):{...p,port:"value",value:S?.type==="literal"?S.value:S?.type==="variable"?Me({source:"variable",key:S.key,...S.path?{path:S.path}:{}},{declarations:t.variables,answers:u.answers,results:d,parameters:u.parameters,attributes:o.attributes,savedGroups:{}}):null},S&&(p.value===void 0||!De(t.outputSchema,p.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let C=[...a,{nodeId:i,result:p}];if(Y({steps:C})>6e4){if(!a.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(a.push({nodeId:i,result:p}),s.type==="feature"||s.type==="offering"||s.type==="coupon"||s.type==="coupons"){let S=s.type==="coupons"?s.couponIds.map(D=>({type:"reward",id:D})):s.type==="coupon"?{type:"reward",id:s.couponId}:p.value;if(S===void 0)throw r("INVALID_RESPONSE","Node output is missing");let _=Ve(s,{value:S});Le(t.variables,s,_),Object.assign(d,_)}for(let S of p.sticky)c[`${S.next.attributeName}||${S.next.attributeValue}`]=structuredClone(S.next);if(s.type==="end"||s.type==="output"){y=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");i=x,g++}let T=m.get(i);return{steps:a,...!y&&T&&(!ve(T)||h(T))?{boundary:{nodeId:i,visit:g}}:{}}}function gn(e,t){let u=an.safeParse(t);if(!u.success)throw new f("INVALID_RESPONSE","Funnel response contract changed");let r=u.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new f("SCOPE_MISMATCH","Funnel scope changed");return r}var xe=(e,t)=>new f(e,t);function Ir(e){return we(e,xe)}var Un=3,Bn=2e3;function Kn(e){return e instanceof TypeError||e instanceof f&&/^(?:CONFIGURATION_UNAVAILABLE|CONFIGURATION_HTTP_(?:429|5\d\d)|TEMPORARY_UNAVAILABLE)$/i.test(e.code)}async function zn(e){for(let t=1;;t++)try{return await e.refresh()}catch(u){if(t===Un||!Kn(u))throw u;await new Promise(r=>setTimeout(r,t*Bn))}}async function Se(e,t,{predict:u=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new f("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new f("SCOPE_MISMATCH","Evaluation environment changed");let o=null,m;if(u)try{let d=await e.funnel(t.source.id,t.source.versionId);m=d.manifest.generation,o=$n(e,t,d)}catch{o=null}return m??=e.snapshot?.generation??(await zn(e)).generation,{advance:{policyRevision:r.policyRevision,generation:m},prediction:o}}function $n(e,t,u){let r=t.instruction;if(r?.type!=="evaluate_segment"||!u.growth||u.control.evaluationMode!=="local"||u.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:o,remoteFeatures:m,...d}=u.growth,c=ge({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:u.document,payload:K.parse(d)}),a=Jn(c,u.document,{...t,...r}),i=a.steps.at(-1),g=a.boundary??(i?.result.port==="value"?{nodeId:i.nodeId,visit:t.visit+a.steps.length-1}:null);return g?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:g.nodeId,visit:g.visit,terminal:!a.boundary}:null}function Jn(e,t,u){return fn(e,t,u,xe)}var yn=G.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 f("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),In=n.strictObject({schemaVersion:n.literal(1),scope:V,runId:n.uuid(),funnelId:n.uuid(),versionId:n.uuid(),processBindingIds:n.record(n.uuid(),n.uuid().nullable()).optional(),command:yn.optional(),closeCommand:yn.refine(e=>e.operation==="close").optional(),purchase:n.strictObject({receiptId:n.uuid(),operationId:n.uuid(),generation:n.number().int().nonnegative()}).optional(),closed:n.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"),A=()=>new f("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ne=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function H(e,t){if(!e||!t)return e;if(e.processBindingIds&&Object.hasOwn(e.processBindingIds,t)){let u={...e.processBindingIds};delete u[t],e={...e,processBindingIds:u}}return e.command?.requestId===t?e.closeCommand?{...e,command:e.closeCommand,closeCommand:void 0}:e.purchase?{...e,command:void 0}:null:e.closeCommand?.requestId===t?{...e,closeCommand:void 0}:e}function vn(e){let t=0,u=null,r=a=>JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]),o=Promise.resolve();async function m(){let a=await e.read();if(!Number.isSafeInteger(a.revision)||a.revision<0)throw new f("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:a.revision,entry:a.entry===null?null:In.parse(a.entry)}}function d(a){let i=o.then(a);return o=i.catch(()=>{}),i}async function c(a){for(let i=0;i<4;i++){let g=await m();if(g.entry&&u!==null&&r(g.entry)!==u)throw A();let y=a(g.entry,g.revision);if(ne(g.entry,y)){t=g.revision;return}let v=await e.write(g.revision,y);if(v!==null){if(!Number.isSafeInteger(v)||v<=g.revision)throw A();t=v;return}}throw A()}return{bind(a){let i=JSON.stringify([a.scope,a.runId,a.funnelId,a.versionId]);if(u!==null&&u!==i)throw A();u=i},async load(){let a=await m();return t=a.revision,u=a.entry?r(a.entry):null,a.entry},retain(a){let i=In.parse(a),g=i.command;return!g||u!==null&&r(i)!==u?Promise.reject(A()):(u??=r(i),d(()=>c((y,v)=>{if(y&&!ne(r(y),r(i)))throw A();if(y&&i.processBindingIds){for(let[h,b]of Object.entries(i.processBindingIds))if(y.processBindingIds&&Object.hasOwn(y.processBindingIds,h)&&y.processBindingIds[h]!==b)throw A();y={...y,processBindingIds:{...y.processBindingIds,...i.processBindingIds}}}if(!y){if(v!==t&&g.operation!=="close")throw A();return i}if(!y.command)return{...y,command:g,...g.operation==="close"?{closed:!0}:{}};if(g.operation==="close"&&y.command.operation!=="close"){if(y.command.requestId===g.requestId||y.closeCommand&&!ne(y.closeCommand,g))throw A();return{...y,closeCommand:g,closed:!0}}if(!ne(y.command,g))throw A();return y})))},observePurchase(a,i,g,y){return d(()=>c((v,h)=>{if(!v&&h!==t||v&&r(v)!==r({...a,schemaVersion:1}))throw A();if(v?.purchase&&v.purchase.generation>i.generation)return H(v,y);if(v?.purchase&&v.purchase.generation===i.generation&&v.purchase.operationId!==i.operationId)throw A();return g?!v?.purchase||v.purchase.operationId!==i.operationId?H(v,y):H(v.command?{...v,purchase:void 0}:null,y):H({schemaVersion:1,...a,...v,purchase:i},y)}))},settle(a){return d(()=>c(i=>H(i,a)))}}}function Or(e,t){return t.type==="id"?e.customerId===t.value:e.externalUserId===t.value}function te(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((o,m)=>te(o,t[m]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let u=Object.entries(e),r=Object.entries(t);return u.length===r.length&&u.every(([o,m])=>Object.hasOwn(t,o)&&te(m,Reflect.get(t,o)))}function hn(e,t){let u=t&&{...t},r=null,o=0,m=-1,d=0,c=new AbortController;function a(){d++,c.abort(new f("IDENTITY_CHANGED","Run identity changed")),c=new AbortController}let i=!1,g,y=0,v=new Set;return{get scope(){return u},bindScope(h){if(u&&(u.projectId!==h.projectId||u.environment!==h.environment))throw new f("SCOPE_MISMATCH","Run scope changed");u??={...h}},get view(){return r},get currentView(){return m===d?r:null},get viewAgeMs(){return r&&m===d?performance.now()-o:void 0},get generation(){return d},get signal(){return c.signal},get disposed(){return i},get customerToken(){return g},get readSequence(){return y},nextRead(){return++y},assertCurrent(h,b="Run identity changed during the request"){if(h!==d||i)throw new f("IDENTITY_CHANGED",b)},assertRun(h){if(r&&(h.id!==r.id||h.source.type!==r.source.type||h.source.id!==r.source.id||h.source.versionId!==r.source.versionId||h.locale!==r.locale||!te(h.parameters,r.parameters)))throw new f("INVALID_RESPONSE","Run version changed");if(e&&h.source.id!==e)throw new f("INVALID_RESPONSE","Run belongs to another Funnel")},publish(h,b,T,O,s){if(!(h.operation==="review"&&r&&r!==T&&b.run.revision<=r.revision)&&!(r&&b.run.revision===r.revision&&O!==void 0&&O<y)&&(h.operation==="review"&&!b.run.stopped&&["running","waiting"].includes(b.run.status)&&r&&m===d&&b.run.nodeId===r.nodeId&&b.run.visit===r.visit&&b.run.revision===r.revision&&(b.run.screen=r.screen,(r.paywall?.quote?.operationId===b.review?.activeOperationId||!r.paywall?.quote&&b.review?.activeOperationId===null)&&(b.run.paywall=r.paywall)),!(r?.paywall&&b.run.paywall&&r.paywall.receiptId===b.run.paywall.receiptId&&(b.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||b.run.revision>=r.revision)r=b.run,o=performance.now(),m=d;else if(!s)return;if(r&&m===d)for(let p of v)try{p(structuredClone(r))}catch{}}},identify(h){if(i)throw new f("IDENTITY_CHANGED","Controller was reset");if(!Q.test(h))throw new f("INVALID_TOKEN","Customer credential required");a(),g=h},subscribe(h){return v.add(h),()=>v.delete(h)},reset(){i||(i=!0,a(),g=void 0,r=null,v.clear())}}}var Re=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function Lr(e,t,u="A server API key is required"){if(typeof window<"u")throw new f("SERVER_ONLY",t);if(!Re.test(e))throw new f("INVALID_TOKEN",u)}function Mr(e){let t=W(e);return t.identify(e.apiKey),t}function wn(e,t){if(!e)return;let u=t?.execution,r=u?.provider==="merchant"?"merchant":u?.provider==="stripe"?u.executor==="merchant"?"record_only":"indiana":t&&!ae(t)&&["apple","google"].includes(t.provider)?"native":t&&!ae(t)&&t.provider==="stripe"?"indiana":void 0;if(!r||!e.allowed.includes(r))throw new f("EXECUTION_POLICY_REFUSED","The original quote does not permit the declared purchase execution")}function q(e){let{customerToken:t,...u}=e;return u}var Hn=e=>!(e instanceof f&&e.code==="EXECUTION_POLICY_REFUSED")&&(!(e instanceof f)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation");function bn({journal:e,state:t,call:u,processIdentity:r}){let o=null,m=null,d=!1,c={command:null,close:null},a=new Set,i,g=null,y=e?e.load().then(s=>{if(t.disposed)throw new f("IDENTITY_CHANGED","Controller was reset during command restoration");if(g=s,!s)return;if(r){if([s.command,s.closeCommand].some(x=>x&&!Object.hasOwn(s.processBindingIds??{},x.requestId)))throw new f("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(s.processBindingIds??{})}if(t.scope&&(s.scope.projectId!==t.scope.projectId||s.scope.environment!==t.scope.environment))throw new f("SCOPE_MISMATCH","Pending command belongs to another scope");if(i=s.purchase,d=s.closed===!0,!s.command)return;let p=s.command;o=p.operation==="close"?null:p,m=p.operation==="close"?p:s.closeCommand?.operation==="close"?s.closeCommand:null,m&&(d=!0);for(let x of[o,m])x&&a.add(x.requestId)}):Promise.resolve();y.catch(()=>{});async function v(s){e&&await y;let p=t.generation;if(e){if(!t.view||!t.scope)throw new f("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:q(s),...r?{processBindingIds:{[s.requestId]:r.binding(s.requestId)}}:{}})}if(p!==t.generation||o!==s&&m!==s)throw new f("IDENTITY_CHANGED","Run changed before command dispatch");let x=a.has(s.requestId);a.add(s.requestId);try{return await u(s)}catch(C){let S=s.operation==="submit"&&s.input.type==="paywall_quote",_=!x&&!Hn(C),D=!1;if(S&&_&&p===t.generation&&o===s&&C instanceof f&&C.status!==void 0){let l=await T(s.requestId).catch(()=>{});D=l?.settlement?.state==="unknown"&&l.settlement.operationId===null}throw p===t.generation&&(o===s||m===s)&&_&&(!S||!(C instanceof f)||C.status===void 0||D)&&(e&&await e.settle(s.requestId),p===t.generation&&O(s)),C}}function h(s){let p=G.parse(s);if(p.operation==="start"||p.operation==="get"||p.operation==="review")throw new f("INVALID_REQUEST","Mutation required");if(d&&p.operation!=="close"){if(o?.requestId===p.requestId)return T(p.requestId);throw new f("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(p.operation==="close"){if(o?.requestId===p.requestId)throw new f("INVALID_REQUEST","Close requires its own request identity");if(d=!0,m&&JSON.stringify(q(m))!==JSON.stringify(q(p)))throw new f("COMMAND_PENDING","Retry the original Close");return m??=p,c.close?c.close:b(m,"close")}if(o){if(JSON.stringify(q(o))!==JSON.stringify(q(p)))throw new f("COMMAND_PENDING","Retry the original command before sending another");if(c.command)return c.command}else o=p;return b(o,"command")}function b(s,p){let x=v(s);c[p]=x;let C=()=>{c[p]===x&&(c[p]=null)};return x.then(C,C),x}function T(s){return u({operation:"get",settlementRequestId:s})}function O(s){return!s||o!==s&&m!==s?!1:(o===s&&(o=null),m===s&&(m=null),a.delete(s.requestId),!o&&!m&&(g=null),!0)}return{ready:y,get pending(){return o},get closing(){return m},get closeRequested(){return d},get inFlight(){return c.command},get closeFlight(){return c.close},get purchase(){return i},assertBinding(s){if(g&&(s.run.id!==g.runId||s.run.source.id!==g.funnelId||s.run.source.versionId!==g.versionId))throw new f("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(s,p,x,C){let S=s.operation==="get"?s.settlementRequestId:"requestId"in s&&s.operation!=="start"?s.requestId:void 0,_=S&&p.settlement?.state==="settled"&&p.run.pendingRequest?.requestId!==S&&(s.operation==="get"||!d||s.operation==="close"||!["running","waiting"].includes(p.run.status))?S:void 0,D=o?.requestId===_?o:m?.requestId===_?m:void 0;e?.bind({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId});let l=p.run.paywall,I=l??p.purchase,P=I?.operation,E=p.settlement&&(!l||l.purchaseRequestId===p.settlement.requestId)&&(!i||i.operationId===p.settlement.operationId)?p.settlement:void 0,R=P?.operationId??I?.quote?.operationId??E?.operationId,F=I?.receiptId??E?.receiptId,w=l?.selectionGeneration??i?.generation??0;if(e&&R&&F&&s.operation!=="review"&&(!t.view||p.run.revision>=t.view.revision)&&(C===void 0||C>=t.readSequence)&&(!i||w>=i.generation)){let N={receiptId:F,operationId:R,generation:w},k=tn(P,I?.canReselect===!0);await e.observePurchase({scope:p.scope,runId:p.run.id,funnelId:p.run.source.id,versionId:p.run.source.versionId},N,k,_),t.assertCurrent(x),(!i||N.generation>=i.generation)&&(C===void 0||C>=t.readSequence)&&(k?i?.operationId===N.operationId&&(i=void 0):i=N)}else e&&_&&await e.settle(_);return t.assertCurrent(x),_?O(D):!1},stop(){d=!0},submit:h,settle:T,reset(){d=!0,o=null,m=null,i=void 0,g=null,c.close=null,a.clear(),c.command=null}}}function Qn(e){e={...e};let t=e.initialResponse;delete e.initialResponse;let u=e.funnelExecutionPolicy&&structuredClone(e.funnelExecutionPolicy);if(!e.customerRun&&(typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken)))throw new f("INVALID_TOKEN","Run credential required");if(e.customerRun&&(!e.session||!e.scope||!e.funnelId||!e.funnelCommandStorage||e.serverKey))throw new f("INVALID_REQUEST","Customer recovery requires its scoped session and durable journal");if(e.serverKey&&(typeof window<"u"||!Re.test(e.serverKey)))throw new f("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new f("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let r=W({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),o=hn(e.funnelId,e.scope??e.configuration?.scope),m=e.session?.subscribeIdentity(b),d=null,c=e.funnelCommandStorage??(!e.customerRun&&typeof window<"u"&&window.isSecureContext?rn(e):void 0),a=c&&vn(c),i=bn({journal:a,state:o,call:T,processIdentity:e.process}),g=0,y=new Map;function v(){g++,y.clear(),t=void 0}async function h(l){let I=l.operation==="resume"?i.pending?.operation==="resume"?null:i.pending:l;if(u&&l.operation==="resume"&&!I&&l.requestId!==e.customerRun?.startRequestId)throw new f("EXECUTION_POLICY_REFUSED","The original command is required to verify execution permission before resuming");if(I?.operation==="submit"&&I.input.type==="paywall_confirm"){let N=o.view?.paywall;wn(u,N?.quote?.operationId===I.input.operationId?N.quote:void 0)}if(e.process)return e.process.request(l);let P=o.generation;o.assertCurrent(P);let E=performance.now()+(e.timeoutMs??35e3),R=o.customerToken??("customerToken"in l?l.customerToken:void 0);if(e.session){let N=o.signal,k,B=()=>{},xn=new Promise((Yn,Fe)=>{B=()=>Fe(N.reason),N.addEventListener("abort",B,{once:!0}),k=setTimeout(()=>Fe(new f("TIMEOUT","The request timed out")),Math.max(1,E-performance.now()))});try{R=await Promise.race([Promise.resolve().then(()=>(o.assertCurrent(P),e.session.access())),xn])}finally{clearTimeout(k),N.removeEventListener("abort",B)}}o.assertCurrent(P);let F={...l,...R?{customerToken:R}:{}},w=l.operation==="page_experiments"?fe.parse(F):G.parse(F);if(e.customerRun){if(e.session?.snapshot()?.customerId!==e.customerRun.customerId||!R)throw new f("IDENTITY_CHANGED","Original recovery Customer changed");let N={...w};return"customerToken"in N&&delete N.customerToken,r.requestWithCredential("funnels",{operation:"run_command",runId:e.customerRun.runId,funnelId:e.funnelId,command:N},R,{timeoutMs:Math.max(1,E-performance.now())})}return r.requestWithCredential("funnels",w,e.runToken,{headers:e.serverKey&&!R?{[un]:e.serverKey}:void 0,timeoutMs:Math.max(1,E-performance.now())})}function b(){v(),m?.(),o.reset(),i.reset(),d=null,r.dispose()}async function T(l,I){let P=t;t=void 0;let E=o.generation,R=()=>o.assertCurrent(E);a&&await i.ready,R();let F=o.view,w=gn(e,P!==void 0&&l.operation==="get"&&!l.data&&!l.purchase&&!l.settlementRequestId?P:await h(l));if(l.operation==="review"&&!w.review)throw new f("INVALID_RESPONSE","Historical projection is missing");if(e.customerRun&&w.run.id!==e.customerRun.runId)throw new f("INVALID_RESPONSE","Original recovery Run changed");if(l.operation==="get"&&l.purchase&&w.purchase&&(w.purchase.receiptId!==l.purchase.receiptId||(w.purchase.operation?.operationId??w.purchase.quote?.operationId)!==l.purchase.operationId))throw new f("INVALID_RESPONSE","The requested original purchase changed");if(R(),w.runToken&&w.runToken!==e.runToken)throw new f("INVALID_RESPONSE","Run credential changed");let N=l.operation==="get"?l.settlementRequestId:"requestId"in l&&l.operation!=="start"?l.requestId:void 0;if(N&&w.settlement?.requestId!==N)throw new f("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");i.assertBinding(w),o.assertRun(w.run),o.bindScope(w.scope);let k=await i.observe(l,w,E,I);return(!o.view||w.run.revision>=o.view.revision)&&(I===void 0||I>=o.readSequence)&&(await e.onAcceptedResponse?.(w),R()),!w.run.stopped&&["running","waiting"].includes(w.run.status)&&l.operation==="get"&&l.settlementRequestId||(R(),["running","waiting"].includes(w.run.status)||i.stop(),o.publish(l,w,F,I,k)),w}function O(l){let I=o.generation;v();let P=l(),E=()=>{o.generation===I&&v()};return P.then(E,E),P}let s=l=>O(()=>i.submit(l)),p=null,x=new WeakMap;function C(l){let I=x.get(l);if(I)return I;let P=_(l);return x.set(l,P),P}let S=!1;async function _(l){let I=await l;if(I.run.instruction?.type!=="evaluate_segment")return I;if(p)return p;S=!0;let P=o.generation,E=(async()=>{for(let R=0;R<32&&I.run.instruction?.type==="evaluate_segment";R++){if(i.pending||i.closeRequested)return I;let F=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:N}=await Se(e.configuration,F,{predict:!1});if(P!==o.generation)throw new f("IDENTITY_CHANGED","Run identity changed during segment calculation");if(i.pending||i.closeRequested)return I;if(o.view&&(o.view.revision!==F.revision||o.view.visit!==F.visit||o.view.nodeId!==F.nodeId))return T({operation:"get"});let k=!0;Se(e.configuration,F).then(({prediction:B})=>{k&&P===o.generation&&!i.closeRequested&&o.view?.id===F.id&&!o.view.stopped&&o.view.nodeId===F.nodeId&&o.view.visit===F.visit&&o.view.revision===F.revision&&(d=B)}).catch(()=>{});try{I=await s({operation:"commit_segment",requestId:Xe(F.id,F.visit,`segment:${F.revision}`),nodeId:F.nodeId,visit:F.visit,revision:F.revision,...N})}finally{k=!1,d=null}}}return I})();p=E;try{return await E}finally{p===E&&(p=null)}}let D={get configuration(){return S?e.configuration:void 0},get configurationReady(){return!0},get view(){let l=o.currentView;return l?structuredClone(l):null},get viewAgeMs(){return o.viewAgeMs},get pendingCommand(){let l=i.closing??i.pending;return l?structuredClone(q(l)):null},get pendingCommands(){return[i.pending,i.closing].filter(l=>l!==null).map(l=>structuredClone(q(l)))},get pendingPurchase(){return i.purchase?structuredClone(i.purchase):null},get hasDurableJournal(){return a!==void 0},get prediction(){let l=o.view;return d&&l&&!l.stopped&&["running","waiting"].includes(l.status)&&l.id===d.runId&&l.nodeId===d.from.nodeId&&l.visit===d.from.visit&&l.revision===d.from.revision&&!i.closeRequested?structuredClone(d):null},settle:(...l)=>O(()=>i.settle(...l)),get webViewUrl(){return"bundled"},resolvePaywall(l){return nn(e,l)},async pageExperiments(l,I=[]){let P=o.generation;o.assertCurrent(P);let E=o.view?.id;if(!E)throw new f("INVALID_REQUEST","Read the Run before its page experiments");let R=ln.parse(await h(fe.parse({operation:"page_experiments",release:l,usedReceiptIds:I})));if(o.assertCurrent(P),R.runId!==E||R.scope.projectId!==o.scope?.projectId||R.scope.environment!==o.scope?.environment)throw new f("SCOPE_MISMATCH","Page experiment Run changed");return R},review(l){return T({operation:"review",...l?{receiptId:l}:{}},o.nextRead())},async get(l,I){let P=o.generation;l=l&&structuredClone(l),I=I&&{...I},a&&await i.ready,o.assertCurrent(P),I??=i.purchase&&{receiptId:i.purchase.receiptId,operationId:i.purchase.operationId};let E=JSON.stringify([o.generation,g,l??null,I??null]),R=y.get(E);if(R)return R.then(k=>structuredClone(k));let F=o.nextRead(),w=C(T({operation:"get",...l?{data:l}:{},...I?{purchase:I}:{}},F));y.set(E,w);let N=()=>{y.get(E)===w&&y.delete(E)};return w.then(N,N),w.then(k=>structuredClone(k))},resume(l=o.view?.pendingRequest?.requestId){return l?i.closeRequested?D.settle(l):i.pending?.requestId===l?C(s(i.pending)):C(s({operation:"resume",requestId:l})):Promise.reject(new f("INVALID_REQUEST","No interrupted command is available"))},submit(l){return C(s(l))},async retry(){if(i.closeFlight)return i.closeFlight;if(i.closing)return s(i.closing);if(i.closeRequested&&i.pending)return D.settle(i.pending.requestId);if(i.inFlight)return C(i.inFlight);if(!i.pending)throw new f("INVALID_REQUEST","No command is pending");let l=i.pending;if(l.operation==="submit"&&l.input.type==="paywall_quote"){let I=o.generation;if(await D.settle(l.requestId),o.assertCurrent(I),!i.pending)return D.get();if(i.pending!==l||i.closeRequested)throw new f("COMMAND_PENDING","The original quote is being recovered")}return C(s(l))},identify(l){let I=o.customerToken?void 0:t;v(),o.identify(l),t=I,d=null,r.reset()},get identitySignal(){return o.signal},subscribe:o.subscribe,reset:b};return D}function uo(e,t){return Qn({...e,runToken:"",initialResponse:t})}export{on as a,Fn as b,pe as c,Pn as d,an as e,Tn as f,At as g,Tt as h,_t as i,fe as j,ln as k,X as l,kn as m,Kt as n,lr as o,cr as p,gn as q,xe as r,Ir as s,Jn as t,In as u,H as v,rn as w,Sn as x,Or as y,te as z,Re as A,Lr as B,Mr as C,wn as D,Qn as E,uo as F};
@@ -0,0 +1 @@
1
+ import{B as p,C as u,D as d,E as f}from"./chunk-KP4QI4RX.js";import{v as y}from"./chunk-MWICFZUF.js";import{a as s}from"./chunk-TL67SYPH.js";function Q(e,t,r=new Set){let i={...t};return y(e.document.screen,n=>{if(n.hidden)return!1;if(n.type!=="quantity_picker"||r.has(n.id))return;let a=e.capabilities.quantities?.[n.id],o=a?.available?a.value:i[n.id]??n.defaultQuantity;if(a?.available&&(typeof o!="number"||!Number.isSafeInteger(o)||o<Math.max(n.minimumQuantity,a.minimum)||o>Math.min(n.maximumQuantity,a.maximum)||(o-n.minimumQuantity)%n.step!==0))throw new s("INVALID_RESPONSE","The current subscription quantity is outside this control's bounds");typeof o=="number"&&(i[n.id]=o)}),i}function V(e){let t=Object.create(null);for(let r of e.document.screen.actions){let i=r.properties.couponBinding,n=e.document.buttons[r.id];if(typeof i!="string"||n?.type!=="checkout")continue;let a=Object.hasOwn(e.capabilities.nodes,i)?e.capabilities.nodes[i]:void 0,{product:o}=n,b=o.type==="fixed"?[o.productVersionId]:o.allowedProductVersionIds,I=a?[a.base,...Object.values(a.byPlan??{})]:[],w=Object.fromEntries(I.flatMap(l=>l.planVersionId&&l.couponId&&l.text&&b.includes(l.planVersionId)?[[l.planVersionId,l]]:[]));t[r.id]={products:w,...o.type==="picker"?{picker:o.pickerId}:{}}}return Object.keys(t).length?{...e.capabilities,checkoutCoupons:t}:e.capabilities}function E(e,t){let r=structuredClone(e);for(let[i,n]of Object.entries(r.plans)){let a=t.plans[i];!a||a.versionId!==n.versionId||(a.amountMinor!==void 0&&(n.amountMinor=a.amountMinor),a.interval!==void 0&&(n.interval=a.interval),a.intervalCount!==void 0&&(n.intervalCount=a.intervalCount),a.prepaid!==void 0&&(n.prepaid=structuredClone(a.prepaid)))}return r}var h=class extends s{constructor(r="Plans were updated. Choose again.",i="\u5957\u9910\u5DF2\u66F4\u65B0\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9\u3002"){super("CONFLICT",r);this.zhMessage=i}zhMessage;customerMessage(r){return r?this.zhMessage:this.message}};function N(e,t){let r=i=>"document"in i?i.offering.id:i.content.offeringVersionId;return e.id===t.id&&r(e)===r(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function D(e,t,r){if(e.operationId!==t.operationId||t.currency!==void 0&&"currency"in e&&e.currency!==t.currency||t.membershipId!==void 0&&(t.membershipId===null?u(e):!u(e)||e.membershipId!==t.membershipId)||t.featureQuantities!==void 0&&(!u(e)||!c(e.featureQuantities,t.featureQuantities)))throw new s("INVALID_RESPONSE",r)}function c(e,t){return Object.keys(e??{}).length===Object.keys(t??{}).length&&Object.entries(t??{}).every(([r,i])=>e?.[r]===i)}function P(e,t,r){if(p(e)){if(!t.subscriptionChange||e.membershipId!==t.subscriptionChange.membershipId||e.timing!==t.subscriptionChange.timing||e.productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE",r);if(e.execution.provider==="merchant"){let n=e.execution.change,a=e.merchantTerms?.request;if(e.execution.membershipId!==e.membershipId||e.execution.timing!==e.timing||n.type!=="plan"||n.productVersionId!==e.productVersionId||!c(n.featureQuantities,e.featureQuantities)||a&&(a.action!=="subscription_change"||a.timing!==e.timing||a.change.type!=="plan"||a.change.productVersionId!==e.productVersionId||!c(a.change.featureQuantities,e.featureQuantities)))throw new s("INVALID_RESPONSE",r)}return}if(t.subscriptionChange)throw new s("INVALID_RESPONSE",r);let i=Object.fromEntries((e.lines[0]?.prepaid??[]).map(n=>[n.internal_feature_id,n.quantity]));if(t.featureQuantities&&(Object.keys(i).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([n,a])=>i[n]!==a)))throw new s("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new s("INVALID_RESPONSE",r)}function m(e,t){if(e.operationId===t.operationId){if(p(e))P(t,{productVersionId:e.productVersionId,currency:e.currency,subscriptionChange:{membershipId:e.membershipId,timing:e.timing},featureQuantities:e.featureQuantities??{}},"The original membership change selection changed");else if(p(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed")}}function C(e,t,r=!1){if(t&&u(t)&&t.quote&&!c(t.featureQuantities,t.quote.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");if(t&&u(t)&&t.quote&&m(t.quote,t.quote),!e||e.operationId!==t?.operationId)return t;if(e.quote&&t.quote&&m(e.quote,t.quote),u(e)&&u(t)&&!c(e.featureQuantities,t.featureQuantities))throw new s("INVALID_RESPONSE","The original membership change quantities changed");let i=e.merchantExecution,n=t.merchantExecution;if(i&&(!n||Date.parse(n.updatedAt)<Date.parse(i.updatedAt)))return e;if(u(e)!==u(t))throw new s("INVALID_RESPONSE","The commercial operation kind changed");if(d(e)&&!d(t))return e;let a=t.status===e.status&&i?.recordingStatus!=="accepted"&&n?.recordingStatus==="accepted";return!f(e)&&(f(t)||r&&!d(t)&&!a)?e:t}function R(e){return e.screen.actions.some(t=>t.properties.closeControl==="content"&&e.buttons[t.id]?.type==="close")}export{Q as a,V as b,E as c,h as d,N as e,D as f,P as g,m as h,C as i,R as j};
@@ -0,0 +1 @@
1
+ import{d as b}from"./chunk-3SXPCVIP.js";import{b as r}from"./chunk-GPJF3T43.js";var f=r.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),y=r.strictObject({type:r.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:r.boolean(),enum:r.array(r.string().max(255)).min(1).max(100).optional()}),g=y.extend({type:r.enum([...y.shape.type.options,"array"]),items:y.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),h=g.safeExtend({source:r.discriminatedUnion("type",[r.strictObject({type:r.literal("input")}),r.strictObject({type:r.literal("node")}),r.strictObject({type:r.enum(["parameter","attribute"]),key:f})])}),O=r.record(f,h),R=r.record(f,f).refine(e=>Object.keys(e).length<=20);function m(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>m(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&r.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function w(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&w(e.items,t.items)}function d(e,t){let n={};for(let[s,a]of Object.entries(e)){let i=a.source,l=i.type==="input"?t.answers:i.type==="node"?t.results??{}:i.type==="parameter"?t.parameters:t.attributes,c=i.type==="parameter"||i.type==="attribute"?i.key:s,u=Object.hasOwn(l,c),o=l[c];if(i.type==="attribute"&&c.includes(".")&&(!u||c.startsWith("merchandise."))){o=l,u=!0;for(let p of c.split(".")){if(!o||typeof o!="object"||!Object.hasOwn(o,p)||Array.isArray(o)&&(!/^(0|[1-9]\d*)$/.test(p)||Number(p)>=o.length)){u=!1;break}o=o[p]}}if(!(!u||o===void 0)){if(!m(a,o))throw new Error(`Invalid variable value: ${s}`);n[s]=o}}return n}function J(e,t){let n={};for(let[s,a]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,s))throw new Error(`Node output is missing: ${s}`);if(Object.hasOwn(n,a))throw new Error("Node outputs cannot overwrite one another");n[a]=t[s]}return n}function A(e,t,n){let s=new Set(Object.values(t.writes??{}));for(let[a,i]of Object.entries(n))if(!s.has(a)||e[a]?.source.type!=="node"||!m(e[a],i))throw new Error(`Invalid node variable write: ${a}`);if(s.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var k=b,V=["parameters","answers","results","variables"];function j(e){return V.some(t=>e===t||e.startsWith(t+"."))}function z(e){let t={};for(let[s,a]of Object.entries(d(e.declarations,e))){let i=s.split(".");if(i.some(u=>["__proto__","constructor","prototype"].includes(u)))throw new Error("Reserved result path");let l=t;for(let u of i.slice(0,-1)){Object.hasOwn(l,u)||(l[u]={});let o=l[u];if(!o||typeof o!="object"||Array.isArray(o))throw new Error("Ambiguous result path");l=o}let c=i.at(-1);if(c===void 0)throw new Error("Empty result path");l[c]=a}return{...Object.fromEntries(Object.entries(e.attributes).filter(([s])=>!j(s))),variables:t}}var N=r.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);export{f as a,g as b,h as c,R as d,m as e,w as f,d as g,J as h,A as i,k as j,j as k,z as l,N as m};