@tinkerlandai/longplay-sdk 0.10.57 → 0.10.59

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 (103) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +1 -0
  3. package/README.zh-CN.md +1 -0
  4. package/dist/check-response-K56UEZ6E.js +1 -0
  5. package/dist/{chunk-ANJPFGFN.js → chunk-2RFI2DEV.js} +1 -1
  6. package/dist/{chunk-EACC667P.js → chunk-32AEJKJW.js} +1 -1
  7. package/dist/{chunk-554BTJ3I.js → chunk-45PGU2HW.js} +1 -1
  8. package/dist/{chunk-M4P6TGBU.js → chunk-4OODZM64.js} +1 -1
  9. package/dist/{chunk-CJUODAOF.js → chunk-4SI4SQ3C.js} +1 -1
  10. package/dist/{chunk-OV46DXRX.js → chunk-5LNX7MHO.js} +1 -1
  11. package/dist/chunk-5MRSFLQA.js +1 -0
  12. package/dist/{chunk-6K6N5XLO.js → chunk-6426YKPK.js} +1 -1
  13. package/dist/{chunk-2NIMTHN7.js → chunk-66W37FEV.js} +1 -1
  14. package/dist/{chunk-2OBAMFGZ.js → chunk-725CAWOK.js} +1 -1
  15. package/dist/{chunk-PVMGYRGE.js → chunk-77O2O552.js} +1 -1
  16. package/dist/{chunk-IN32NWRI.js → chunk-7STWC4L4.js} +1 -1
  17. package/dist/{chunk-6HKQILBV.js → chunk-BJW4AXFL.js} +1 -1
  18. package/dist/{chunk-XHZH3E4G.js → chunk-C3HZCZVJ.js} +1 -1
  19. package/dist/{chunk-J4RM5GQP.js → chunk-DBYRJ4QV.js} +1 -1
  20. package/dist/{chunk-GGZG56GR.js → chunk-EB7MIZ4T.js} +1 -1
  21. package/dist/{chunk-YMRWDMIL.js → chunk-EE6QNOCL.js} +1 -1
  22. package/dist/{chunk-BX2MSRA4.js → chunk-EKUDMQXT.js} +1 -1
  23. package/dist/{chunk-FQJWNS4U.js → chunk-FBNEQ2K5.js} +1 -1
  24. package/dist/{chunk-NNJVMJUG.js → chunk-FQMZY5VP.js} +1 -1
  25. package/dist/{chunk-L64BS65O.js → chunk-HUYKZH3H.js} +1 -1
  26. package/dist/{chunk-OQ2E3JLZ.js → chunk-IMFPRZUY.js} +1 -1
  27. package/dist/chunk-J3RW4GMO.js +1 -0
  28. package/dist/{chunk-LENTXDGK.js → chunk-J5K4PNII.js} +1 -1
  29. package/dist/chunk-J7VGTAJ7.js +1 -0
  30. package/dist/{chunk-JJIP6BZL.js → chunk-JBSJ3JU2.js} +1 -1
  31. package/dist/{chunk-LOBZ45T3.js → chunk-JEDRJAJ5.js} +1 -1
  32. package/dist/{chunk-RJT764B2.js → chunk-KTWKDR5L.js} +1 -1
  33. package/dist/{chunk-725DCRIN.js → chunk-LUDTXNMH.js} +1 -1
  34. package/dist/{chunk-YA2XHXUS.js → chunk-MB2U2GWJ.js} +1 -1
  35. package/dist/{chunk-UJVNIA5Q.js → chunk-MZ6NEOOQ.js} +1 -1
  36. package/dist/{chunk-JXWZS4UM.js → chunk-NAFHQVSX.js} +1 -1
  37. package/dist/{chunk-ADTZEBQF.js → chunk-NDNHTG5B.js} +1 -1
  38. package/dist/{chunk-3LDOPWRV.js → chunk-O2V4MTM6.js} +1 -1
  39. package/dist/{chunk-R4BYUK7S.js → chunk-PGLBFTRK.js} +1 -1
  40. package/dist/{chunk-36VNAOG6.js → chunk-PJHTN5NJ.js} +1 -1
  41. package/dist/chunk-PTNMDAND.js +1 -0
  42. package/dist/{chunk-C4NXQMSO.js → chunk-R4CYPCBI.js} +1 -1
  43. package/dist/{chunk-OZK47BUU.js → chunk-RIEWU4MN.js} +1 -1
  44. package/dist/{chunk-NL7AXMUA.js → chunk-S5RM3VO6.js} +1 -1
  45. package/dist/{chunk-WE55LJEN.js → chunk-TK3WOD2O.js} +1 -1
  46. package/dist/chunk-U2NEVISJ.js +1 -0
  47. package/dist/{chunk-CAE4KIZN.js → chunk-VNYUL3PV.js} +1 -1
  48. package/dist/{chunk-HMJTABQ5.js → chunk-VPT5MFDG.js} +2 -2
  49. package/dist/{chunk-QGKROSRD.js → chunk-VXDVMAS6.js} +1 -1
  50. package/dist/{chunk-LOKH33KR.js → chunk-WUPNZGE2.js} +1 -1
  51. package/dist/{chunk-BKBWGPNR.js → chunk-XCFAKO23.js} +1 -1
  52. package/dist/chunk-XY2X6YJF.js +1 -0
  53. package/dist/{chunk-DHFJN4JM.js → chunk-YB3PQ75M.js} +2 -2
  54. package/dist/{chunk-73UFNVEP.js → chunk-ZCJEXNJD.js} +1 -1
  55. package/dist/{chunk-RRZZUIFM.js → chunk-ZRGL2CAP.js} +1 -1
  56. package/dist/content-5OMLKBPP.js +1 -0
  57. package/dist/funnel-host-purchase-53LYWG4V.js +1 -0
  58. package/dist/funnel-host-recovery-paywall-FC3XQU2U.js +1 -0
  59. package/dist/funnel-paywall-copies-U3JIYQJ5.js +1 -0
  60. package/dist/funnel-paywall-prerender-YCATKDAY.js +1 -0
  61. package/dist/funnel-route-prediction-XYWNKGQZ.js +1 -0
  62. package/dist/funnel-route-source-4ZVBFNYV.js +1 -0
  63. package/dist/funnel-runtime-host-LQ6X5B6R.js +1 -0
  64. package/dist/index.d.ts +795 -1
  65. package/dist/index.js +1 -1
  66. package/dist/merchant-bridge-contracts-IZ7ARRRO.js +1 -0
  67. package/dist/openrouter.js +1 -1
  68. package/dist/operation-contracts-6RQ33K66.js +1 -0
  69. package/dist/page.js +1 -1
  70. package/dist/paywall-KQIBPACY.js +1 -0
  71. package/dist/paywall-content-NQXU3O4D.js +1 -0
  72. package/dist/paywall-session-W42F6DIF.js +1 -0
  73. package/dist/popup.js +1 -1
  74. package/dist/react-native.js +1 -1
  75. package/dist/screen-renderer-2ZDV2WYD.js +1 -0
  76. package/dist/server.js +1 -1
  77. package/dist/{visual-dom-MH3JDJHJ.js → visual-dom-5LUN4AHO.js} +1 -1
  78. package/dist/visual.js +1 -1
  79. package/package.json +1 -1
  80. package/dist/check-response-MJHH5FWT.js +0 -1
  81. package/dist/chunk-5HYA7TBE.js +0 -1
  82. package/dist/chunk-5UVYLTM7.js +0 -1
  83. package/dist/chunk-AJVVXHP7.js +0 -1
  84. package/dist/chunk-NMBKBC7X.js +0 -1
  85. package/dist/chunk-UWMXBSYO.js +0 -1
  86. package/dist/content-3MNGXC7L.js +0 -1
  87. package/dist/funnel-host-purchase-H6BMFIXK.js +0 -1
  88. package/dist/funnel-host-recovery-paywall-UQC5FAL4.js +0 -1
  89. package/dist/funnel-paywall-prerender-XBEUY6CG.js +0 -1
  90. package/dist/funnel-route-prediction-ICGW4DPX.js +0 -1
  91. package/dist/funnel-route-source-64LTJZXN.js +0 -1
  92. package/dist/funnel-runtime-host-HEBLLPFC.js +0 -1
  93. package/dist/merchant-bridge-contracts-DEDEIYNU.js +0 -1
  94. package/dist/operation-contracts-RHJJI5NO.js +0 -1
  95. package/dist/paywall-HZVO7BDI.js +0 -1
  96. package/dist/paywall-content-KBHI22JD.js +0 -1
  97. package/dist/paywall-session-TS7G7OEM.js +0 -1
  98. package/dist/screen-renderer-XBWES3XN.js +0 -1
  99. /package/dist/{chunk-DLRCJF6U.js → chunk-CILM5XMH.js} +0 -0
  100. /package/dist/{chunk-VJIONC4S.js → chunk-OJM6ORHE.js} +0 -0
  101. /package/dist/{chunk-5YBTU4KS.js → chunk-PZTWDJHN.js} +0 -0
  102. /package/dist/{chunk-HMJTABQ5.js.LEGAL.txt → chunk-VPT5MFDG.js.LEGAL.txt} +0 -0
  103. /package/dist/{chunk-DHFJN4JM.js.LEGAL.txt → chunk-YB3PQ75M.js.LEGAL.txt} +0 -0
@@ -1 +1 @@
1
- import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-6K6N5XLO.js";import{a as tt}from"./chunk-725DCRIN.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-EACC667P.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-BX2MSRA4.js";import{a as fe,b as Ze}from"./chunk-5HYA7TBE.js";import{a as le}from"./chunk-L64BS65O.js";import{e as de}from"./chunk-NNJVMJUG.js";import{a as D}from"./chunk-WE55LJEN.js";import{h as ie}from"./chunk-OZK47BUU.js";import{b as et}from"./chunk-3VUPVXAV.js";import{b as Qe}from"./chunk-NMBKBC7X.js";import{b as e}from"./chunk-5YBTU4KS.js";import{c as Fe,f as Pe}from"./chunk-HMJTABQ5.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-64LTJZXN.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-64LTJZXN.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
1
+ import{A as me,E as rt,b as qe,c as $e,d as Se,h as He,i as Ke,j as Ye,n as We,q as Xe,z as nt}from"./chunk-6426YKPK.js";import{a as tt}from"./chunk-LUDTXNMH.js";import{c as Ne,d as Te,e as _e,f as Le,g as De,i as Ue,m as ke,n as M,o as Ge,q as be,r as _,s as je,t as ze,u as Be,v as Je}from"./chunk-32AEJKJW.js";import{K as U,e as Ve,q as ve,r as Me}from"./chunk-EKUDMQXT.js";import{a as fe,b as Ze}from"./chunk-J7VGTAJ7.js";import{a as le}from"./chunk-HUYKZH3H.js";import{e as de}from"./chunk-FQMZY5VP.js";import{a as D}from"./chunk-TK3WOD2O.js";import{h as ie}from"./chunk-RIEWU4MN.js";import{b as et}from"./chunk-3VUPVXAV.js";import{a as Qe}from"./chunk-5MRSFLQA.js";import{b as e}from"./chunk-PZTWDJHN.js";import{c as Fe,f as Pe}from"./chunk-VPT5MFDG.js";var j=e.literal(Ve),ht=e.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),xe=e.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),ot=e.discriminatedUnion("type",[e.strictObject({type:e.literal("guest"),guestToken:xe}),e.strictObject({type:e.literal("customer"),customer:ve,customerData:Me.optional()})]),Ee=e.strictObject({id:e.uuid(),runId:e.uuid(),customerId:e.uuid(),requestId:e.uuid(),acceptedAt:e.iso.datetime({offset:!0})}),yt=e.strictObject({participantId:e.uuid(),startedAs:e.enum(["guest","identified"]),binding:Ee.omit({runId:!0,requestId:!0}).nullable()}),wt=e.union([qe,e.strictObject({type:e.literal("authentication_required"),reason:e.enum(["customer_required","customer_experiment_required"]),nodeId:e.string().min(1).max(64),visit:e.number().int().nonnegative()})]),It=$e.omit({authenticated:!0}).extend({identity:yt,instruction:wt.nullable()}),vt=e.discriminatedUnion("operation",[U.options[2].omit({customerToken:!0}),U.options[3].omit({customerToken:!0}),U.options[4].omit({customerToken:!0}),U.options[5].omit({customerToken:!0}),U.options[6].omit({customerToken:!0}),U.options[7].omit({customerToken:!0})]),pe={contract:j,customerToken:e.string().regex(le)},it={contract:j,requestId:e.uuid(),runToken:ht,externalUserId:ve.options[1].shape.value},at=e.discriminatedUnion("operation",[e.strictObject({contract:j,operation:e.literal("describe")}),e.strictObject({contract:j,operation:e.literal("start"),source:ot,funnelId:U.options[0].shape.funnelId,requestId:e.uuid(),locale:U.options[0].shape.locale,parameters:U.options[0].shape.parameters}),He.omit({operation:!0}).extend({contract:j,operation:e.literal("entry_start"),source:ot}),e.strictObject({...it,operation:e.literal("bind_customer"),guestToken:xe,claimRequestId:e.uuid(),expectedBindingId:e.null()}),e.strictObject({...it,operation:e.literal("binding_status"),guestToken:xe.optional()}),U.options[1].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("get"),settlementBindingId:e.uuid().nullable().optional()}),U.options[8].omit({operation:!0,customerToken:!0}).extend({...pe,operation:e.literal("review")}),Ye.omit({customerToken:!0}).extend(pe),e.strictObject({...pe,operation:e.literal("command"),identity:e.strictObject({bindingId:e.uuid().nullable()}),command:vt})]),bt=Se.omit({run:!0}).extend({contract:j,run:It,settlement:Se.shape.settlement.unwrap().extend({accepted:e.boolean().nullable().optional()}).optional()}),Dt=Ke.extend({contract:j}),Ut=e.discriminatedUnion("operation",[at.options[1].omit({contract:!0,source:!0,requestId:!0}),at.options[2].omit({contract:!0,source:!0,requestId:!0})]),Vt=bt.extend({binding:Ee,outcome:e.enum(["bound","already_bound"]),replayed:e.boolean()}),Mt=e.discriminatedUnion("state",[e.strictObject({contract:j,scope:ie,state:e.literal("not_accepted")}),e.strictObject({contract:j,scope:ie,state:e.literal("conflict")}),e.strictObject({contract:j,scope:ie,state:e.literal("bound"),binding:Ee})]),kt=e.strictObject({contract:j,scope:ie,keyId:e.uuid(),operations:e.array(e.string()).max(20)});var st=e.string().regex(/^[a-f0-9]{64}$/),St=Ne.omit({variations:!0,active:!0}).extend({changeId:st,variations:e.array(e.strictObject({urlRedirect:e.string().max(2048)})).min(2).max(20)}),ut=e.strictObject({environmentId:e.uuid(),trackExposures:e.boolean(),generation:st,experiments:e.array(St).max(100),savedGroups:Te}),xt=e.strictObject({eventUuid:e.uuid(),timestamp:e.iso.datetime({offset:!0}).optional(),deviceId:e.string().min(1).max(128),sessionId:e.string().min(1).max(128).optional(),url:e.url().max(2048),pageTitle:e.string().max(512).optional(),experimentKey:e.string().min(1).max(255),variationKey:e.string().min(1).max(64)}),Bt=e.strictObject({events:e.array(xt).min(1).max(20)}),Jt=e.strictObject({inserted:e.number().int().nonnegative(),duplicates:e.number().int().nonnegative(),skipped:e.number().int().nonnegative(),rejected:e.array(e.strictObject({index:e.number().int().nonnegative(),reason:e.string()}))});function Wt(r){let a=null,g=null,O=0,v=0,C=new Set,l=null,w=null,m=new Set,b=()=>{for(let s of m)try{s()}catch{}},d={attributes:de.parse(r.attributes??{}),onFeatureUsage:r.onFeatureUsage?(s,I)=>{!C.has(s)&&a&&(!("analyticsConfig"in a)||a.analyticsConfig.featureUsageEnabled)&&r.onFeatureUsage(s,structuredClone(I),structuredClone(d.attributes),a.generation)}:void 0,onExperimentViewed:r.onExperimentViewed?(s,I)=>a&&(!("analyticsConfig"in a)||a.analyticsConfig.experimentViewsEnabled)&&r.onExperimentViewed(structuredClone(s),structuredClone(I),structuredClone(d.attributes),a.generation):void 0,stickyBucketAssignmentDocs:structuredClone(r.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:r.saveStickyBucketAssignmentDoc?s=>r.saveStickyBucketAssignmentDoc(structuredClone(s)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function h(s,I=new Set){return C.has(s)?!l||!l.features[s]||["unknownFeature","cyclicPrerequisite"].includes(l.features[s].source):I.has(s)?!1:(I.add(s),(a?.features[s]?.rules??[]).some(F=>[...F.parentConditions??[],...(F.tracks??[]).flatMap(P=>P.experiment.parentConditions??[])].some(P=>h(P.id,I))))}let x=s=>{if(r.assertUsable?.(a?.generation),!a)throw new Error("Initialize the Feature client before evaluation");if(a.expiresAt&&Date.parse(a.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return l?.expiresAt&&Date.parse(l.expiresAt)<=Date.now()&&(l=null,d.features=a.features),C.has(s)?!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now()?S():structuredClone(l.features[s]??S()):r.evaluateRemote&&(d.attributes?.merchandise||d.attributes?.merchandiseId)&&!l||h(s)?S():structuredClone(Pe(s,d))};async function V(){if(!a||!C.size&&!d.attributes?.merchandise&&!d.attributes?.merchandiseId)return;if(!r.evaluateRemote){if(C.size)throw new Error("Remote Feature evaluation requires a server loader");return}let s=v;if(w?.revision===s)return w.loading;let I=O,F=a,P=[...C],E=(async()=>{let y=Ue.parse(await r.evaluateRemote({attributes:structuredClone(d.attributes),features:P}));if(!(I!==O||s!==v||F!==a)){if(r.assertUsable?.(F.generation),y.generation!==F.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(P.some(T=>!Object.hasOwn(y.features,T))||Object.keys(y.features).some(T=>!C.has(T)))throw new Error("Invalid remote Feature results");if(d.attributes?.merchandise||d.attributes?.merchandiseId){if(!y.merchandiseContext)throw new Error("Server did not resolve merchandise context");d.attributes=de.parse({...d.attributes,...y.merchandiseContext})}l=structuredClone(y),d.features={...F.features,...Object.fromEntries(Object.entries(l.features).map(([T,J])=>[T,{defaultValue:J.value}]))},b()}})();w={revision:s,loading:E};try{await E}finally{w?.loading===E&&(w=null)}}function L(){V().catch(s=>{try{r.onError?.(s)}catch{}})}async function k(){if(g)return g;let s=O,I=(async()=>{let F=await r.load(),P="remoteFeatures"in F?Le.parse(F):null,E=P??_e.parse(F);if(E.scope.projectId!==r.scope.projectId||E.scope.environment!==r.scope.environment)throw new Error("Feature payload scope changed");if(s!==O)throw new Error("Feature client was reset");if(r.assertUsable&&a?.generation===E.generation){let{evaluatedAt:T,expiresAt:J,...ae}=a,{evaluatedAt:Z,expiresAt:ge,...z}=E;if(_(ae)!==_(z))throw new Error("Immutable Feature generation changed content");return a.evaluatedAt=E.evaluatedAt,a.expiresAt=E.expiresAt,b(),(!l||l.expiresAt&&Date.parse(l.expiresAt)<=Date.now())&&L(),structuredClone(a)}let y=new Set(P?.remoteFeatures??[]);if([...y].some(T=>Object.hasOwn(E.features,T)))throw new Error("Remote Feature definitions must not be delivered locally");return a&&"analyticsConfig"in a&&"analyticsConfig"in E&&!a.analyticsConfig.experimentViewsEnabled&&P?.analyticsConfig.experimentViewsEnabled&&d.trackedExperiments?.clear(),a=structuredClone(E),C=y,l=null,w=null,v++,d.features=a.features,d.savedGroups=Fe(a.savedGroups),d.trackedFeatureUsage={},b(),L(),structuredClone(a)})();g=I;try{return await I}finally{g===I&&(g=null)}}return{init:k,refresh:k,refreshRemote:V,get generation(){return a?.generation??null},get expiresAt(){return a?.expiresAt??null},subscribe(s){return m.add(s),()=>{m.delete(s)}},setAttributes(s){let I=de.parse(s);(d.attributes?.merchandise||d.attributes?.merchandiseId||s.merchandise||s.merchandiseId)&&d.trackedExperiments?.clear(),d.attributes=I,v++,l=null,w=null,d.features=a?.features??{},d.trackedFeatureUsage={},b(),L()},evalFeature:x,isOn(s){return x(s).on},isOff(s){return x(s).off},getFeatureValue(s,I){let F=x(s).value;return structuredClone(F===null?I:F)},reset(){O++,v++,g=null,w=null,a=null,l=null,C.clear(),d.features={},d.savedGroups={},d.stickyBucketAssignmentDocs={},d.attributes={},d.trackedFeatureUsage={},d.trackedExperiments?.clear(),b()}}}var Et=e.record(e.string().regex(/^[a-f0-9]{64}$/),e.strictObject({at:e.number(),text:e.string()})),Q=2*1048576,Ct=100;function Rt(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function ct(r,a){let g=a===void 0?Rt():a,O=new Map,v=0,C=!1,l=!1,w,m;async function b(S){if(!g)return null;let h;try{let x=await Promise.race([Promise.resolve().then(()=>g.getItem(S)),new Promise(V=>{h=setTimeout(()=>V(null),Ct)})]);return typeof x=="string"&&x.length<=Q&&new TextEncoder().encode(x).byteLength<=Q?x:null}catch{return null}finally{clearTimeout(h)}}function d(){if(m)return m;let S=(async()=>{try{let h=await b(`${r}:artifacts`);if(h)return Et.parse(JSON.parse(h))}catch{}return{}})();return m=S,S.finally(()=>{m===S&&(m=void 0)}),S}return{async readManifest(){return b(r)},writeManifest(S){!g||S.length>Q||new TextEncoder().encode(S).byteLength>Q||(w=S,!l&&(l=!0,Promise.resolve().then(async()=>{try{for(;w!==void 0;){let h=w;try{await g.setItem(r,h)}catch{}w===h&&(w=void 0)}}finally{l=!1}})))},async readArtifact(S){let h=(await d())[S],x=Date.now();return h&&x>=h.at&&x-h.at<=M.retentionMs?h.text:void 0},writeArtifact(S,h){if(!g||h.length>Q)return;let x=O.get(S);if(x?.text===h||!x&&O.size>=128)return;let V=new TextEncoder().encode(h).byteLength;v-(x?.byteLength??0)+V>Q||(O.set(S,{text:h,byteLength:V}),v+=V-(x?.byteLength??0),!C&&(C=!0,Promise.resolve().then(async()=>{try{for(;O.size;){let L=new Map(O);try{let k={...await d()},s=Date.now();for(let[E,y]of L)k[E]={at:s,text:y.text};let I={},F=2,P=0;for(let[E,y]of Object.entries(k).sort(([,T],[,J])=>J.at-T.at)){if(y.at>s||s-y.at>M.retentionMs)continue;let T=new TextEncoder().encode(JSON.stringify({[E]:y})).byteLength;F+T>Q||P>=128||(I[E]=y,F+=T,P++)}await g.setItem(`${r}:artifacts`,JSON.stringify(I))}catch{}finally{for(let[k,s]of L)O.get(k)===s&&(O.delete(k),v-=s.byteLength)}}}finally{C=!1}})))}}}var u=(r,a)=>new D(r,a),B=()=>performance.now(),lt=r=>{typeof r=="object"&&"unref"in r&&r.unref()};function pn(r){let a=Ge.parse(r.scope),g=new fe(r.origin??Qe);if(g.username||g.password||g.search||g.hash||g.pathname!=="/"||g.protocol!=="https:"&&!(g.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(g.hostname)))throw u("INVALID_URL","Configuration requires a trusted HTTPS origin");let O=new Set([g.origin,...(r.assetOrigins??[]).map(t=>{let n=new fe(t);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/")throw u("INVALID_URL","Invalid configuration asset origin");return n.origin})]),v=r.fetch??globalThis.fetch.bind(globalThis),C=`/api/v1/configuration/${a.environmentId}`,l=`indiana:configuration:1:${g.origin}:${_(a)}`,w=ct(l,r.storage),m,b=0,d=0,S=!1,h=!1,x=0,V=0,L,k,s,I,F=0,P=new Set,E=new Set,y=new Map,T=new Map,J=0,ae=!1;function Z(){for(let t of P)try{t()}catch{}}function ge(t){try{r.onError?.(t)}catch{}}let z=()=>!h&&!S&&!!m&&B()<b&&Date.now()<d;function re(){if(!z())throw u("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function Ce(t,n,i){if(!y.has(t)){for(;y.size&&(y.size>=128||J+i>M.maxCacheBytes);){let o=y.entries().next().value;J-=o[1].byteLength,y.delete(o[0])}y.set(t,{text:n,byteLength:i}),J+=i}}function he(t,n,i){return et(t,n,{signal:i,error:o=>u("INVALID_RESPONSE",o==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function ye(t){let n=new fe(t,g);if(!O.has(n.origin)||n.username||n.password||n.hash||n.search)throw u("INVALID_URL","Configuration artifact origin is not trusted");return n.href}async function we(t,n,i=!1){let o=await v(ye(t),{method:"GET",credentials:"omit",redirect:"error",cache:i?"default":"no-cache",signal:n,headers:{}});if(o.status===429){let f=o.headers.get("retry-after")??"";F=/^\d+$/.test(f)?Number(f)*1e3:Math.max(0,Date.parse(f)-Date.now())||15e3}if(!o.ok&&o.status!==304)throw u(`CONFIGURATION_HTTP_${o.status}`,"Configuration synchronization failed");return o}function ft(t,n,i){let o=Date.parse(t.headers.get("x-indiana-config-validated-at")??""),f=Date.parse(t.headers.get("x-indiana-config-valid-until")??""),p=Date.parse(t.headers.get("date")??""),c=t.headers.get("age"),R=c!==null&&/^\d+(\.\d+)?$/.test(c)?Number(c)*1e3:NaN;if(![o,f,p,R].every(Number.isFinite)||f<=o||f-o>M.maxControlAgeMs||o>p+1e3)throw u("INVALID_RESPONSE","Configuration freshness evidence is invalid");let A=Math.min(f-o,i.maxControlAgeSeconds*1e3,M.maxControlAgeMs)-Math.max(R,p-o,0)-(B()-n);if(A<=0)throw u("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return B()+A}function se(){if(clearTimeout(s),clearTimeout(I),h||!P.size||(z()&&(I=setTimeout(()=>{z()?se():Z()},Math.max(1,b-B())),lt(I)),typeof document<"u"&&document.visibilityState==="hidden"))return;let t=V?Math.min(15e3,1e3*2**Math.min(V-1,4)):Math.min(15e3,(m?.policy.refreshIntervalSeconds??15)*1e3);s=setTimeout(()=>{X().catch(ge)},Math.max(F,t*(.8+Math.random()*.2))),lt(s)}async function X(){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(L)return L;let t=x,n=new AbortController;k=n;let i=(async()=>{if(!ae){ae=!0;try{let ce=await w.readManifest();if(ce&&!m){let $=be.parse(JSON.parse(ce));_($.scope)===_(a)&&(m=$)}}catch{}}n.signal.throwIfAborted();let c=m,R=B(),N=await we(C,n.signal);N.status===304&&(!c||!N.headers.has("x-indiana-config-validated-at")||!N.headers.has("x-indiana-config-valid-until")||!N.headers.has("age"))&&(N=await we(C,n.signal));let A=N.status===304?c:be.parse(JSON.parse(await he(N,M.maxManifestBytes,n.signal))),{generation:G,...ne}=A,q=N.headers.get("etag");if(_(A.scope)!==_(a)||ze(ne)!==G||q!==`"${G}"`&&q!==`W/"${G}"`)throw u("INVALID_RESPONSE","Configuration scope or content identity changed");if(c&&(A.revision<c.revision||A.revision===c.revision&&A.generation!==c.generation))throw u("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[ce,$]of Object.entries(c?.funnels??{})){let W=A.funnels[ce];if(W&&(W.controlRevision<$.controlRevision||W.evaluationRevision<$.evaluationRevision||W.controlRevision===$.controlRevision&&W.state!==$.state||W.evaluationRevision===$.evaluationRevision&&W.evaluationMode!==$.evaluationMode))throw u("INVALID_RESPONSE","Funnel control revision changed identity")}let Y=ft(N,R,A.policy);if(n.signal.throwIfAborted(),t!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return m=A,b=Y,d=Date.now()+Math.max(0,Y-B()),S=!1,V=0,F=0,w.writeManifest(_(A)),Z(),structuredClone(A)})(),o=setTimeout(()=>n.abort(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs),f=new Promise((c,R)=>n.signal.addEventListener("abort",()=>R(n.signal.reason),{once:!0})),p=Promise.race([i,f]).catch(c=>{throw V++,(c instanceof e.ZodError||c instanceof SyntaxError||c instanceof D&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(c.code))&&(b=0,S=!0,Z()),c}).finally(()=>{clearTimeout(o),L===p&&(L=void 0),se()});return L=p,p}async function ue(t){let n=t.sha256,i=ne=>tt(ne,t);ye(t.url);let o=y.get(n);if(o){if(o.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return y.delete(n),y.set(n,o),o.text}let f=T.get(n);if(f){if(f.byteLength!==t.byteLength)throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return f.promise}let p=new AbortController;E.add(p);let c=x,R=(async()=>{try{let Y=await w.readArtifact(n);if(Y&&i(Y)){if(p.signal.throwIfAborted(),h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,Y,t.byteLength),Y}}catch{}p.signal.throwIfAborted();let ne=await we(t.url,p.signal,!0),q=await he(ne,t.byteLength,p.signal);if(!i(q))throw u("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(h||c!==x)throw u("CONFIGURATION_DISPOSED","Configuration scope changed");return Ce(n,q,t.byteLength),w.writeArtifact(n,q),q})(),N=setTimeout(()=>p.abort(u("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),M.initializationMs),A=new Promise((ne,q)=>p.signal.addEventListener("abort",()=>q(p.signal.reason),{once:!0})),G=Promise.race([R,A]).finally(()=>{clearTimeout(N),E.delete(p),T.delete(n)});return T.set(n,{promise:G,byteLength:t.byteLength}),G}async function ee(){return z()||await X(),re(),m}async function K(t){let n,i=new Promise((o,f)=>{n=setTimeout(()=>f(u("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),M.initializationMs)});try{return await Promise.race([t(),i])}finally{clearTimeout(n)}}function H(t,n){if(re(),m?.generation!==t.generation)throw u("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(n&&m.funnels[n]?.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Re(t){let n=t.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let o=De.parse(JSON.parse(await ue(i)));if(_(o.scope)!==_({projectId:a.projectId,environment:a.environment})||o.generation!==i.generation||o.remoteFeatures.some(f=>Object.hasOwn(o.features,f)))throw u("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return H(t),{...o,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,b-B())).toISOString()}}async function Oe(t,n){let i=await ee(),o=i.funnels[t];n&&(!o||o.evaluationMode==="local"&&!o.versions[n])&&(L&&await L,i=await X()),H(i,t);let f=i.funnels[t];if(f.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let p=n??f.currentVersionId,c=f.versions[p];if(!c)throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(i.artifacts[c.artifact].formatVersion!==3)throw u("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[R,N]=await Promise.all([ue(i.artifacts[c.artifact]).then(A=>Je(JSON.parse(A))),f.evaluationMode==="local"?Re(i):void 0]);if(N&&_(Be(R,N))!==_(c.dependencies))throw u("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return H(i,t),{document:R,growth:N,versionId:p,control:structuredClone(f),manifest:structuredClone(i)}}async function Ie(t,n){try{return await Oe(t,n)}catch(i){if(!(i instanceof D)||!(i.code==="CONFIGURATION_CHANGED"||i.code==="CONFIGURATION_HTTP_404"&&z()))throw i;let o=m?.generation;if(L&&await L,await X(),i.code!=="CONFIGURATION_CHANGED"&&m?.generation===o)throw i;return Oe(t,n)}}let oe=new Map;async function mt(t,n){let{FUNNEL_ROUTE_LIMITS:i,funnelRouteSchema:o}=await import("./funnel-route-source-4ZVBFNYV.js"),f=new AbortController;E.add(f);let p=setTimeout(()=>f.abort(u("CONFIGURATION_UNAVAILABLE","Funnel route read timed out")),M.initializationMs);try{let c=await v(ye(`${C}/funnels/${t}/versions/${n}/route`),{method:"GET",credentials:"omit",redirect:"error",cache:"no-cache",signal:f.signal,headers:{}});if(c.status===404)throw u("ROUTE_UNAVAILABLE","This Funnel Version publishes no route");if(!c.ok)throw u(`CONFIGURATION_HTTP_${c.status}`,"Funnel route read failed");let R=await he(c,i.maxBytes,f.signal),N=je(R),A=c.headers.get("etag");if(A!==`"${N}"`&&A!==`W/"${N}"`)throw u("INVALID_RESPONSE","Funnel route identity changed");let G=o.safeParse(JSON.parse(R));if(!G.success||G.data.funnelId!==t||G.data.versionId!==n)throw u("INVALID_RESPONSE","Funnel route does not describe this Version");return G.data}finally{clearTimeout(p),E.delete(f)}}async function pt(t){let n=await ee();H(n,t);let i=n.funnels[t],o=i.currentVersionId,f;if(i.evaluationMode==="local"){let{projectFunnelRoute:p}=await import("./funnel-route-source-4ZVBFNYV.js"),c=await Ie(t,o),R=Object.entries(c.manifest.paywalls??{});f=p({funnelId:t,versionId:o,document:c.document,experiments:c.growth?.experiments??{},paywallOf:N=>R.find(([,A])=>Object.hasOwn(A.versions,N))?.[0]})}else{let p=`${t}:${o}`,c=oe.get(p);if(!c||B()-c.readAt>=M.maxControlAgeMs){let R={promise:mt(t,o),readAt:B()};oe.set(p,R),R.promise.catch(()=>{oe.get(p)===R&&oe.delete(p)}),c=R}f=await c.promise}return H(n,t),{route:structuredClone(f),control:structuredClone(i),generation:n.generation}}function te(){if(z()||Z(),typeof document<"u"&&document.visibilityState==="hidden"){se();return}X().catch(ge)}function gt(t){if(h)throw u("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return P.add(t),P.size===1&&(typeof window<"u"&&(window.addEventListener("online",te),window.addEventListener("focus",te),document.addEventListener("visibilitychange",te)),se()),()=>{P.delete(t),P.size||(clearTimeout(s),clearTimeout(I),Ae())}}function Ae(){typeof window<"u"&&(window.removeEventListener("online",te),window.removeEventListener("focus",te),document.removeEventListener("visibilitychange",te))}return{scope:Object.freeze({...a}),refresh:X,subscribe:gt,assertFresh:re,assertFeatures(t){re();let n=m.gb.features;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(t!==void 0&&m.artifacts[n].generation!==t)throw u("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return z()},get snapshot(){return m?structuredClone(m):null},get remainingMs(){return z()?Math.max(0,b-B()):0},async features(){return K(async()=>Re(await ee()))},pageExperiments:()=>K(async()=>{let t=await ee(),n=t.gb.pageExperiments;if(!n)throw u("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let i=t.artifacts[n];if(i.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let o=ut.parse(JSON.parse(await ue(i)));if(o.environmentId!==a.environmentId||o.generation!==i.generation)throw u("INVALID_RESPONSE","Page experiment scope or generation changed");return H(t),o}),funnel:(t,n)=>K(()=>Ie(t,n)),funnelControl:t=>K(async()=>{let n=await ee();return H(n,t),structuredClone(n.funnels[t])}),funnelRoute:t=>K(()=>pt(t)),paywall:(t,n)=>K(async()=>{let i=await ee(),o=i.paywalls?.[t];if(!o||!n&&o.state!=="published")throw u("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let f=n??o.currentVersionId,p=o.versions[f],c=p&&i.artifacts[p.artifact];if(!c||c.kind!=="paywall"||c.formatVersion!==1)throw u("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let R=ke.parse(JSON.parse(await ue(c)));return H(i),{document:R,versionId:f,version:p.version,control:structuredClone(o),manifest:structuredClone(i)}}),async localFunnel(t,n){let i=await K(()=>Ie(t,n));if(!i.growth)throw u("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:o,remoteFeatures:f,...p}=i.growth;return We({scope:{projectId:a.projectId,environment:a.environment},funnelId:t,versionId:i.versionId,evaluationMode:"local",evaluationRevision:i.control.evaluationRevision,document:i.document,payload:p})},assertFunnel(t,n,i){re();let o=m.funnels[t];if(!o||o.state!=="active")throw u("FUNNEL_STOPPED","Funnel is paused or unavailable");if(o.evaluationMode!=="local")throw u("EVALUATION_MODE","This Funnel now executes at Longplay");if(n!==void 0&&o.controlRevision!==n)throw u("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(i!==void 0&&!o.versions[i])throw u("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!h){h=!0,x++,b=0,k?.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(s),clearTimeout(I),Ae(),Z(),P.clear();for(let t of E)t.abort(u("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));y.clear(),oe.clear(),J=0}}}}function dt(r){let a=le.test(r.apiKey);if(typeof window<"u"&&!a)throw new D("SERVER_ONLY","Funnel starts are issued by your backend");if(!a&&!me.test(r.apiKey))throw new D("INVALID_TOKEN","A customer credential or server API key is required");return{async start(g){let O=U.safeParse({...g,operation:"start"});if(!O.success||O.data.operation!=="start"||(a?O.data.customer!==void 0:O.data.customer===void 0))throw new D("INVALID_REQUEST","Invalid current Funnel start");let v=O.data,C=Ze({...r,timeoutMs:r.timeoutMs??35e3});try{r.session||C.identify(r.apiKey);let l=Xe(r,await C.request("funnels",v));if(!l.runToken)throw new D("INVALID_RESPONSE","Funnel start credentials are missing");if(l.run.source.id!==v.funnelId||l.run.locale!==(v.locale??"en")||!nt(l.run.parameters,v.parameters??{})||(v.customer?!l.customerId||v.customer.type==="id"&&l.customerId!==v.customer.value:l.customerId!==void 0))throw new D("INVALID_RESPONSE","Funnel start contract changed");return{...l,runToken:l.runToken}}finally{C.dispose()}}}}async function An(r){r={...r};let a=r.configuration;if(!a)throw new D("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let g={projectId:a.scope.projectId,environment:a.scope.environment};if(r.scope&&_(g)!==_(r.scope))throw new D("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await a.funnelControl(r.funnelId)).evaluationMode!=="local")throw new D("EVALUATION_MODE","This Funnel uses Remote evaluation");let v=me.test(r.credential);if(v?!r.customerId:r.customerId!==void 0)throw new D("INVALID_REQUEST","Only Server-Key starts name their Customer");let C=dt({...r,scope:g,apiKey:r.credential}),l=(w,m)=>{let b=rt({...r,scope:g,runToken:w,initialResponse:m,...v?{serverKey:r.credential}:{}});return v||b.identify(r.credential),b};return{async start(w){let m=await C.start({...w,funnelId:r.funnelId,...v?{customer:{type:"id",value:r.customerId}}:{}}),b=l(m.runToken,m),d=await b.get();return{...m,...d,controller:b}},async restore(w){let m=l(w),b=await m.get();if(b.run.source.id!==r.funnelId)throw m.reset(),new D("SCOPE_MISMATCH","Run belongs to another Funnel");return{...b,runToken:w,controller:m}}}}export{at as a,bt as b,Dt as c,Ut as d,Vt as e,Mt as f,kt as g,Wt as h,pn as i,dt as j,An as k};
@@ -1 +1 @@
1
- import{a,b as o,c as i}from"./chunk-CAE4KIZN.js";import{a as p}from"./chunk-WE55LJEN.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
1
+ import{a,b as o,c as i}from"./chunk-VNYUL3PV.js";import{a as p}from"./chunk-TK3WOD2O.js";function c(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new p("INVALID_REQUEST","Customer requests use the verified session identity")}function I(e){return{async previewUpdate(t){t=a(t),c(t);let r=await o(e,"previewUpdate");return i(e,r,t)},async update(t){t=a(t),c(t);let r=await o(e,"update");return i(e,r,t)},async readSubscriptionUpdate(t){t=a(t),c(t);let r=await o(e,"readSubscriptionUpdate");return i(e,r,t)},async restoreNativePurchase(t){t=a(t),c(t);let r=await o(e,"restoreNativePurchase");return i(e,r,t)},async previewAttach(t){t=a(t),c(t);let r=await o(e,"previewAttach");return i(e,r,t)},async attach(t){t=a(t),c(t);let r=await o(e,"attach");return i(e,r,t)},async readSubscriptionOperation(t){t=a(t),c(t);let r=await o(e,"readSubscriptionOperation");return i(e,r,t)}}}export{c as a,I as b};
@@ -1 +1 @@
1
- import{a as E,b as M,c as j,d as O,e as T}from"./chunk-ANJPFGFN.js";import{a as u}from"./chunk-WE55LJEN.js";import{j as w}from"./chunk-OZK47BUU.js";import{b as t}from"./chunk-5YBTU4KS.js";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Z(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Z as d};
1
+ import{a as E,b as M,c as j,d as O,e as T}from"./chunk-2RFI2DEV.js";import{a as u}from"./chunk-TK3WOD2O.js";import{j as w}from"./chunk-RIEWU4MN.js";import{b as t}from"./chunk-PZTWDJHN.js";var _=E,V=t.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),C=t.strictObject(Object.fromEntries(_.map(i=>[i,t.number().int().nonnegative().max(1e9)]))),L=M,D=j,q=t.strictObject({modelId:L,source:t.enum(["models.dev","custom"]),fetchedAt:t.iso.datetime(),rates:O,contextTier:t.number().int().nonnegative(),markupPercent:D}),U=t.strictObject({pricing:q,tokens:C,quantity:w,digest:t.string().regex(/^[a-f0-9]{64}$/)}),z=i=>{let[s,o=""]=i.split(".");return BigInt(s)*10n**12n+BigInt(o.padEnd(12,"0"))};function $(i){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new u("AI_PRICE_UNAVAILABLE","A published token price is missing");let s=String(i),o=s.includes("e")?i.toFixed(12).replace(/0+$/,"").replace(/\.$/,""):s;if(Number(o)!==i||!V.safeParse(o).success)throw new u("AI_PRICE_UNAVAILABLE","Published price exceeds the supported precision");return o}var R=t.strictObject({input:t.number().nonnegative(),output:t.number().nonnegative(),cache_read:t.number().nonnegative().optional(),cache_write:t.number().nonnegative().optional(),reasoning:t.number().nonnegative().optional(),input_audio:t.number().nonnegative().optional(),output_audio:t.number().nonnegative().optional()}),F=R.extend({context_over_200k:t.unknown().optional(),tiers:t.array(R.extend({tier:t.strictObject({type:t.literal("context"),size:t.number().int().nonnegative()})})).max(20).refine(i=>new Set(i.map(s=>s.tier.size)).size===i.length).optional()});async function N(i,s,o){let d=new TextEncoder().encode(JSON.stringify({pricing:i,tokens:s,quantity:o}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",d))].map(m=>m.toString(16).padStart(2,"0")).join("")}function B(i,s){let o=0n;for(let c of _){if(!s[c])continue;let f=i.rates[c];if(f===void 0)throw new u("AI_PRICE_UNAVAILABLE",`No published price for ${c}; report exclusive token pools`);o+=z(f)*BigInt(s[c])}let[d,m="0"]=String(i.markupPercent).split("e"),r=(d.split(".")[1]?.length??0)-Number(m),e=10n**BigInt(Math.max(r,0)),n=BigInt(d.replace(".",""))*10n**BigInt(Math.max(-r,0)),g=100n*e+n,l=100n*e*1000000n,a=(o*g+l-1n)/l;return w.parse(`${a/1000000n}.${(a%1000000n).toString().padStart(6,"0")}`)}function K(i={}){if(typeof window<"u")throw new u("SERVER_ONLY","AI token pricing belongs on your backend");let s=T.parse({defaultMarkup:i.defaultMarkup??0,providerMarkups:i.providerMarkups??{},modelMarkups:i.modelMarkups??{},customModels:i.customModels??{}}),o=null,d=0;async function m(){if(!o||Date.now()>=d){d=Date.now()+15*6e4;let r=(async()=>{let e=await(i.fetch??fetch)("https://models.dev/api.json",{signal:AbortSignal.timeout(3e4)});if(!e.ok)throw new u("AI_PRICE_UNAVAILABLE","Models.dev pricing is unavailable");return{data:t.record(t.string(),t.object({models:t.record(t.string(),t.unknown())})).parse(await e.json()),fetchedAt:new Date().toISOString()}})().catch(e=>{throw o===r&&(o=null),e});o=r}return o}return{refreshPrices(){o=null,d=0},async quoteTokens(r){let e=L.parse(r.modelId),n=C.parse(r.tokens),[g,...l]=e.split("/"),a=s.customModels[e],c,f,p,y=0;if(a?.input!==void 0&&a.output!==void 0&&_.every(A=>n[A]===0||a[A]!==void 0))c={...a,input:a.input,output:a.output},f="custom",p=new Date().toISOString();else{let A=await m(),x=A.data[g]?.models[l.join("/")];if(!x)throw new u("AI_PRICE_UNAVAILABLE","Unknown model; configure a complete custom price");let{cost:I}=t.object({cost:F}).parse(x),P=n.input+n.cache_read+n.cache_write+n.input_audio;if(I.tiers===void 0&&I.context_over_200k!==void 0&&P>2e5)throw new u("AI_PRICE_UNAVAILABLE","A current context tier is required for this model");let b=I.tiers?.filter(k=>P>k.tier.size).sort((k,Q)=>Q.tier.size-k.tier.size)[0],v=b??I;b&&(y=b.tier.size),c=Object.fromEntries(_.filter(k=>v[k]!==void 0).map(k=>[k,$(v[k])])),c={...c,...a},f=a?"custom":"models.dev",p=A.fetchedAt}let h=q.parse({modelId:e,source:f,fetchedAt:p,rates:c,contextTier:y,markupPercent:s.modelMarkups[e]??s.providerMarkups[g]??s.defaultMarkup}),S=B(h,n);return U.parse({pricing:h,tokens:n,quantity:S,digest:await N(h,n,S)})},async trackTokens(r,e){let n=U.parse(e.quote);if(n.quantity!==B(n.pricing,n.tokens)||n.digest!==await N(n.pricing,n.tokens,n.quantity))throw new u("INVALID_REQUEST","AI quote changed after pricing");let g=e.properties??{},l=e.providerCostUsd===void 0?void 0:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,18})?$/).parse(e.providerCostUsd),a=e.generationId===void 0?void 0:t.string().min(1).max(120).parse(e.generationId),c=8+ +(l!==void 0)+ +(a!==void 0);if(Object.keys(g).some(p=>p.startsWith("ai_")))throw new u("INVALID_REQUEST","AI tracking reserves ai_ event properties");if(Object.keys(g).length>16-c)throw new u("INVALID_REQUEST","AI tracking properties exceed the available event budget");let f={operation:"consume",internal_feature_id:e.internal_feature_id,quantity:n.quantity,idempotencyKey:e.idempotencyKey,properties:{...g,...l!==void 0?{ai_provider_cost_usd:l}:{},...a!==void 0?{ai_generation_id:a}:{},ai_model:n.pricing.modelId,ai_source:n.pricing.source,ai_price_at:n.pricing.fetchedAt,ai_quote_hash:n.digest,ai_markup:String(n.pricing.markupPercent),ai_tier:String(n.pricing.contextTier),ai_tokens:_.map(p=>n.tokens[p]).join(","),ai_rates:"v1:"+_.map(p=>n.pricing.rates[p]===void 0?"-":z(n.pricing.rates[p]).toString(36)).join(",")},...e.entityId?{entityId:e.entityId}:{}};return r.mutateBalance({customerId:e.customerId,command:f})}}}async function Z(i,s,o={}){let{config:d,model_markups:m}=await i.readAiPricing(s);return K({defaultMarkup:d.default_markup??0,providerMarkups:Object.fromEntries(Object.entries(d.provider_markups??{}).map(([r,e])=>[r,e.markup])),modelMarkups:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.markup!==void 0).map(([r,e])=>[r,e.markup])),customModels:Object.fromEntries(Object.entries(m??{}).filter(([,r])=>r.input_cost!==void 0||r.output_cost!==void 0).map(([r,e])=>[r,{...e.input_cost!==void 0?{input:String(e.input_cost)}:{},...e.output_cost!==void 0?{output:String(e.output_cost)}:{}}])),...o})}export{q as a,U as b,K as c,Z as d};
@@ -1 +1 @@
1
- import{a as m,m as f,p as y}from"./chunk-EACC667P.js";import{g as d}from"./chunk-RRZZUIFM.js";import{e as l,f as u,j as p}from"./chunk-RJT764B2.js";import{b as e}from"./chunk-5YBTU4KS.js";var h={funnelId:e.uuid().optional(),funnelVersionId:e.uuid().optional()};var w=e.strictObject({runId:e.uuid(),bindingId:e.uuid(),receiptId:e.uuid()});var q=e.strictObject({processContext:w.optional(),...h,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("paywall"),paywallId:e.uuid()}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),customerId:e.uuid().optional(),commerce:l,locale:e.string().min(1).max(35),requirement:u.optional()}),c=e.strictObject({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),document:m.omit({requirement:!0,offeringId:!0}),offering:e.strictObject({id:e.uuid()}),content:e.strictObject({environmentId:e.uuid(),offeringVersionId:e.uuid(),artifact:y.refine(n=>n.kind==="paywall"&&n.formatVersion===1)}).optional(),capabilities:d,check:p.nullable()}).superRefine((n,r)=>{let t=new Set(n.document.products.items.map(o=>o.productVersionId));(n.document.offeringVersionId!==n.offering.id||Object.values(n.capabilities.plans).some(o=>!t.has(o.versionId)))&&r.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),M=e.strictObject(c.shape).omit({document:!0,offering:!0}).extend({content:c.shape.content.unwrap()});function _(n,r){let t=f.parse(r);if(t.offeringVersionId!==n.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let o=structuredClone(n.capabilities);for(let[g,i]of Object.entries(t.catalog)){let a=o.plans[g],s=i.channels.stripe?.prices.find(I=>I.currency===a?.currency);a&&s&&Object.assign(a,{amountMinor:s.amountMinor,interval:i.interval,intervalCount:i.intervalCount,...i.prepaid?.length?{prepaid:i.prepaid}:{}})}return c.parse({...n,capabilities:o,document:{schemaVersion:3,kind:t.kind,name:t.name,presentation:t.presentation,products:t.products,offeringVersionId:t.offeringVersionId,screen:t.screen,buttons:t.buttons},offering:{id:t.offeringVersionId}})}export{h as a,w as b,q as c,c as d,M as e,_ as f};
1
+ import{a as m,m as f,p as y}from"./chunk-32AEJKJW.js";import{g as d}from"./chunk-ZRGL2CAP.js";import{e as l,f as u,j as p}from"./chunk-KTWKDR5L.js";import{b as e}from"./chunk-PZTWDJHN.js";var h={funnelId:e.uuid().optional(),funnelVersionId:e.uuid().optional()};var w=e.strictObject({runId:e.uuid(),bindingId:e.uuid(),receiptId:e.uuid()});var q=e.strictObject({processContext:w.optional(),...h,selector:e.discriminatedUnion("type",[e.strictObject({type:e.literal("paywall"),paywallId:e.uuid()}),e.strictObject({type:e.literal("version"),versionId:e.uuid()})]),customerId:e.uuid().optional(),commerce:l,locale:e.string().min(1).max(35),requirement:u.optional()}),c=e.strictObject({id:e.uuid(),paywallId:e.uuid(),version:e.number().int().positive(),document:m.omit({requirement:!0,offeringId:!0}),offering:e.strictObject({id:e.uuid()}),content:e.strictObject({environmentId:e.uuid(),offeringVersionId:e.uuid(),artifact:y.refine(n=>n.kind==="paywall"&&n.formatVersion===1)}).optional(),capabilities:d,check:p.nullable()}).superRefine((n,r)=>{let t=new Set(n.document.products.items.map(o=>o.productVersionId));(n.document.offeringVersionId!==n.offering.id||Object.values(n.capabilities.plans).some(o=>!t.has(o.versionId)))&&r.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),M=e.strictObject(c.shape).omit({document:!0,offering:!0}).extend({content:c.shape.content.unwrap()});function _(n,r){let t=f.parse(r);if(t.offeringVersionId!==n.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let o=structuredClone(n.capabilities);for(let[g,i]of Object.entries(t.catalog)){let a=o.plans[g],s=i.channels.stripe?.prices.find(I=>I.currency===a?.currency);a&&s&&Object.assign(a,{amountMinor:s.amountMinor,interval:i.interval,intervalCount:i.intervalCount,...i.prepaid?.length?{prepaid:i.prepaid}:{}})}return c.parse({...n,capabilities:o,document:{schemaVersion:3,kind:t.kind,name:t.name,presentation:t.presentation,products:t.products,offeringVersionId:t.offeringVersionId,screen:t.screen,buttons:t.buttons},offering:{id:t.offeringVersionId}})}export{h as a,w as b,q as c,c as d,M as e,_ as f};
@@ -1 +1 @@
1
- import{m as o}from"./chunk-RJT764B2.js";import{a as i}from"./chunk-WE55LJEN.js";function m(t,e,n,r){if(!o(t,e)||n!==void 0&&e.observation&&e.observation.subject.customerId!==n||r!==void 0&&e.observation!==void 0&&(e.observation.subject.scope.projectId!==r.projectId||e.observation.subject.scope.environment!==r.environment))throw new i("INVALID_RESPONSE","The access requirement or Customer changed");return e}function d(t,e,n){if(t.requirement){if(!e)throw new i("INVALID_RESPONSE","The requested access check is missing");m(t.requirement,e,t.customerId,n)}}export{m as a,d as b};
1
+ import{m as o}from"./chunk-KTWKDR5L.js";import{a as i}from"./chunk-TK3WOD2O.js";function m(t,e,n,r){if(!o(t,e)||n!==void 0&&e.observation&&e.observation.subject.customerId!==n||r!==void 0&&e.observation!==void 0&&(e.observation.subject.scope.projectId!==r.projectId||e.observation.subject.scope.environment!==r.environment))throw new i("INVALID_RESPONSE","The access requirement or Customer changed");return e}function d(t,e,n){if(t.requirement){if(!e)throw new i("INVALID_RESPONSE","The requested access check is missing");m(t.requirement,e,t.customerId,n)}}export{m as a,d as b};
@@ -1 +1 @@
1
- import{d as b}from"./chunk-NNJVMJUG.js";import{b as r}from"./chunk-5YBTU4KS.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};
1
+ import{d as b}from"./chunk-FQMZY5VP.js";import{b as r}from"./chunk-PZTWDJHN.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};
@@ -1 +1 @@
1
- import{O as x,a as w,b as f,c as T,d as E,e as j,h as b,i as y,m as G,n as Q,o as $,p as D,q as k,s as g,t as S}from"./chunk-NL7AXMUA.js";import{a as ee}from"./chunk-VILB5M4X.js";import{a as H,b as _,c as Z,d as W,q as J}from"./chunk-RRZZUIFM.js";import{a as u,b as K,c as V,d as Y}from"./chunk-RJT764B2.js";import{e as X,f as R,g as z}from"./chunk-NNJVMJUG.js";import{b as t}from"./chunk-5YBTU4KS.js";var te={"zh-Hans":{merchandise:"减 {discount}(单次使用)",once:"首期减 {discount}",repeating:"前 {months} 个月每月减 {discount}",forever:"每期减 {discount}"},"zh-Hant":{merchandise:"減 {discount}(單次使用)",once:"首期減 {discount}",repeating:"前 {months} 個月每月減 {discount}",forever:"每期減 {discount}"},en:{merchandise:"{discount} off · one use",once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{merchandise:"{discount} 割引(1回のみ)",once:"初回のお支払いが {discount} 割引",repeating:"最初の {months} か月間、毎月 {discount} 割引",forever:"毎回のお支払いが {discount} 割引"},ko:{merchandise:"{discount} 할인 · 1회 사용",once:"첫 결제 {discount} 할인",repeating:"첫 {months}개월 동안 매월 {discount} 할인",forever:"매 결제 {discount} 할인"},es:{merchandise:"{discount} de descuento · un uso",once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{merchandise:"{discount} de réduction · une utilisation",once:"{discount} de réduction sur le premier paiement",repeating:"{discount} de réduction par mois pendant les {months} premiers mois",forever:"{discount} de réduction sur chaque paiement",repeatingOne:"{discount} de réduction pendant le premier mois"},de:{merchandise:"{discount} Rabatt · einmalig",once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat für die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{merchandise:"{discount} de desconto · um uso",once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por mês nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro mês"},it:{merchandise:"{discount} di sconto · un utilizzo",once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{merchandise:"Скидка {discount} · одно использование",once:"Скидка {discount} на первый платёж",repeating:"Скидка {discount} каждый месяц в течение первых {months} мес.",repeatingOne:"Скидка {discount} в первый месяц",forever:"Скидка {discount} на каждый платёж"},vi:{merchandise:"Giảm {discount} · dùng một lần",once:"Giảm {discount} cho lần thanh toán đầu tiên",repeating:"Giảm {discount} mỗi tháng trong {months} tháng đầu",forever:"Giảm {discount} cho mỗi lần thanh toán"},th:{merchandise:"ลด {discount} · ใช้ได้ครั้งเดียว",once:"ลด {discount} สำหรับการชำระเงินครั้งแรก",repeating:"ลด {discount} ต่อเดือนในช่วง {months} เดือนแรก",forever:"ลด {discount} สำหรับการชำระเงินทุกครั้ง"},id:{merchandise:"Diskon {discount} · sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"خصم {discount} · استخدام واحد",once:"خصم {discount} على الدفعة الأولى",repeating:"خصم {discount} شهريًا لمدة {period}",forever:"خصم {discount} على كل دفعة"}};function N(e){let i=J(e)??"en",n=i.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(c=>["TW","HK","MO"].includes(c))?"zh-Hant":"zh-Hans":n[0]??"en",o=te[r];return o?{locale:i,copy:o}:{locale:"en",copy:te.en}}function je(e,i,n="zh-CN"){let r=K(i);return V(e,i,N(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function De(e,i="zh-CN"){let n=N(i).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):je(e.amountOffCents,e.currency,n)}var ie={zh:"前 {months} 个月内开出的账单减 {discount}","zh-Hant":"前 {months} 個月內開出的帳單減 {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"最初の {months} か月以内の請求が {discount} 割引",ko:"첫 {months}개월 내 청구서 {discount} 할인",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de réduction sur les factures émises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"Скидка {discount} на счета в течение первых {months} мес.",vi:"Giảm {discount} cho hóa đơn trong {months} tháng đầu",th:"ลด {discount} สำหรับใบแจ้งหนี้ในช่วง {months} เดือนแรก",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"خصم {discount} على الفواتير الصادرة خلال أول {period}"};function Lt(e,i="zh-CN",n="month"){let r=N(i),o=De(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",o);let c=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0]??"en",d=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,l=e.duration.type==="repeating"&&n!=="month"?ie[d]??ie.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],Ee=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return l.replace("{discount}",o).replace("{months}",c).replace("{period}",Ee)}var Qt=t.discriminatedUnion("action",[t.strictObject({action:t.literal("create"),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:t.enum(["introductory","promotional"])}),t.strictObject({action:t.literal("set_enabled"),id:t.uuid(),revision:t.number().int().nonnegative(),enabled:t.boolean()})]),$t=t.array(t.strictObject({id:t.uuid(),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).nullable(),storeOfferType:t.enum(["introductory","promotional"]),enabled:t.boolean(),revision:t.number().int().nonnegative()})).max(500),I=t.strictObject({offerKind:t.enum(["none","introductory","promotional"]),offerId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:t.number().int().min(0).max(1e8),trialDays:t.number().int().min(1).max(730).nullable()}).superRefine((e,i)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&i.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),Kt=t.record(t.uuid(),I).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var U=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:Y,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(o=>o.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var ke=t.enum(["active","inactive"]),Re=t.preprocess((e,i)=>{let n=0;function r(o,c){if(!(++n>1e4||c>20)){if(Array.isArray(o))o.forEach(a=>r(a,c+1));else if(o&&typeof o=="object")for(let[a,d]of Object.entries(o))["__proto__","constructor","prototype"].includes(a)&&i.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(d,c+1)}}return r(e,0),e},X),Ne=t.strictObject({id:t.string().trim().min(1).max(255),name:t.string().trim().min(1).max(255),status:ke,metadata:Re}),ei=Ne.extend({internal_id:t.uuid(),project_id:t.uuid(),environment_id:t.uuid(),created_at:t.iso.datetime({offset:!0}),updated_at:t.iso.datetime({offset:!0})}),ti=t.union([t.strictObject({id:t.string().trim().min(1).max(255)}),t.strictObject({internalId:t.uuid()})]),ii=t.enum(["customer","merchandise","context"]),ni=t.enum(["system","stored","request"]),ri=t.enum(["customer","merchandise","mixed"]),ne=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function q(e,i={},n=new Set){if(ee(e).some(ne))return!0;for(let r of z(e)){if(n.has(r))continue;n.add(r);let o=i[r];if(o?.type==="list"&&ne(o.attributeKey)||o?.type==="condition"&&q(o.condition,i,n))return!0}return!1}var di=t.enum(["draft","active","paused","archived"]),v=t.discriminatedUnion("type",[t.object({type:t.literal("percent"),percentOff:t.number().min(1).max(100).multipleOf(.01)}).strict(),t.object({type:t.literal("amount"),amountOffCents:t.number().int().min(1).max(1e8),currency:u}).strict()]),A=t.discriminatedUnion("type",[t.object({type:t.literal("once")}).strict(),t.object({type:t.literal("repeating"),months:t.number().int().min(1).max(36)}).strict(),t.object({type:t.literal("forever")}).strict()]),re=[t.object({type:t.literal("all")}).strict(),t.object({type:t.literal("plans"),planIds:t.array(t.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"套餐不能重复")}).strict()],Ue=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.discriminatedUnion("type",[t.strictObject({type:t.literal("all")}),t.strictObject({type:t.literal("selected"),merchandiseIds:t.array(t.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),t.strictObject({type:t.literal("condition"),condition:R})])})]),qe=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.strictObject({type:t.enum(["all","selected","condition"])})})]),Be=t.strictObject({firstPurchaseOnly:t.boolean(),condition:R}),pi=t.object({name:t.string().trim().min(1).max(80),description:t.string().max(500),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:Ue,eligibility:Be,selfClaimEnabled:t.boolean().default(!1),startsAt:t.iso.datetime().nullable(),endsAt:t.iso.datetime().nullable(),totalLimit:t.number().int().min(1).max(1e6).nullable(),perCustomerLimit:t.number().int().min(1).max(10),grantWindowHours:t.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"结束时间必须晚于开始时间",path:["endsAt"]}).refine(e=>!q(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),li=t.object({code:t.string().trim().transform(e=>e.toUpperCase()).pipe(t.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"优惠码只能用 3–32 位字母、数字、- 和 _,以字母或数字开头")),maxRedemptions:t.number().int().min(1).max(1e6).nullable(),expiresAt:t.iso.datetime().nullable(),firstPurchaseOnly:t.boolean(),minimumAmountCents:t.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:u.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var hi=t.object({id:t.uuid(),couponId:t.uuid(),status:t.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:t.iso.datetime(),expiresAt:t.iso.datetime(),coupon:t.object({name:t.string(),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:qe}).strict()}).strict(),fi=t.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var oe=t.strictObject({itemKey:t.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:Z,pricing:H.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{W(e.includedAmount,e.terms.units,e.quantity),_({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var C=t.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID 使用小写字母、数字和下划线,并以字母开头"),vi=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"免费套餐金额必须为 0,付费金额必须大于 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"附加币种不能重复默认币种;免费套餐不设置附加价格");var Le=t.registry(),{BillingInterval:ae}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Fe}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(t),{withSpecDefault:Ge}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:o})=>(e.add(n,{description:o,default:r}),n)}))(Le),{COMMON:se}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Qe}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:$e}=(e=>({COMMON_SET:new Set(e)}))(se),{hasNoDuplicateCurrencies:ce}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let o=r.toLowerCase();if(n.has(o))return!1;n.add(o)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:ue}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ke}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Ve}={Infinite:"inf"},{TierBehavior:He}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:me}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Ze}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:We}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ye}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Je}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:de}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(t),{VIOLATION_MESSAGES:Xe}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:pe}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:ze}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,pe),{InvoiceUsageEntrySchema:et}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(t),{AttachDiscountSchema:le}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(t),{CustomLineItemSchema:tt}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(t),{UnixMsTimestampSchema:it}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:nt}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(t),{ReissueInvoiceParamsSchema:wi}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(t),{InvoiceModeParamsSchema:h}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(t),{InvoiceTemplateSchema:Ti}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(t),{BasePriceSchema:rt}=((e,i,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(i).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(t,ae,Fe),{CURRENCY_CODES:ot}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(o=>!n.has(o)).sort()]}))(se,Qe,$e),{ApiPriceProcessorsSchema:he}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ke),{AllocatedBillingFieldSchema:at}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(t,Ze),{CreditDimensionNameSchema:st}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(o=>!o.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,We,Ye),{ApiCreditMatchSchema:fe}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Je),{findCreditTierViolations:ct}=(e=>({findCreditTierViolations:n=>{let r=[],o=(a,d)=>r.push({index:a,reason:d,message:e[d]}),c=0;for(let[a,d]of n.entries()){let l=a===n.length-1;if(d==="inf"){l||o(a,"non_final_infinity");continue}(!Number.isFinite(d)||d<=c)&&o(a,"not_increasing"),c=d,l&&o(a,"final_not_infinity")}return r}}))(Xe),{ApiCreditMultiplierSchema:ut}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(t,fe),{ProviderMarkupsSchema:mt}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,pe),{InvoiceFeatureQuantitySchema:be}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(o=>o.quantity!==void 0!=(o.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,me,et),{CreateInvoicePreviewSchema:Ei}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(t,nt),{SUPPORTED_SET:dt}=(e=>({SUPPORTED_SET:new Set(e)}))(ot),{ApiCreditDimensionBaseSchema:pt}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,fe),{refineGraduatedTiers:ye}=(e=>({refineGraduatedTiers:(n,r)=>{let o=e(n.tiers.map(c=>c.to));for(let{index:c,message:a}of o)r.addIssue({code:"custom",message:a,path:["tiers",c,"to"]})}}))(ct),{ApiFeatureMarkupsOverrideSchema:lt}=((e,i,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:i.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(t,mt,ze),{isValidCurrencyCode:ht}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(dt),{ApiCreditDimensionSchema:ft}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,pt,de,ye),{CurrencyCodeSchema:ge}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,ht),{AdditionalCurrencyTierSchema:bt}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(t,ge),{ApiCreditSchemaItemBaseSchema:Se}=((e,i,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(i,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,st,ft,ut),{ApiFlatCreditSchemaItemSchema:yt}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Se,t),{AdditionalCurrencyPriceSchema:gt}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,ge),{AdditionalCurrencyTierArraySchema:St}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,bt,ce,ue),{ApiGraduatedCreditSchemaItemSchema:_t}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(Se,t,de,ye),{AdditionalCurrencyPriceArraySchema:_e}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,gt,ce,ue),{ApiUsageTierWithCurrenciesSchema:xt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(o=>o.amount!==void 0||o.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(o=>({...o,amount:o.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Ve,St),{ApiCreditSchemaItemSchema:It}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,_t,yt),{BasePriceParamsSchema:vt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(rt,Ge,t,_e),{PlanItemPriceParamsSchema:At}=((e,i,n,r,o,c,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:i.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(o).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(c).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(t,_e,xt,He,ae,me,at),{ApiFeatureOverrideSchema:Ct}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(t,It,lt),{InvoiceBasePriceParamsSchema:xe}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(vt,he),{InvoiceItemPriceParamsSchema:Ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(At,he),{InvoiceLicenseQuantitySchema:Pt}=((e,i,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:i.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(t,xe,be),{InvoiceCustomizeItemSchema:Mt}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(t,Ot,Ct),{InvoiceCustomizeSchema:wt}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(t,xe,Mt),{InvoicePlanParamsSchema:Tt}=((e,i,n,r,o)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(o).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(t,wt,be,Pt,le),{CreateInvoiceParamsSchema:ji}=((e,i,n,r,o)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:o.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start → period_end against one price interval starting at period_start."}),period_end:o.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(t,Tt,tt,le,it);var m=t.iso.datetime({offset:!0}),Ae=t.url().refine(e=>new URL(e).protocol==="https:").nullable(),Zi=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:h.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:I.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(C,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Wi=t.strictObject({operationId:t.uuid()}),s=t.number().int().min(0).max(1e8),Et=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:s,seats:t.array(t.strictObject({key:C,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:s})).max(20),prepaid:t.array(oe).max(100).optional(),catalogAmountMinor:s,trial:G.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+_({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Ce=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),jt=t.strictObject({id:Ce,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Dt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),Oe=t.strictObject({invoiceMode:h.optional(),append:Dt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:Ce,terms:jt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:m}),B=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:v,duration:A,amountMinor:s,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:s})).min(1).max(20),expiresAt:m}).nullable(),charge:t.strictObject({effectiveAt:m,periodEndsAt:m,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s}).nullable(),expiresAt:m,provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:I.optional(),currency:u,lines:t.array(Et).min(1).max(20),catalogAmountMinor:s,nativeDiscountMinor:s.optional(),automaticTax:t.boolean(),execution:t.union([Oe,T]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&S(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Pe=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:Ae,execution:t.union([Oe,T]).nullable(),currency:u,catalogAmountMinor:s,taxMinor:s,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:U.nullable(),confirmedAt:m.nullable().optional(),quote:B.optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),P=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Yi=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:h.optional(),membershipId:t.uuid(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid(),featureQuantities:f.optional()}),t.strictObject({type:t.literal("seats"),licenseKey:C,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),O=t.string().regex(/^price_[A-Za-z0-9]+$/),Ie=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),ve=t.strictObject({price:O.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),Me=t.strictObject({provider:t.literal("stripe"),invoiceMode:h.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(ve).max(20),remove:t.array(O).max(20),restoreItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:Ie}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(ve).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:Ie}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:m}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),M=t.strictObject({merchantTerms:g.optional(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),timing:t.enum(["immediate","renewal"]),effectiveAt:m,expiresAt:m,currency:u,creditMinor:s,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([Me,E])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"subscription_change",e.currency)),L=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:m,checkoutUrl:Ae,executor:t.enum(["indiana","merchant"]),execution:t.union([Me,E]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),quote:M.optional(),authority:x.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),kt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:m,currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:s,policy:t.enum(["apple_store","google_full_price"])})}),Rt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:m.nullable(),checkoutUrl:t.null(),nativePurchase:U.nullable()}),Ji=t.union([M,kt]),Xi=t.union([L,Rt]),F=Q,p=$,zi=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount"),we=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:F,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Nt=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([we,j]),expiresAt:m}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ut=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:Nt.optional(),execution:t.union([we,j]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:m,completedAt:m.nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),en=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,refundableMinor:p,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(Ut).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),tn=t.strictObject({requestId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount");var an=t.strictObject({membershipId:t.uuid(),timing:t.enum(["immediate","renewal"])}),sn=t.union([B,M]),cn=t.union([Pe,L]);function un(e){return"membershipId"in e}function Te(e){return"membershipId"in e}function mn(e){return Te(e)?e.status==="effective"||e.status==="scheduled":e.status==="complete"}function dn(e){return Te(e)?["prepared","quoted","confirmed","pending"].includes(e.status):e.status==="pending"}export{I as a,ti as b,je as c,De as d,Lt as e,v as f,A as g,qe as h,hi as i,fi as j,wi as k,Ei as l,ji as m,Zi as n,Wi as o,B as p,Pe as q,Yi as r,M as s,Ji as t,Xi as u,zi as v,Nt as w,Ut as x,an as y,sn as z,cn as A,un as B,Te as C,mn as D,dn as E};
1
+ import{O as x,a as w,b as f,c as T,d as E,e as j,h as b,i as y,m as G,n as Q,o as $,p as D,q as k,s as g,t as S}from"./chunk-S5RM3VO6.js";import{a as ee}from"./chunk-VILB5M4X.js";import{a as H,b as _,c as Z,d as W,q as J}from"./chunk-ZRGL2CAP.js";import{a as u,b as K,c as V,d as Y}from"./chunk-KTWKDR5L.js";import{e as X,f as R,g as z}from"./chunk-FQMZY5VP.js";import{b as t}from"./chunk-PZTWDJHN.js";var te={"zh-Hans":{merchandise:"减 {discount}(单次使用)",once:"首期减 {discount}",repeating:"前 {months} 个月每月减 {discount}",forever:"每期减 {discount}"},"zh-Hant":{merchandise:"減 {discount}(單次使用)",once:"首期減 {discount}",repeating:"前 {months} 個月每月減 {discount}",forever:"每期減 {discount}"},en:{merchandise:"{discount} off · one use",once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{merchandise:"{discount} 割引(1回のみ)",once:"初回のお支払いが {discount} 割引",repeating:"最初の {months} か月間、毎月 {discount} 割引",forever:"毎回のお支払いが {discount} 割引"},ko:{merchandise:"{discount} 할인 · 1회 사용",once:"첫 결제 {discount} 할인",repeating:"첫 {months}개월 동안 매월 {discount} 할인",forever:"매 결제 {discount} 할인"},es:{merchandise:"{discount} de descuento · un uso",once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{merchandise:"{discount} de réduction · une utilisation",once:"{discount} de réduction sur le premier paiement",repeating:"{discount} de réduction par mois pendant les {months} premiers mois",forever:"{discount} de réduction sur chaque paiement",repeatingOne:"{discount} de réduction pendant le premier mois"},de:{merchandise:"{discount} Rabatt · einmalig",once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat für die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{merchandise:"{discount} de desconto · um uso",once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por mês nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro mês"},it:{merchandise:"{discount} di sconto · un utilizzo",once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{merchandise:"Скидка {discount} · одно использование",once:"Скидка {discount} на первый платёж",repeating:"Скидка {discount} каждый месяц в течение первых {months} мес.",repeatingOne:"Скидка {discount} в первый месяц",forever:"Скидка {discount} на каждый платёж"},vi:{merchandise:"Giảm {discount} · dùng một lần",once:"Giảm {discount} cho lần thanh toán đầu tiên",repeating:"Giảm {discount} mỗi tháng trong {months} tháng đầu",forever:"Giảm {discount} cho mỗi lần thanh toán"},th:{merchandise:"ลด {discount} · ใช้ได้ครั้งเดียว",once:"ลด {discount} สำหรับการชำระเงินครั้งแรก",repeating:"ลด {discount} ต่อเดือนในช่วง {months} เดือนแรก",forever:"ลด {discount} สำหรับการชำระเงินทุกครั้ง"},id:{merchandise:"Diskon {discount} · sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"خصم {discount} · استخدام واحد",once:"خصم {discount} على الدفعة الأولى",repeating:"خصم {discount} شهريًا لمدة {period}",forever:"خصم {discount} على كل دفعة"}};function N(e){let i=J(e)??"en",n=i.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(c=>["TW","HK","MO"].includes(c))?"zh-Hant":"zh-Hans":n[0]??"en",o=te[r];return o?{locale:i,copy:o}:{locale:"en",copy:te.en}}function je(e,i,n="zh-CN"){let r=K(i);return V(e,i,N(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function De(e,i="zh-CN"){let n=N(i).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):je(e.amountOffCents,e.currency,n)}var ie={zh:"前 {months} 个月内开出的账单减 {discount}","zh-Hant":"前 {months} 個月內開出的帳單減 {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"最初の {months} か月以内の請求が {discount} 割引",ko:"첫 {months}개월 내 청구서 {discount} 할인",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de réduction sur les factures émises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"Скидка {discount} на счета в течение первых {months} мес.",vi:"Giảm {discount} cho hóa đơn trong {months} tháng đầu",th:"ลด {discount} สำหรับใบแจ้งหนี้ในช่วง {months} เดือนแรก",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"خصم {discount} على الفواتير الصادرة خلال أول {period}"};function Lt(e,i="zh-CN",n="month"){let r=N(i),o=De(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",o);let c=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0]??"en",d=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,l=e.duration.type==="repeating"&&n!=="month"?ie[d]??ie.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],Ee=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return l.replace("{discount}",o).replace("{months}",c).replace("{period}",Ee)}var Qt=t.discriminatedUnion("action",[t.strictObject({action:t.literal("create"),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:t.enum(["introductory","promotional"])}),t.strictObject({action:t.literal("set_enabled"),id:t.uuid(),revision:t.number().int().nonnegative(),enabled:t.boolean()})]),$t=t.array(t.strictObject({id:t.uuid(),couponId:t.uuid(),productBindingId:t.uuid(),storeOfferId:t.string().min(1).max(255).nullable(),storeOfferType:t.enum(["introductory","promotional"]),enabled:t.boolean(),revision:t.number().int().nonnegative()})).max(500),I=t.strictObject({offerKind:t.enum(["none","introductory","promotional"]),offerId:t.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:t.number().int().min(0).max(1e8),trialDays:t.number().int().min(1).max(730).nullable()}).superRefine((e,i)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&i.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),Kt=t.record(t.uuid(),I).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var U=t.object({type:t.literal("native_purchase"),receiptId:t.uuid(),orderId:t.uuid(),productVersionId:t.uuid(),provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),productKind:Y,replacement:t.strictObject({sourceOrderId:t.uuid(),sourceProductId:t.string().min(1).max(255),policy:t.enum(["apple_store","google_full_price"]),sourceAccountTokens:t.array(t.uuid()).max(50)}).nullable(),appAccountToken:t.uuid().optional(),obfuscatedAccountId:t.string().min(1).max(64).optional(),obfuscatedProfileId:t.uuid().optional(),basePlanId:t.string().min(1).max(255).optional(),offerId:t.string().min(1).max(255).optional(),offerKind:t.enum(["none","introductory","promotional"]),currency:u,catalogAmountMinor:t.number().int().nonnegative().max(1e8),discountMinor:t.number().int().nonnegative().max(1e8),trialDays:t.number().int().min(1).max(730).nullable(),seatBundle:t.array(t.strictObject({key:t.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:t.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:t.strictObject({offerId:t.string().min(1).max(255),keyId:t.string().min(1).max(255),nonce:t.uuid(),signature:t.string().min(1).max(1024),timestamp:t.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,i)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(o=>o.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&i.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});var ke=t.enum(["active","inactive"]),Re=t.preprocess((e,i)=>{let n=0;function r(o,c){if(!(++n>1e4||c>20)){if(Array.isArray(o))o.forEach(a=>r(a,c+1));else if(o&&typeof o=="object")for(let[a,d]of Object.entries(o))["__proto__","constructor","prototype"].includes(a)&&i.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(d,c+1)}}return r(e,0),e},X),Ne=t.strictObject({id:t.string().trim().min(1).max(255),name:t.string().trim().min(1).max(255),status:ke,metadata:Re}),ei=Ne.extend({internal_id:t.uuid(),project_id:t.uuid(),environment_id:t.uuid(),created_at:t.iso.datetime({offset:!0}),updated_at:t.iso.datetime({offset:!0})}),ti=t.union([t.strictObject({id:t.string().trim().min(1).max(255)}),t.strictObject({internalId:t.uuid()})]),ii=t.enum(["customer","merchandise","context"]),ni=t.enum(["system","stored","request"]),ri=t.enum(["customer","merchandise","mixed"]),ne=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function q(e,i={},n=new Set){if(ee(e).some(ne))return!0;for(let r of z(e)){if(n.has(r))continue;n.add(r);let o=i[r];if(o?.type==="list"&&ne(o.attributeKey)||o?.type==="condition"&&q(o.condition,i,n))return!0}return!1}var di=t.enum(["draft","active","paused","archived"]),v=t.discriminatedUnion("type",[t.object({type:t.literal("percent"),percentOff:t.number().min(1).max(100).multipleOf(.01)}).strict(),t.object({type:t.literal("amount"),amountOffCents:t.number().int().min(1).max(1e8),currency:u}).strict()]),A=t.discriminatedUnion("type",[t.object({type:t.literal("once")}).strict(),t.object({type:t.literal("repeating"),months:t.number().int().min(1).max(36)}).strict(),t.object({type:t.literal("forever")}).strict()]),re=[t.object({type:t.literal("all")}).strict(),t.object({type:t.literal("plans"),planIds:t.array(t.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"套餐不能重复")}).strict()],Ue=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.discriminatedUnion("type",[t.strictObject({type:t.literal("all")}),t.strictObject({type:t.literal("selected"),merchandiseIds:t.array(t.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),t.strictObject({type:t.literal("condition"),condition:R})])})]),qe=t.discriminatedUnion("type",[...re,t.strictObject({type:t.literal("merchandise"),scope:t.strictObject({type:t.enum(["all","selected","condition"])})})]),Be=t.strictObject({firstPurchaseOnly:t.boolean(),condition:R}),pi=t.object({name:t.string().trim().min(1).max(80),description:t.string().max(500),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:Ue,eligibility:Be,selfClaimEnabled:t.boolean().default(!1),startsAt:t.iso.datetime().nullable(),endsAt:t.iso.datetime().nullable(),totalLimit:t.number().int().min(1).max(1e6).nullable(),perCustomerLimit:t.number().int().min(1).max(10),grantWindowHours:t.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"结束时间必须晚于开始时间",path:["endsAt"]}).refine(e=>!q(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),li=t.object({code:t.string().trim().transform(e=>e.toUpperCase()).pipe(t.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"优惠码只能用 3–32 位字母、数字、- 和 _,以字母或数字开头")),maxRedemptions:t.number().int().min(1).max(1e6).nullable(),expiresAt:t.iso.datetime().nullable(),firstPurchaseOnly:t.boolean(),minimumAmountCents:t.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:u.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var hi=t.object({id:t.uuid(),couponId:t.uuid(),status:t.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:t.iso.datetime(),expiresAt:t.iso.datetime(),coupon:t.object({name:t.string(),discount:v,duration:A,nativeDiscountPolicy:w.optional(),appliesTo:qe}).strict()}).strict(),fi=t.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var oe=t.strictObject({itemKey:t.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:t.uuid(),includedAmount:t.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:t.number().int().min(0).max(1e4),terms:Z,pricing:H.optional(),unitAmountMinor:t.number().int().min(0).max(1e8),productId:t.string().min(1).max(255).nullable(),priceId:t.string().min(1).max(255).nullable()}).superRefine((e,i)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&i.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{W(e.includedAmount,e.terms.units,e.quantity),_({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{i.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});var C=t.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID 使用小写字母、数字和下划线,并以字母开头"),vi=t.object({amountCents:t.number().int().min(0).max(1e8),currency:u,interval:t.enum(["free","month","year"]),currencyOptions:t.partialRecord(u,t.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"免费套餐金额必须为 0,付费金额必须大于 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"附加币种不能重复默认币种;免费套餐不设置附加价格");var Le=t.registry(),{BillingInterval:ae}=(()=>{var e;return(function(i){i.OneOff="one_off",i.Week="week",i.Month="month",i.Quarter="quarter",i.SemiAnnual="semi_annual",i.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:Fe}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(t),{withSpecDefault:Ge}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:o})=>(e.add(n,{description:o,default:r}),n)}))(Le),{COMMON:se}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Qe}={STRIPE_PRESENTMENT_CURRENCIES:["usd","aed","afn","all","amd","ang","aoa","ars","aud","awg","azn","bam","bbd","bdt","bif","bmd","bnd","bob","brl","bsd","bwp","byn","bzd","cad","cdf","chf","clp","cny","cop","crc","cve","czk","djf","dkk","dop","dzd","egp","etb","eur","fjd","fkp","gbp","gel","gip","gmd","gnf","gtq","gyd","hkd","hnl","htg","huf","idr","ils","inr","isk","jmd","jpy","kes","kgs","khr","kmf","krw","kyd","kzt","lak","lbp","lkr","lrd","lsl","mad","mdl","mga","mkd","mmk","mnt","mop","mur","mvr","mwk","mxn","myr","mzn","nad","ngn","nio","nok","npr","nzd","pab","pen","pgk","php","pkr","pln","pyg","qar","ron","rsd","rub","rwf","sar","sbd","scr","sek","sgd","shp","sle","sos","srd","std","szl","thb","tjs","top","try","ttd","twd","tzs","uah","ugx","uyu","uzs","vnd","vuv","wst","xaf","xcd","xcg","xof","xpf","yer","zar","zmw"]},{COMMON_SET:$e}=(e=>({COMMON_SET:new Set(e)}))(se),{hasNoDuplicateCurrencies:ce}={hasNoDuplicateCurrencies:i=>{let n=new Set;for(let{currency:r}of i){let o=r.toLowerCase();if(n.has(o))return!1;n.add(o)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:ue}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ke}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(t),{Infinite:Ve}={Infinite:"inf"},{TierBehavior:He}=(()=>{var e;return(function(i){i.Graduated="graduated",i.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:me}=(()=>{var e;return(function(i){i.Prepaid="prepaid",i.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Ze}=(()=>{var e;return(function(i){i.Arrear="arrear",i.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:We}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ye}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Je}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(t),{ApiCreditTierSchema:de}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(t),{VIOLATION_MESSAGES:Xe}={VIOLATION_MESSAGES:{non_final_infinity:"Only the final tier may use an 'inf' boundary.",not_increasing:"Tier boundaries must be strictly increasing.",final_not_infinity:"The final tier must use an 'inf' boundary."}},{MarkupEntrySchema:pe}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(t),{ModelMarkupsSchema:ze}=((e,i)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),i.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(t,pe),{InvoiceUsageEntrySchema:et}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(t),{AttachDiscountSchema:le}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(t),{CustomLineItemSchema:tt}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(t),{UnixMsTimestampSchema:it}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(t),{CreateInvoicePreviewLineSchema:nt}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(t),{ReissueInvoiceParamsSchema:wi}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(t),{InvoiceModeParamsSchema:h}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(t),{InvoiceTemplateSchema:Ti}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(t),{BasePriceSchema:rt}=((e,i,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(i).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(t,ae,Fe),{CURRENCY_CODES:ot}=((e,i,n)=>({CURRENCY_CODES:[...e,...i.filter(o=>!n.has(o)).sort()]}))(se,Qe,$e),{ApiPriceProcessorsSchema:he}=((e,i)=>({ApiPriceProcessorsSchema:e.object({stripe:i.nullish()}).meta({"x-atmn-mapping":!0})}))(t,Ke),{AllocatedBillingFieldSchema:at}=((e,i)=>({AllocatedBillingFieldSchema:e.enum(i).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(t,Ze),{CreditDimensionNameSchema:st}=((e,i,n)=>({CreditDimensionNameSchema:e.string().min(1).max(i).refine(o=>!o.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(t,We,Ye),{ApiCreditMatchSchema:fe}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Je),{findCreditTierViolations:ct}=(e=>({findCreditTierViolations:n=>{let r=[],o=(a,d)=>r.push({index:a,reason:d,message:e[d]}),c=0;for(let[a,d]of n.entries()){let l=a===n.length-1;if(d==="inf"){l||o(a,"non_final_infinity");continue}(!Number.isFinite(d)||d<=c)&&o(a,"not_increasing"),c=d,l&&o(a,"final_not_infinity")}return r}}))(Xe),{ApiCreditMultiplierSchema:ut}=((e,i)=>({ApiCreditMultiplierSchema:e.object({match:i,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(t,fe),{ProviderMarkupsSchema:mt}=((e,i)=>({ProviderMarkupsSchema:e.record(e.string(),i).nullish()}))(t,pe),{InvoiceFeatureQuantitySchema:be}=((e,i,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(i).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(o=>o.quantity!==void 0!=(o.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(t,me,et),{CreateInvoicePreviewSchema:Ei}=((e,i)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(i),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(t,nt),{SUPPORTED_SET:dt}=(e=>({SUPPORTED_SET:new Set(e)}))(ot),{ApiCreditDimensionBaseSchema:pt}=((e,i)=>({ApiCreditDimensionBaseSchema:e.object({match:i,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(t,fe),{refineGraduatedTiers:ye}=(e=>({refineGraduatedTiers:(n,r)=>{let o=e(n.tiers.map(c=>c.to));for(let{index:c,message:a}of o)r.addIssue({code:"custom",message:a,path:["tiers",c,"to"]})}}))(ct),{ApiFeatureMarkupsOverrideSchema:lt}=((e,i,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:i.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(t,mt,ze),{isValidCurrencyCode:ht}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(dt),{ApiCreditDimensionSchema:ft}=((e,i,n,r)=>({ApiCreditDimensionSchema:e.union([i.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),i.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(t,pt,de,ye),{CurrencyCodeSchema:ge}=((e,i)=>({CurrencyCodeSchema:e.string().refine(i,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(t,ht),{AdditionalCurrencyTierSchema:bt}=((e,i)=>({AdditionalCurrencyTierSchema:e.object({currency:i,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(t,ge),{ApiCreditSchemaItemBaseSchema:Se}=((e,i,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(i,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(i,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(t,st,ft,ut),{ApiFlatCreditSchemaItemSchema:yt}=((e,i)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:i.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Se,t),{AdditionalCurrencyPriceSchema:gt}=((e,i)=>({AdditionalCurrencyPriceSchema:e.object({currency:i,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(t,ge),{AdditionalCurrencyTierArraySchema:St}=((e,i,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(i).refine(n,{message:r})}))(t,bt,ce,ue),{ApiGraduatedCreditSchemaItemSchema:_t}=((e,i,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:i.literal("graduated"),tiers:i.array(n).min(1)}).strict().superRefine(r)}))(Se,t,de,ye),{AdditionalCurrencyPriceArraySchema:_e}=((e,i,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(i).refine(n,{message:r})}))(t,gt,ce,ue),{ApiUsageTierWithCurrenciesSchema:xt}=((e,i,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(i)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(o=>o.amount!==void 0||o.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(o=>({...o,amount:o.amount??0})).pipe(e.object({to:e.number().or(e.literal(i)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(t,Ve,St),{ApiCreditSchemaItemSchema:It}=((e,i,n)=>({ApiCreditSchemaItemSchema:e.union([i,n])}))(t,_t,yt),{BasePriceParamsSchema:vt}=((e,i,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:i({schema:n.number().optional(),defaultValue:1,description:"Number of intervals per billing cycle. Defaults to 1."}),additional_currencies:r.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),base_currency:n.string().optional().meta({internal:!0}),entitlement_id:n.string().optional().meta({internal:!0}),price_id:n.string().optional().meta({internal:!0}),stripe_price_id:n.string().optional().meta({description:"Stripe price id this base price is billed under. Set by sync flows to capture the actual Stripe price when it differs from the catalog default.",internal:!0})}).meta({title:"BasePrice",description:"Base price configuration for a plan."})}))(rt,Ge,t,_e),{PlanItemPriceParamsSchema:At}=((e,i,n,r,o,c,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(l=>l??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:i.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(o).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(c).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(t,_e,xt,He,ae,me,at),{ApiFeatureOverrideSchema:Ct}=((e,i,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(i).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(t,It,lt),{InvoiceBasePriceParamsSchema:xe}=((e,i)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(vt,he),{InvoiceItemPriceParamsSchema:Ot}=((e,i)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:i.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(At,he),{InvoiceLicenseQuantitySchema:Pt}=((e,i,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:i.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(t,xe,be),{InvoiceCustomizeItemSchema:Mt}=((e,i,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:i.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(t,Ot,Ct),{InvoiceCustomizeSchema:wt}=((e,i,n)=>({InvoiceCustomizeSchema:e.object({price:i.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(t,xe,Mt),{InvoicePlanParamsSchema:Tt}=((e,i,n,r,o)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:i.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(o).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(t,wt,be,Pt,le),{CreateInvoiceParamsSchema:ji}=((e,i,n,r,o)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(i).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:o.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start → period_end against one price interval starting at period_start."}),period_end:o.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(t,Tt,tt,le,it);var m=t.iso.datetime({offset:!0}),Ae=t.url().refine(e=>new URL(e).protocol==="https:").nullable(),Zi=t.strictObject({requestId:t.uuid(),predecessorOperationId:t.uuid().optional(),invoiceMode:h.optional(),entityId:t.uuid().optional(),billingSubscriptionId:t.uuid().optional(),newBillingSubscription:t.literal(!0).optional(),offerId:t.uuid().optional(),nativeOffer:I.optional(),plans:t.array(t.strictObject({productVersionId:t.uuid(),seatQuantities:t.record(C,t.number().int().min(0).max(1e4)).optional(),featureQuantities:t.record(t.uuid(),t.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(i=>i.productVersionId)).size===e.length,"Plan versions must be unique"),provider:t.enum(["stripe","apple","google","merchant"]),currency:u}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Wi=t.strictObject({operationId:t.uuid()}),s=t.number().int().min(0).max(1e8),Et=t.strictObject({lineId:t.uuid(),productVersionId:t.uuid(),productName:t.string().min(1).max(80),interval:t.enum(["free","week","month","year","one_time"]),intervalCount:t.number().int().min(1).max(156).optional(),baseAmountMinor:s,seats:t.array(t.strictObject({key:C,quantity:t.number().int().min(0).max(1e4),includedQuantity:t.number().int().min(0).max(1e4),maximumQuantity:t.number().int().min(0).max(1e4),unitAmountMinor:s})).max(20),prepaid:t.array(oe).max(100).optional(),catalogAmountMinor:s,trial:G.nullable()}).refine(e=>new Set(e.seats.map(i=>i.key)).size===e.seats.length&&e.seats.every(i=>i.quantity>=i.includedQuantity&&i.quantity<=i.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((i,n)=>i+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((i,n)=>i+_({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Ce=t.string().regex(/^[A-Za-z0-9_-]{1,200}$/),jt=t.strictObject({id:Ce,name:t.string().min(1).max(40),percent_off:t.number().gt(0).max(100).optional(),amount_off:t.number().int().positive().optional(),currency:t.string().regex(/^[a-z]{3}$/).optional(),duration:t.enum(["once","repeating","forever"]),duration_in_months:t.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Dt=t.strictObject({subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:t.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:t.array(t.strictObject({id:t.string(),price_id:t.string(),quantity:t.number().int().nonnegative(),discounts:t.array(t.strictObject({id:t.string(),coupon:t.string(),start:t.number(),end:t.number().nullable()})).optional()})).min(1).max(100),prorationDate:t.number().int().nonnegative(),amountMinor:t.number().int().positive(),periodStartMs:t.number(),periodEndMs:t.number()}),Oe=t.strictObject({invoiceMode:h.optional(),append:Dt.optional(),provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),mode:t.enum(["payment","subscription"]),lineItems:t.array(t.strictObject({price:t.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:t.number().int().min(1).max(1e4),priceId:t.uuid(),productName:t.string().min(1).max(80),amountMinor:t.number().int().min(0).max(1e8),currency:t.string().regex(/^[a-z]{3}$/),interval:t.enum(["week","month","year","one_off"]),intervalCount:t.number().int().min(1).max(52),slot:t.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:t.strictObject({mode:t.enum(["graduated","volume"]),tiers:t.array(t.strictObject({upTo:t.number().int().min(1).max(1e6).nullable(),unitAmountMinor:t.number().int().min(0).max(1e8),flatAmountMinor:t.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:t.array(t.strictObject({coupon:Ce,terms:jt})).max(1),trialPeriodDays:t.number().int().min(1).max(730).nullable(),metadata:t.strictObject({grooveCheckoutId:t.uuid(),grooveCustomerId:t.uuid()}),expiresAt:m}),B=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),entityId:t.uuid().nullable(),billingSubscriptionId:t.uuid().nullable(),discount:t.strictObject({offerId:t.uuid(),couponId:t.uuid(),discount:v,duration:A,amountMinor:s,allocations:t.array(t.strictObject({productVersionId:t.uuid(),amountMinor:s})).min(1).max(20),expiresAt:m}).nullable(),charge:t.strictObject({effectiveAt:m,periodEndsAt:m,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s}).nullable(),expiresAt:m,provider:t.enum(["stripe","apple","google","merchant"]),nativeOffer:I.optional(),currency:u,lines:t.array(Et).min(1).max(20),catalogAmountMinor:s,nativeDiscountMinor:s.optional(),automaticTax:t.boolean(),execution:t.union([Oe,T]).nullable()}).refine(e=>!e.merchantTerms||e.provider==="merchant"&&S(e.merchantTerms,e.operationId,"purchase",e.currency)).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(i=>!["one_time","free"].includes(i.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(i=>i.price!==null))&&e.execution.discounts.every(i=>i.coupon===i.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(i=>e.discount!==null&&(i.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&i.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${i.terms.amount_off}`&&i.terms.amount_off===e.discount.discount.amountOffCents&&i.terms.currency?.toUpperCase()===e.currency&&i.terms.duration==="once"))):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((i,n)=>{let r=e.lines[n];return r!==void 0&&i.productVersionId===r.productVersionId&&i.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((i,n)=>i+n.amountMinor,0)===e.discount.amountMinor)&&(["stripe","merchant"].includes(e.provider)?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(i=>i.lineId)).size===e.lines.length&&e.lines.reduce((i,n)=>i+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),Pe=t.strictObject({operationId:t.uuid(),orderId:t.uuid(),append:t.boolean().optional(),invoiceMode:t.boolean().optional(),status:t.enum(["pending","complete","cancelled","failed"]),executor:t.enum(["indiana","merchant"]),checkoutUrl:Ae,execution:t.union([Oe,T]).nullable(),currency:u,catalogAmountMinor:s,taxMinor:s,totalMinor:t.number().int().min(0).max(2e8).nullable(),quoteFinalized:t.boolean(),nativePurchase:U.nullable(),confirmedAt:m.nullable().optional(),quote:B.optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),P=t.strictObject({enabled:t.literal(!0),featureIds:t.array(t.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Yi=t.strictObject({requestId:t.uuid(),offerId:t.uuid().optional(),invoiceMode:h.optional(),membershipId:t.uuid(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),membershipIds:t.array(t.uuid()).min(1).max(20).optional(),prorationBehavior:t.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:t.enum(["immediate","renewal","store"]),change:t.discriminatedUnion("type",[t.strictObject({type:t.literal("plan"),productVersionId:t.uuid(),featureQuantities:f.optional()}),t.strictObject({type:t.literal("seats"),licenseKey:C,quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("quantity"),internal_feature_id:t.uuid(),quantity:t.number().int().min(0).max(1e4)}),t.strictObject({type:t.literal("cancel")}),t.strictObject({type:t.literal("uncancel")}),t.strictObject({type:t.literal("billing_cycle"),billingCycleAnchor:t.union([t.literal("now"),t.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>!e.offerId||e.change.type==="plan"&&e.timing!=="store","A selected plan-change offer requires a merchant target Product").refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),O=t.string().regex(/^price_[A-Za-z0-9]+$/),Ie=t.strictObject({grooveUpdateId:t.uuid(),grooveCustomerId:t.uuid()}),ve=t.strictObject({price:O.nullable(),priceId:t.uuid().optional(),quantity:t.number().int().min(0).max(1e4)}),Me=t.strictObject({provider:t.literal("stripe"),invoiceMode:h.optional(),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:t.string().regex(/^sub_[A-Za-z0-9]+$/),action:t.enum(["update","cancel","schedule","release"]),update:t.strictObject({items:t.array(ve).max(20),remove:t.array(O).max(20),restoreItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:t.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:t.number().int().positive().optional(),paymentBehavior:t.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:t.boolean().optional(),clearCancelAt:t.literal(!0).optional(),billingCycleAnchorNow:t.literal(!0).optional(),metadata:Ie}).nullable(),cancel:t.strictObject({prorate:t.literal(!1),invoiceNow:t.literal(!1)}).nullable(),schedule:t.strictObject({currentItems:t.array(t.strictObject({price:O,quantity:t.number().int().min(0).max(1e4)})).max(20),nextItems:t.array(ve).min(1).max(20),switchAt:t.number().int().positive(),interval:t.enum(["week","month","year"]),intervalCount:t.number().int().min(1).max(52),resetBillingCycleAnchor:t.literal(!0).optional(),metadata:Ie}).nullable(),release:t.strictObject({schedule:t.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:m}).refine(e=>["update","cancel","schedule","release"].every(i=>e[i]!==null==(e.action===i))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(i=>i.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),M=t.strictObject({merchantTerms:g.optional(),carryOverBalances:P.optional(),carryOverUsages:P.optional(),operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),timing:t.enum(["immediate","renewal"]),effectiveAt:m,expiresAt:m,currency:u,creditMinor:s,debitMinor:s,discountMinor:s,taxMinor:s,totalMinor:s,retainedProductVersionIds:t.array(t.uuid()).max(19),execution:t.union([Me,E])}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"subscription_change",e.currency)),L=t.strictObject({operationId:t.uuid(),invoiceMode:t.boolean().optional(),membershipId:t.uuid(),productVersionId:t.uuid(),featureQuantities:f.optional(),status:t.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:t.enum(["immediate","renewal"]),effectiveAt:m,checkoutUrl:Ae,executor:t.enum(["indiana","merchant"]),execution:t.union([Me,E]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),quote:M.optional(),authority:x.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),kt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),timing:t.literal("store"),effectiveAt:t.null(),expiresAt:m,currency:u,creditMinor:t.null(),debitMinor:t.null(),discountMinor:t.null(),taxMinor:t.null(),totalMinor:t.null(),retainedProductVersionIds:t.array(t.uuid()).max(19),store:t.strictObject({provider:t.enum(["apple","google"]),productId:t.string().min(1).max(255),catalogAmountMinor:s,policy:t.enum(["apple_store","google_full_price"])})}),Rt=t.strictObject({operationId:t.uuid(),membershipId:t.uuid(),productVersionId:t.uuid(),status:t.enum(["prepared","pending","effective","cancelled","failed"]),timing:t.literal("store"),effectiveAt:m.nullable(),checkoutUrl:t.null(),nativePurchase:U.nullable()}),Ji=t.union([M,kt]),Xi=t.union([L,Rt]),F=Q,p=$,zi=t.strictObject({requestId:t.uuid(),invoiceId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount"),we=t.strictObject({provider:t.literal("stripe"),executor:t.enum(["indiana","merchant"]),accountId:t.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:t.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:F,currency:t.string().regex(/^[a-z]{3}$/),metadata:t.strictObject({indianaRefundId:t.uuid()}),idempotencyKey:t.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:t.array(t.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Nt=t.strictObject({operationId:t.uuid(),merchantTerms:g.optional(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),revokes:t.strictObject({customerProductIds:t.array(t.uuid()).max(100),subscriptionIds:t.array(t.string().min(1).max(200)).max(20)}),execution:t.union([we,j]),expiresAt:m}).refine(e=>!e.merchantTerms||e.execution.provider==="merchant"&&S(e.merchantTerms,e.operationId,"refund",e.currency)).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency:e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase())&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),Ut=t.strictObject({operationId:t.uuid(),invoiceId:t.uuid(),providerInvoiceId:t.string().min(1).max(200),status:t.enum(["quoted","pending","succeeded","failed","expired"]),executor:t.enum(["indiana","merchant"]),currency:u,amountMinor:F,mode:t.enum(["full","partial"]),entitlementAction:t.enum(["retain","revoke"]),refundId:t.string().min(1).max(200).nullable(),quote:Nt.optional(),execution:t.union([we,j]).nullable(),confirmedAt:m.nullable().optional(),merchantExecution:y.nullable().optional(),problem:b.nullable().optional(),authority:x.optional(),failureReason:t.string().min(1).max(200).nullable(),createdAt:m,completedAt:m.nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),en=t.strictObject({invoiceId:t.uuid(),currency:u,paidMinor:p,refundedMinor:p,pendingMinor:p,refundableMinor:p,executor:t.enum(["indiana","merchant"]).nullable(),canRefund:t.boolean(),operations:t.array(Ut).max(50)}).refine(e=>e.operations.every(i=>i.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),tn=t.strictObject({requestId:t.uuid(),...k.shape}).refine(D,"A partial refund states amountMinor; a full refund refunds the remaining amount");var an=t.strictObject({membershipId:t.uuid(),timing:t.enum(["immediate","renewal"])}),sn=t.union([B,M]),cn=t.union([Pe,L]);function un(e){return"membershipId"in e}function Te(e){return"membershipId"in e}function mn(e){return Te(e)?e.status==="effective"||e.status==="scheduled":e.status==="complete"}function dn(e){return Te(e)?["prepared","quoted","confirmed","pending"].includes(e.status):e.status==="pending"}export{I as a,ti as b,je as c,De as d,Lt as e,v as f,A as g,qe as h,hi as i,fi as j,wi as k,Ei as l,ji as m,Zi as n,Wi as o,B as p,Pe as q,Yi as r,M as s,Ji as t,Xi as u,zi as v,Nt as w,Ut as x,an as y,sn as z,cn as A,un as B,Te as C,mn as D,dn as E};
@@ -1 +1 @@
1
- import{b as p,c as d}from"./chunk-BX2MSRA4.js";import{t as a,w as u,z as m}from"./chunk-RRZZUIFM.js";import{b as e}from"./chunk-5YBTU4KS.js";var s=e.enum(["page","popup","banner"]),y=3e5,f=e.strictObject({type:e.enum(["string","number","boolean","strings","json"]),nullable:e.boolean()}),h=e.strictObject({inputs:e.record(a,f.extend({required:e.boolean()})).refine(t=>Object.keys(t).length<=40,"Too many content inputs"),outputs:e.record(a,f).refine(t=>Object.keys(t).length<=40,"Too many content outputs")}),g=e.strictObject({kind:s,schemaVersion:e.literal(1),name:e.string().trim().min(1).max(80),screen:u,contract:h}),c=g.superRefine((t,r)=>{let n=(o,b)=>r.addIssue({code:"custom",message:o,path:b});t.screen.surface!==t.kind&&n("Content surface must match its domain",["screen","surface"]),t.screen.name!==t.name&&n("Content has one editable name",["screen","name"]),t.kind==="banner"&&t.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),t.kind!=="banner"&&t.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),t.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let i=new Set(t.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(t.contract.outputs).some(o=>!i.has(o))||[...i].some(o=>!Object.hasOwn(t.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),d(t)>y&&n("Content document exceeds its byte budget",[])});function S(t,r){if(t===null)return r.nullable;switch(r.type){case"json":return!0;case"string":return typeof t=="string";case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"strings":return Array.isArray(t)&&t.every(n=>typeof n=="string")}}var x=c.superRefine((t,r)=>{for(let n of p(t.screen))Object.keys(t.contract.inputs).some(i=>n===i||n.startsWith(i+"."))||r.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of t.screen.actions){if(n.type!=="event")continue;let i=t.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;i&&!S(o,i)&&r.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}m(t.screen).some(n=>!n.complete)&&r.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),l=e.strictObject({id:e.uuid(),kind:s,projectId:e.uuid(),environmentId:e.uuid(),name:e.string(),revision:e.number().int().nonnegative(),status:e.enum(["draft","published","archived"]),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})}),D=l.extend({draft:c}),I=e.strictObject({rows:e.array(l).max(200),nextCursor:e.uuid().nullable()}),v=e.strictObject({id:e.uuid(),kind:s,resourceId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),sourceRevision:e.number().int().nonnegative(),document:x,createdAt:e.iso.datetime({offset:!0})}),z=v.omit({document:!0}),V=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),kind:s,id:e.uuid(),document:c}),e.strictObject({action:e.literal("save"),kind:s,id:e.uuid(),revision:e.number().int().nonnegative(),document:c}),e.strictObject({action:e.enum(["publish","archive"]),kind:s,id:e.uuid(),revision:e.number().int().nonnegative()})]).superRefine((t,r)=>{"document"in t&&t.document.kind!==t.kind&&r.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});export{s as a,v as b};
1
+ import{b as p,c as d}from"./chunk-EKUDMQXT.js";import{t as a,w as u,z as m}from"./chunk-ZRGL2CAP.js";import{b as e}from"./chunk-PZTWDJHN.js";var s=e.enum(["page","popup","banner"]),y=3e5,f=e.strictObject({type:e.enum(["string","number","boolean","strings","json"]),nullable:e.boolean()}),h=e.strictObject({inputs:e.record(a,f.extend({required:e.boolean()})).refine(t=>Object.keys(t).length<=40,"Too many content inputs"),outputs:e.record(a,f).refine(t=>Object.keys(t).length<=40,"Too many content outputs")}),g=e.strictObject({kind:s,schemaVersion:e.literal(1),name:e.string().trim().min(1).max(80),screen:u,contract:h}),c=g.superRefine((t,r)=>{let n=(o,b)=>r.addIssue({code:"custom",message:o,path:b});t.screen.surface!==t.kind&&n("Content surface must match its domain",["screen","surface"]),t.screen.name!==t.name&&n("Content has one editable name",["screen","name"]),t.kind==="banner"&&t.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),t.kind!=="banner"&&t.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),t.screen.actions.some(o=>o.type!=="event"&&o.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let i=new Set(t.screen.actions.filter(o=>o.type==="event").map(o=>o.id));(Object.keys(t.contract.outputs).some(o=>!i.has(o))||[...i].some(o=>!Object.hasOwn(t.contract.outputs,o)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),d(t)>y&&n("Content document exceeds its byte budget",[])});function S(t,r){if(t===null)return r.nullable;switch(r.type){case"json":return!0;case"string":return typeof t=="string";case"number":return typeof t=="number"&&Number.isFinite(t);case"boolean":return typeof t=="boolean";case"strings":return Array.isArray(t)&&t.every(n=>typeof n=="string")}}var x=c.superRefine((t,r)=>{for(let n of p(t.screen))Object.keys(t.contract.inputs).some(i=>n===i||n.startsWith(i+"."))||r.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of t.screen.actions){if(n.type!=="event")continue;let i=t.contract.outputs[n.id],o=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;i&&!S(o,i)&&r.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}m(t.screen).some(n=>!n.complete)&&r.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),l=e.strictObject({id:e.uuid(),kind:s,projectId:e.uuid(),environmentId:e.uuid(),name:e.string(),revision:e.number().int().nonnegative(),status:e.enum(["draft","published","archived"]),publishedVersionId:e.uuid().nullable(),createdAt:e.iso.datetime({offset:!0}),updatedAt:e.iso.datetime({offset:!0})}),D=l.extend({draft:c}),I=e.strictObject({rows:e.array(l).max(200),nextCursor:e.uuid().nullable()}),v=e.strictObject({id:e.uuid(),kind:s,resourceId:e.uuid(),projectId:e.uuid(),environmentId:e.uuid(),version:e.number().int().positive(),sourceRevision:e.number().int().nonnegative(),document:x,createdAt:e.iso.datetime({offset:!0})}),z=v.omit({document:!0}),V=e.discriminatedUnion("action",[e.strictObject({action:e.literal("create"),kind:s,id:e.uuid(),document:c}),e.strictObject({action:e.literal("save"),kind:s,id:e.uuid(),revision:e.number().int().nonnegative(),document:c}),e.strictObject({action:e.enum(["publish","archive"]),kind:s,id:e.uuid(),revision:e.number().int().nonnegative()})]).superRefine((t,r)=>{"document"in t&&t.document.kind!==t.kind&&r.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});export{s as a,v as b};