@tinkerlandai/indiana-sdk 0.7.0 → 0.8.0

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 (52) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/README.md +11 -10
  3. package/README.zh-CN.md +16 -11
  4. package/dist/{ai-usage-BsrSG955.d.ts → ai-usage-Bigjb8MS.d.ts} +468 -274
  5. package/dist/chunk-2A6UYUFA.js +1 -0
  6. package/dist/chunk-3BQFJANQ.js +1 -0
  7. package/dist/chunk-3ENVRJE6.js +350 -0
  8. package/dist/chunk-A3N4ZZTM.js +7 -0
  9. package/dist/chunk-AE4CUTUE.js +1 -0
  10. package/dist/chunk-CXYOZSOF.js +1 -0
  11. package/dist/{chunk-4AWSZWZD.js → chunk-G2R56FKU.js} +1 -1
  12. package/dist/{chunk-6MO6Y24B.js → chunk-OVMNCZYC.js} +1 -1
  13. package/dist/{configuration-sync-Bvd956GL.d.ts → configuration-sync-VFbY1pCN.d.ts} +34 -35
  14. package/dist/content-K2HCZVC2.js +1 -0
  15. package/dist/{customer-page-B4LkIr5q.d.ts → customer-page-BrCZxcaQ.d.ts} +279 -6
  16. package/dist/funnel-runtime-host-HNZ47TZW.js +1 -0
  17. package/dist/{funnel-runtime-start-ChVYbLzV.d.ts → funnel-runtime-start-DKcTCRrd.d.ts} +1646 -1913
  18. package/dist/index.d.ts +13975 -13679
  19. package/dist/index.js +1 -1
  20. package/dist/native-shell.js +1 -1
  21. package/dist/openrouter.d.ts +3 -2
  22. package/dist/openrouter.js +1 -1
  23. package/dist/page.d.ts +9 -9
  24. package/dist/paywall-PD62B2AY.js +1 -0
  25. package/dist/popup.d.ts +3 -271
  26. package/dist/popup.js +1 -350
  27. package/dist/react-native.d.ts +8 -8
  28. package/dist/react-native.js +1 -1
  29. package/dist/{screen-iFngkxaL.d.ts → screen-BazUOjwM.d.ts} +168 -165
  30. package/dist/server.d.ts +5 -5
  31. package/dist/server.js +1 -1
  32. package/dist/src-4MRSESVS.js +1 -0
  33. package/dist/visual.d.ts +5 -2
  34. package/dist/visual.js +2 -2
  35. package/package.json +1 -7
  36. package/dist/chunk-3SONNXFG.js +0 -1
  37. package/dist/chunk-467Z5ISI.js +0 -11
  38. package/dist/chunk-4K25DELJ.js +0 -1
  39. package/dist/chunk-HD74AAFS.js +0 -1
  40. package/dist/chunk-J4RHVU3W.js +0 -1
  41. package/dist/chunk-NOFNOHUI.js +0 -1
  42. package/dist/chunk-QO4YQLZ4.js +0 -1
  43. package/dist/chunk-U6S6AZM6.js +0 -1
  44. package/dist/chunk-WCFVNF5D.js +0 -1
  45. package/dist/client-F6UPJMHR.js +0 -1
  46. package/dist/controls-XG46TKUU.js +0 -2
  47. package/dist/funnel-runtime-host-26QI2W3S.js +0 -1
  48. package/dist/iam.d.ts +0 -131
  49. package/dist/iam.js +0 -1
  50. package/dist/paywall-WKOHBYW7.js +0 -1
  51. package/dist/src-UHLPVD6E.js +0 -1
  52. package/dist/{errors-DrdTlPwf.d.ts → errors-BpCmukJr.d.ts} +1 -1
@@ -0,0 +1,7 @@
1
+ import{A as qt,Ab as Jt,Da as qc,G as $t,H as Si,Hb as kr,I as Oc,Kb as Ii,Lb as vn,M as Er,Ma as jr,Mb as jt,N as Pc,O as Cc,Ob as Ka,Pa as $c,R as wc,S as Tr,T as Ec,U as Tc,V as $a,W as $n,X as Rc,_ as jc,aa as Nc,ca as kc,fa as vi,ga as Gn,ha as Dc,ja as Fc,ka as Rr,oa as Uc,pa as Kn,q as Sn,qa as Mc,qb as Gc,r as se,s as hi,ub as Rt,v as Ic,va as Bc,w as Pt,wb as ze,x as _e,xa as Lc,xb as Nr,y as qa,ya as Vc,yb as Ga}from"./chunk-3BQFJANQ.js";import{b as we,c as Kc,d as Hc,g as Wc,h as Xt,i as Qc}from"./chunk-AE4CUTUE.js";import{a as he,b as Tt,c as Vn,e as qn,q as yi}from"./chunk-RRII2DMC.js";import{f as gi,g as _i,h as xc,i as bi,k as Ac,l as wr}from"./chunk-KQCTDXVD.js";var Yc="X-Indiana-Protocol",Jf="X-Indiana-SDK-Version",TO="X-Indiana-Supported-Protocols",Zc={stableSupportMonths:12,retirementNoticeDays:180,documentation:"/docs/release-notes#support-policy"},Xf={current:"0.8",unversioned:"0.2",releases:[{protocol:"0.2",firstReleasedAt:"2026-10-16T04:05:43.170Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.2.0",integrity:"sha512-kyzHFrt+zuS2hfDZsknCE3AIA9EZXakCDhorO0Ayn2wTpITbm32GMaqVFyhlPufDhkjkV4C0UvXJMyLT5FWIoQ==",sha256:"7e20dd8df9c5e965f67bcdad6c95bf0d0aa5e61a372e5ece88173e32190a1c4c"}]},{protocol:"0.3",firstReleasedAt:"2026-10-16T16:18:04.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.3.0",integrity:"sha512-jrh4DH2DBYL5tRkr9BNBVIgD1ts0hUPx8+AhiNkkt2uWV27R8tXGRCW1HBLOw2bfomyuIsAXBAY6niJfjkazCg==",sha256:"33f7ca369d509c44df95c5c8b94775c2afe9d8e3a94163275fe59754739e6815"},{version:"0.3.1",integrity:"sha512-Ifp24kv236advquxa78jx49XKz9oKsg5zZZvFMkId4+KxsylsGxHS44fqYJL/b84PVHl3DLuc+Ru2btdLEctIw==",sha256:"4cc047fe94477e77c5403ce47afea0db2806bd4c3cb94a2dd48c453b4e942163"}]},{protocol:"0.4",firstReleasedAt:"2026-10-18T12:44:12.148Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.4.0",integrity:"sha512-QYuxMdw63RzPLkqmFRc7xv8VWYKYWG+KuKM+f5ZeRX879n6sKyr38bxkMiozFXT+kvH0lDfTF73uJPY2yQX1pQ==",sha256:"ef22d0f6a89897bfbaf71487c4e805997528c8dbad2921ab5c90ed3aa0c01244"}]},{protocol:"0.5",firstReleasedAt:"2026-10-19T08:12:17.954Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.5.0",integrity:"sha512-tzdmoHdvaSoDIvGmg+JpmzE+o1kv7DXpSyvNUSuBj5rHX2pD1GDsMf7ioudUVT5MiKaBDVVtJVE+GpxMOBBLLA==",sha256:"d8b1909bebe1bca0c8c029a68b71477e06ba0c9317c3a2b4bf657951ae3449ca"}]},{protocol:"0.6",firstReleasedAt:"2026-10-21T11:41:57.832Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.6.0",integrity:"sha512-M4szAkM52gqiGPZbtpdhoAvYW2uNRQ2aRw0mdnpr2ErTnuG2i1++76fHjo0qiEMSlePdqu99T1Smecp/FZ2//g==",sha256:"141b058b485fb17b416a2f7961ca55e2da413c9afb7ff22f9fdec2561890bd82"},{version:"0.6.1",integrity:"sha512-KbZUP4XCRblj4mF//JG9t4AAMHSP7uENTi7edxJE55QZjvxH4n1/ypWtKZq32xgt9qGu9o3iZzL8tcHoM3B7Ng==",sha256:"e87930eaec7735629e27e930a462dcecb65fdc4e396cc8ab075845a4f4d22396"},{version:"0.6.2",integrity:"sha512-CUXfh46gSh1S7cdgStI3NAzRROlCQxOcvna2KKlDWFq8L7DXtcILLBOKw5Y1e+QQdDPsXGrsMVBOwIJxFyoIlw==",sha256:"dee5f6e605133ec6c509f390fafdf1d0cb66984a02bea0bb5c05828276c64a15"},{version:"0.6.3",integrity:"sha512-MJXbEoZdLym8a7IHUhY9Oh6eXaSRZPdkwYmfGvfsu5O/kTzfIg+OJuaNrFHYzK76msTxR76IMtQ1R45/FddGdg==",sha256:"fcff156ee9ae90a0f5c906721c8e12715f5fd7a97bca494d64a4303283ec633a"},{version:"0.6.4",integrity:"sha512-djTPwCCgNbp/dt0pFnwEgutZExBZ//wmA2GnObRtXydGrzfi8Z9W7RdeGUFvufblJaGAmcWwVqUgmzEi9SLyjA==",sha256:"bd8e53823728b1e45a27e187c538dcb18af005f24e55120d0cc6b5a618a033f7"}]},{protocol:"0.7",firstReleasedAt:"2026-10-23T09:15:53.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.7.0",integrity:"sha512-u2LstlzE8IVFy2dUf/sI9sybNRx3lMF32pjLmeEIFqTdcOXRGdH8GCg5927FwavBpRaWO4a7icmrhYiEjGuYWQ==",sha256:"bb3c3666cbba4ea5018f09e9d050b5db1f71e7a222cdde59c5a93f5ee4a52958"}]},{protocol:"0.8",firstReleasedAt:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]}]},Jc=/^(?:0\.(?:0|[1-9]\d*)|[1-9]\d*)$/,zf=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Xc(e){let t=zf.exec(e);return!t?.[1]||!t[2]?null:t[1]==="0"?`0.${t[2]}`:t[1]}var Wa=e=>/^[1-9]\d*$/.test(e);function eh(e,t){let n=new Date(e),r=n.getUTCDate();n.setUTCDate(1),n.setUTCMonth(n.getUTCMonth()+t);let i=new Date(n.getTime());return i.setUTCMonth(i.getUTCMonth()+1,0),n.setUTCDate(Math.min(r,i.getUTCDate())),n.getTime()}var Ha=e=>/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(e)&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString().replace(".000Z","Z")===e.replace(".000Z","Z");function RO(e){let t=[],n=new Set;for(let r of e.releases){let i=r.protocol;(!Jc.test(i)||n.has(i))&&t.push(`Invalid/duplicate protocol ${i}`),n.add(i),(r.firstReleasedAt===null?i!==e.current:!Ha(r.firstReleasedAt))&&t.push(`${i}: invalid first release date`),r.noticePublishedAt!==null&&!Ha(r.noticePublishedAt)&&t.push(`${i}: invalid notice date`),r.sunsetAt!==null&&!Ha(r.sunsetAt)&&t.push(`${i}: invalid sunset date`),r.noticePublishedAt&&(!r.firstReleasedAt||Date.parse(r.noticePublishedAt)<Date.parse(r.firstReleasedAt))&&t.push(`${i}: notice predates release`),r.noticeUrl!==null&&!/^(?:https:\/\/[^\s<>]+|\/docs\/[\w/#.-]+)$/.test(r.noticeUrl)&&t.push(`${i}: invalid notice URL`),r.firstReleasedAt&&!r.baselines.length&&t.push(`${i}: missing published SDK baseline`),!r.firstReleasedAt&&r.baselines.length&&t.push(`${i}: unpublished current protocol cannot claim published baselines`);let a=new Set;for(let o of r.baselines)(Xc(o.version)!==i||a.has(o.version))&&t.push(`${i}: invalid/duplicate baseline ${o.version}`),a.add(o.version),(!/^sha512-[A-Za-z0-9+/]{86}==$/.test(o.integrity)||!/^[a-f0-9]{64}$/.test(o.sha256))&&t.push(`${i}: unpinned baseline ${o.version}`);if(Wa(i)&&r.sunsetAt!==null){let o=e.releases.filter(s=>s.firstReleasedAt!==null&&Wa(s.protocol)&&Number(s.protocol)>Number(i)).sort((s,c)=>Date.parse(s.firstReleasedAt)-Date.parse(c.firstReleasedAt))[0];o?Date.parse(r.sunsetAt)<eh(o.firstReleasedAt,Zc.stableSupportMonths)&&t.push(`${i}: retirement violates 12 calendar months`):t.push(`${i}: retirement requires a released successor major`),!r.noticePublishedAt||!r.noticeUrl?t.push(`${i}: retirement requires a published notice`):Date.parse(r.sunsetAt)-Date.parse(r.noticePublishedAt)<Zc.retirementNoticeDays*864e5&&t.push(`${i}: retirement violates 180 days notice`)}}return(!n.has(e.current)||!n.has(e.unversioned))&&t.push("Current/unversioned protocol is not registered"),e.releases.find(r=>r.protocol===e.current)?.sunsetAt!==null&&t.push("Current protocol cannot be scheduled for retirement"),t}var In=class extends Error{constructor(n,r,i=400){super(r);this.code=n;this.status=i}code;status};function jO(e,t=Xf,n=Date.now()){let r=e.get(Yc)??t.unversioned;if(!Jc.test(r))throw new In("INVALID_PROTOCOL_VERSION","Invalid Indiana protocol version");let i=t.releases.find(o=>o.protocol===r);if(!i)throw new In("UNSUPPORTED_PROTOCOL_VERSION","Indiana protocol version is not supported");if(!Wa(r)&&r!==t.current)throw new In("UNSUPPORTED_PROTOCOL_VERSION","Only the current pre-1.0 Indiana protocol is supported");if(i.sunsetAt&&n>=Date.parse(i.sunsetAt))throw new In("PROTOCOL_RETIRED","Indiana protocol version has retired; follow the published migration notice",410);let a=e.get(Jf);if(a!==null&&Xc(a)!==r)throw new In("INVALID_PROTOCOL_VERSION","SDK version and protocol version do not match");return i}function NO(e,t=Date.now()){let n={[Yc]:e.protocol};return e.noticePublishedAt&&Date.parse(e.noticePublishedAt)<=t&&(n.Deprecation=`@${Math.floor(Date.parse(e.noticePublishedAt)/1e3)}`,e.noticeUrl&&(n.Link=`<${e.noticeUrl}>; rel="deprecation"; type="text/html"`),e.sunsetAt&&(n.Sunset=new Date(e.sunsetAt).toUTCString())),n}import{z as Gt}from"zod";var UO={plans:Sn,creditPacks:Sn,paidSeats:Sn,postpaid:Sn},zc=Gt.partialRecord(Gt.enum(Sn),Gt.number().int().min(1).max(1e8)),th=Gt.strictObject({currency:Gt.enum(Sn),automaticTax:Gt.boolean()}),nh=Gt.strictObject({projectId:Gt.uuid(),environmentId:Gt.uuid()}),MO=nh.extend({settings:th});import{z as V}from"zod";import{z as Nt}from"zod";var rh=Nt.string().regex(/^[a-z][a-z0-9_]{0,63}$/),eu=Nt.number().int().min(0).max(1e4),Qa=Nt.object({key:rh,featureId:Nt.uuid(),planVersionId:Nt.uuid(),includedQuantity:eu,maximumQuantity:eu,unitAmountCents:Nt.number().int().min(0).max(1e8),currency:se,currencyOptions:zc.optional(),stripePriceId:Nt.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:Nt.array(Nt.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:Nt.boolean()}).strict().refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency),"Additional prices cannot repeat the default currency").refine(e=>e.maximumQuantity>=e.includedQuantity,"\u6700\u5927\u5E2D\u4F4D\u6570\u4E0D\u80FD\u5C0F\u4E8E\u5305\u542B\u5E2D\u4F4D\u6570").refine(e=>new Set(e.pooledResources).size===e.pooledResources.length,"\u5171\u4EAB\u6765\u6E90\u4E0D\u80FD\u91CD\u590D");import{z as be}from"zod";import{z as We}from"zod";var Za=We.object({days:We.number().int().min(1).max(730),cardRequired:We.boolean(),featureAllowances:We.record(We.uuid(),We.number().int().min(0).max(1e9)),creditAmounts:We.record(We.uuid(),_e)}).strict(),Ya=We.object({id:We.uuid(),planVersionId:We.uuid(),slot:We.string(),cardRequired:We.boolean(),status:We.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:We.iso.datetime().nullable(),endsAt:We.iso.datetime().nullable(),createdAt:We.iso.datetime()}).strict();var Ja=be.object({group:be.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:be.enum(["main","addon"]).default("main")}).strict(),ih=be.enum(["immediate","end_of_cycle"]),ah=be.enum(["attach","change","cancel","resume","cancel_change"]),tu=be.object({id:be.uuid(),subscriptionId:be.uuid().nullable(),targetPlanVersionId:be.uuid().nullable(),action:ah,timing:ih,status:be.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:be.iso.datetime().nullable(),createdAt:be.iso.datetime()}),oh=be.object({id:be.uuid(),planVersionId:be.uuid(),planId:be.uuid(),basePlanId:be.uuid().nullable(),name:be.string(),group:be.string(),kind:be.enum(["main","addon"]),source:be.enum(["subscription","assignment","license","apple","google"]),status:be.string(),accessEnabled:be.boolean(),startsAt:be.iso.datetime().nullable(),endsAt:be.iso.datetime().nullable(),cancelAtPeriodEnd:be.boolean(),scheduledChange:tu.nullable(),trial:Ya.nullable().optional()}),ZO=be.object({customerId:be.uuid(),evaluatedAt:be.iso.datetime(),holdings:be.array(oh),changes:be.array(tu),trials:be.array(Ya).optional()});var kt=V.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),rP=V.record(V.string().min(1).max(80),V.union([V.string().max(500),V.number().finite(),V.boolean(),V.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),nu=V.object({key:kt,name:V.string().trim().min(1).max(80),description:V.string().trim().max(240),type:V.enum(["boolean","metered"]),usageType:V.enum(["consumable","non_consumable"]).optional()}),iP=nu.extend({...we.shape,id:V.string().min(1),archived:V.boolean(),createdAt:V.iso.datetime()}),ru=V.object({amountCents:V.number().int().min(0).max(1e8),currency:se,interval:V.enum(["free","month","year"]),currencyOptions:V.partialRecord(se,V.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C"),sh=V.object({featureId:V.string().min(1),allowance:V.number().int().min(0).max(1e9).nullable(),pooled:V.boolean().optional()}),iu=V.object({name:V.string().trim().min(1).max(80),description:V.string().trim().max(240),price:ru,membership:Ja.optional(),trial:Za.nullable().optional(),licenses:V.array(Qa).max(20).optional(),items:V.array(sh).max(100).refine(e=>new Set(e.map(t=>t.featureId)).size===e.length,"\u540C\u4E00\u529F\u80FD\u4E0D\u80FD\u91CD\u590D\u52A0\u5165\u5957\u9910")}),aP=V.object({key:kt,config:iu}),oP=we.extend({id:V.string().min(1),key:kt,draft:iu,status:V.enum(["draft","published","archived"]),publishedVersionId:V.string().nullable(),isDefault:V.boolean(),updatedAt:V.iso.datetime()}),ch=nu.pick({key:!0,name:!0,type:!0}).extend({featureId:V.string(),allowance:V.number().int().min(0).max(1e9).nullable(),pooled:V.boolean().optional()}).refine(e=>e.type==="boolean"?e.allowance===null:e.allowance!==null,"\u5F00\u5173\u578B\u65E0\u6570\u91CF\uFF0C\u8BA1\u91CF\u578B\u5FC5\u987B\u6307\u5B9A\u989D\u5EA6"),au=we.extend({id:V.string().min(1),planId:V.string().min(1),variant:V.object({basePlanId:V.uuid(),baseVersionId:V.uuid()}).nullable(),version:V.number().int().positive(),name:V.string(),description:V.string(),price:ru,membership:Ja.optional(),trial:Za.nullable().optional(),licenses:V.array(Qa).optional(),items:V.array(ch),publishedAt:V.iso.datetime()}).strict(),Xa=V.object({startsAt:V.iso.datetime(),endsAt:V.iso.datetime().nullable()}).refine(e=>e.endsAt===null||Date.parse(e.endsAt)>Date.parse(e.startsAt),"\u5230\u671F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u751F\u6548\u65F6\u95F4"),sP=we.extend({id:V.string(),customerId:V.string(),planVersionId:V.string(),assignedAt:V.iso.datetime(),source:V.literal("demo"),validity:Xa.nullable().default(null),used:V.record(V.string(),V.number().int().min(0))}),cP=we.extend({id:V.string(),customerId:V.string(),at:V.iso.datetime(),message:V.string()});import{z as O}from"zod/v4";import{z as uh}from"zod/v4";var ou=uh.registry();var{AppEnv:xi}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:su}={IGNORE_PAST_DUE_DESCRIPTION:"If true, entitlements attached to this plan will still reset on schedule even when the customer's product is in a past_due state."},{PurchaseLimitInterval:lh}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:dh}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(O),{ResetInterval:Dr}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ResetInterval:e}})(),{USAGE_LIMIT_ANCHORS:mh}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:ph}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:fh}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:hh}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:gh}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(O),{BALANCE_BASES:_h}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:cu}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:za}=(e=>({DbOverageAllowedSchema:e.object({feature_id:e.string().meta({description:"The feature ID this overage allowed control applies to."}),enabled:e.boolean().default(!1).meta({description:"Whether overage is allowed for this feature."})})}))(O),{ProductMetadataSchema:Hn}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(O),{findDuplicate:bh}={findDuplicate:t=>{let n=new Set;for(let r of t){if(n.has(r))return r;n.add(r)}}},{BillingInterval:zt}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:eo}=(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')."})})}))(O),{withSpecDefault:Fr}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(ou),{COMMON:uu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:yh}={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:Sh}=(e=>({COMMON_SET:new Set(e)}))(uu),{hasNoDuplicateCurrencies:lu}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:du}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:to}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(O),{Infinite:Ai}={Infinite:"inf"},{TierBehavior:Ur}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Oi}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:mu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:vh}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:Pi}=(()=>{var e;return(function(t){t.BillImmediately="bill_immediately",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.BillNextCycle="bill_next_cycle"})(e||(e={})),{OnIncrease:e}})(),{OnDecrease:Ci}=(()=>{var e;return(function(t){t.Prorate="prorate",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.None="none",t.NoProrations="no_prorations"})(e||(e={})),{OnDecrease:e}})(),{RolloverExpiryDurationType:no}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:pu}=(()=>{var e;return(function(t){t.Day="day",t.Week="week",t.Month="month",t.Year="year"})(e||(e={})),{EntitlementDuration:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Ih}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:xh}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:ro}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(O),{ApiCreditTierSchema:fu}=(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."})})}))(O),{VIOLATION_MESSAGES:Ah}={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:hu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(O),{ModelMarkupsSchema:io}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(O,hu),{additionalCurrencyPlanItemIssues:gu}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let n=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&n.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let r=t.tiers;if(r&&r.length>0){let i=o=>(o.additional_currencies??[]).map(s=>s.currency.toLowerCase()),a=new Set(r.flatMap(i));a.size>0&&(r.every(s=>{let c=new Set(i(s));return c.size===a.size&&[...a].every(u=>c.has(u))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:ao}=((e,t,n,r,i)=>({PlanItemFilterSchema:e.object({feature_id:e.string().optional().meta({description:"Match items linked to this feature."}),billing_method:e.enum(t).optional().meta({description:"Match items with this billing method (prepaid or usage_based)."}),interval:e.union([e.enum(n),e.enum(r)]).optional().meta({description:"Match items with this interval. Accepts either a BillingInterval (price-side) or a ResetInterval (reset-side, includes day/hour/minute) so price-less items keyed by reset.interval can be disambiguated."}),interval_count:e.number().int().positive().optional().meta({description:"Match items with this interval_count. Disambiguates between items that share an interval but differ in count."}),included:i.optional().meta({description:"Match items whose grant equals this included usage. Omitted is a wildcard."})}).refine(o=>o.feature_id!==void 0||o.billing_method!==void 0||o.interval!==void 0||o.interval_count!==void 0,{message:"PlanItemFilter must have at least one field set."}).meta({title:"PlanItemFilter",description:"Filter for matching plan items. All provided fields must match (AND)."})}))(O,Oi,zt,Dr,to),{UpdatePlanItemParamsV1Schema:Oh}=((e,t,n)=>({UpdatePlanItemParamsV1Schema:e.object({filter:t.meta({description:"Filter selecting which existing plan item(s) to update. Same shape as remove_items filters."}),included:e.number().nonnegative().optional().meta({description:"Override the matched item's included usage / allowance. Existing usage carries forward."}),interval:e.enum(n).optional().meta({description:"Override the matched item's reset interval. Use 'one_off' for non-resetting balances."})}).meta({title:"UpdatePlanItem",description:"Deprecated. Use remove_items and add_items to replace plan items.",deprecated:!0})}))(O,ao,Dr),{FreeTrialDuration:Mr}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:Ph}=((e,t)=>({laneParam:({schema:r,description:i})=>e({schema:t.array(r).optional(),defaultValue:[],description:i})}))(Fr,O),{findDuplicateInControls:Ch}={findDuplicateInControls:({controlKey:t,controls:n,rule:r})=>{let i=new Set;for(let[a,o]of n.entries()){let s=r.identityOf(o);if(s!==void 0){if(i.has(s))return{code:"custom",message:r.message,input:o[r.field],path:[t,a,r.field]};i.add(s)}}}},{featureIdIdentity:wh}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:_u}={usageLimitFilterKey:t=>t?.properties?Object.entries(t.properties).map(([n,r])=>[n,String(r)]).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${n}=${r}`).join("&"):""},{usageAlertIdentity:Eh}=((e,t)=>({usageAlertIdentity:r=>[r.feature_id??"",r.basis??e,t(r.filter),r.threshold_type,r.threshold].join("|")}))(cu,_u),{RemovePlanLicenseSchema:Th}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(O),{ApiStripePriceProcessorSchema:Rh}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(O),{ApiFeatureType:jh}=(()=>{var e;return(function(t){t.Static="static",t.Boolean="boolean",t.SingleUsage="single_use",t.ContinuousUse="continuous_use",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{ApiFeatureType:e}})(),{ApiStripePlanProcessorSchema:Nh}=(e=>({ApiStripePlanProcessorSchema:e.object({product_id:e.string().meta({description:"Stripe product ID this plan is billed under."}),additional_product_ids:e.array(e.string()).optional().meta({description:"Extra Stripe product IDs aliased to this plan."})})}))(O),{ApiRevenueCatProductSchema:kh}=(e=>({ApiRevenueCatProductSchema:e.object({product_id:e.string().meta({description:"RevenueCat product ID that grants this plan when purchased."}),feature_quantities:e.array(e.object({feature_id:e.string(),quantity:e.number().nonnegative().optional()})).optional().meta({description:"Prepaid quantities granted when this specific RevenueCat product is purchased, in feature units."})})}))(O),{TrialOnEnd:wi}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:Dh}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:Fh}=(()=>{var e;return(function(t){t.Activate="activate",t.Upgrade="upgrade",t.Downgrade="downgrade",t.None="none",t.Purchase="purchase"})(e||(e={})),{AttachAction:e}})(),{AttachScenario:Uh}=(()=>{var e;return(function(t){t.Scheduled="scheduled",t.Active="active",t.New="new",t.Renew="renew",t.Upgrade="upgrade",t.UpdatePrepaidQuantity="update_prepaid_quantity",t.Downgrade="downgrade",t.Cancel="cancel",t.Expired="expired",t.PastDue="past_due"})(e||(e={})),{AttachScenario:e}})(),{UsageWindowDimensionSchema:Mh}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(O),{UsageWindowScopeSchema:Bh}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(O),{EntInterval:bu}=(()=>{var e;return(function(t){t.Lifetime="lifetime",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{EntInterval:e}})(),{FeatureType:Lh}=(()=>{var e;return(function(t){t.Boolean="boolean",t.Metered="metered",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{FeatureType:e}})(),{FeatureStripeMeterSchema:Vh}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(O),{FreeTrialSchema:qh}=((e,t,n)=>({FreeTrialSchema:e.object({id:e.string(),duration:e.enum(t),length:e.number(),unique_fingerprint:e.boolean(),created_at:e.number(),internal_product_id:e.string(),is_custom:e.boolean(),card_required:e.boolean(),on_end:e.enum(n).nullish()})}))(O,Mr,wi),{BillingType:$h}=(()=>{var e;return(function(t){t.OneOff="one_off",t.FixedCycle="fixed_cycle",t.UsageBelowThreshold="usage_below_threshold",t.UsageInAdvance="usage_in_advance",t.UsageInArrear="usage_in_arrear",t.InArrearProrated="in_arrear_prorated"})(e||(e={})),{BillingType:e}})(),{UsageTierSchema:oo}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).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"]}).transform(r=>({...r,amount:r.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(O,Ai),{IgnoredFixedPriceMetadataSchema:Gh}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(O),{BillWhen:Kh}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:yu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:Hh}=((e,t,n)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(n).default(n.ProrateImmediately)})}))(O,Pi,Ci),{AllowanceType:Wh}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Su}=((e,t)=>({RolloverConfigSchema:e.object({max:e.number().nullable().optional(),max_percentage:e.number().nullable().optional(),duration:e.enum(t).default(t.Month),length:e.number()})}))(O,no),{CreditDimensionBaseSchema:Qh}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(O,ro),{flatCreditRateShape:vu}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(O),{CreditTierSchema:Zh}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(O),{CreditMultiplierSchema:Yh}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(O,ro),{idRegex:Ei}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Iu}={descriptions:{id:"The ID of the product. Used to identify the product in other API calls like checkout or update product.",name:"The name of the product",description:"The description of the product",is_add_on:"Whether the product is an add-on. Add-on products can be attached multiple times and don't to through upgrade / downgrade flows.",is_default:"Whether the product is the default product. Default products are enabled by default for new customers.",group:"Product group which this product belongs to. Products within a group have upgrade / downgrade logic when the customer moves between them.",items:"Array of product items that define the product's features and pricing",free_trial:"Free trial configuration for this product, if available",metadata:"Arbitrary key-value metadata for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Metadata is shared across all versions of a plan.",archived:"Archive this product using this flag. Archived products are hidden on the dashboard."}},{ProductItemType:Jh}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:Xh}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:zh}=(()=>{var e;return(function(t){t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ProductItemInterval:e}})(),{UsageModel:eg}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:tg}={TierInfinite:"inf"},{CreateFreeTrialSchema:xu}=((e,t,n)=>({CreateFreeTrialSchema:e.object({length:e.string().or(e.number()).transform(i=>Number(i)).refine(i=>i>0,{message:"Free trial length must be greater than 0"}),unique_fingerprint:e.boolean().default(!1),duration:e.enum(t).default(t.Day),card_required:e.boolean().default(!0),on_end:e.enum(n).nullish()})}))(O,Mr,wi),{ProductConfigParamsSchema:so}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(O,Fr,su),{CREATE_PRODUCT_EXAMPLE:ng}={CREATE_PRODUCT_EXAMPLE:{id:"Pro Product",name:"Pro Plan",is_add_on:!1,is_default:!1,items:[{price:20,interval:"month"},{feature_id:"messages",included_usage:1e3,price:.5,interval:"month",usage_model:"pay_per_use"}],free_trial:{duration:"day",length:7,unique_fingerprint:!1,card_required:!0}}},{ApiFreeTrialSchema:rg}=((e,t,n)=>({ApiFreeTrialSchema:e.object({duration:e.enum(t).meta({description:"The duration type of the free trial"}),length:e.number().meta({description:"The length of the duration type specified"}),unique_fingerprint:e.boolean().meta({description:"Whether the free trial is limited to one per customer fingerprint"}),card_required:e.boolean().meta({description:"Whether the free trial requires a card. If false, the customer can attach the product without going through a checkout flow or having a card on file."}),on_end:e.enum(n).nullish().meta({description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."}),trial_available:e.boolean().default(!0).nullish().meta({description:"Used in customer context. Whether the free trial is available for the customer if they were to attach the product."})})}))(O,Mr,wi),{CreateProductSchema:fP}=(e=>({CreateProductSchema:e.object({id:e.string(),name:e.string().min(1,"Product name cannot be empty").default("Untitled Product"),is_add_on:e.boolean().default(!1),is_default:e.boolean().default(!1),version:e.number().optional().default(1),group:e.string().optional().default("")})}))(O),{isUsageLimitBasisAlert:ig}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:Au}=(e=>({PromoCodeSchema:e.object({code:e.string(),global_max_redemption:e.number().positive().optional(),first_time_transaction:e.boolean().optional(),max_redemptions:e.number().positive().optional()})}))(O),{RewardType:Ou}=(()=>{var e;return(function(t){t.PercentageDiscount="percentage_discount",t.FixedDiscount="fixed_discount",t.FreeProduct="free_product",t.InvoiceCredits="invoice_credits",t.FeatureGrant="feature_grant"})(e||(e={})),{RewardType:e}})(),{CouponDurationType:Pu}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:Cu}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(O,Pu),{RewardTriggerEvent:ag}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:og}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:Ti}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(O,su),{PurchaseLimitIntervalEnum:sg}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(O,lh),{DbSpendLimitSchema:co}=((e,t)=>({DbSpendLimitSchema:e.object({feature_id:e.string().optional().meta({description:"Optional feature ID this spend limit applies to."}),enabled:e.boolean().default(!1).meta({description:"Whether the overage spend limit is enabled."}),limit_type:t.optional().meta({description:"How overage_limit is interpreted: an absolute overage cap (default) or a percentage of the main-plan allowance."}),overage_limit:e.number().min(0).optional().meta({description:"Overage cap for the feature: absolute units, or a percent (e.g. 120) when limit_type is usage_percentage."}),skip_overage_billing:e.boolean().optional().meta({description:"When true, overage for this feature is not posted to Stripe. Usage tracking and balance resets still behave normally."})}).refine(r=>r.overage_limit===void 0&&r.skip_overage_billing===void 0||r.feature_id!==void 0,{message:"feature_id is required when overage_limit or skip_overage_billing is provided",path:["feature_id"]})}))(O,dh),{USAGE_LIMIT_INTERVALS:cg}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(Dr),{UsageLimitAnchorSchema:wu}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(O,mh),{UsageLimitFilterValueSchema:ug}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(O,fh),{USAGE_ALERT_BASES:lg}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(_h),{licensePatchIssues:dg}=(e=>({licensePatchIssues:({upsertLicenses:n=[]})=>{let r=e(n.map(i=>i.license_plan_id));return r===void 0?[]:[{message:`Duplicate license ${r} in upsert_licenses`,path:["upsert_licenses"]}]}}))(bh),{BasePriceSchema:mg}=((e,t,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(t).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."})})}))(O,zt,eo),{CURRENCY_CODES:pg}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(uu,yh,Sh),{AllocatedBillingFieldSchema:Eu}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).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'."})}))(O,mu),{EntitlementExpirySchema:Ri}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(O,pu),{CreditDimensionNameSchema:Tu}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(O,Ih,xh),{ApiCreditMatchSchema:Ru}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(ro),{findCreditTierViolations:fg}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Ah),{ApiCreditMultiplierSchema:hg}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,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."})}))(O,Ru),{ProviderMarkupsSchema:ju}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(O,hu),{planItemParamsIssues:gg}=((e,t,n,r,i)=>({planItemParamsIssues:o=>{let s=[],c=o.reset?.interval,u=o.price?.interval,l=o.reset?.interval_count??1,d=o.price?.interval_count??1;if(c&&u&&(String(c)!==String(u)||l!==d)&&o.price?.billing_method!==e.Prepaid&&s.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:o}),o.threshold_billing&&(!o.price||o.unlimited)&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing}),o.expiry&&(o.price?.billing_method===e.Prepaid&&String(o.price.interval)===String(t.OneOff)||s.push({message:"expiry is only supported on one-off prepaid items. Recurring items are already bounded by their reset cadence.",input:o.expiry}),o.entity_feature_id&&s.push({message:"expiry is not supported on entity-scoped items; each entity's balance would have to expire on its own clock.",input:o.expiry}),o.pooled&&s.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:o.expiry}),o.expiry.length<=0&&s.push({message:"expiry.length must be greater than 0",input:o.expiry})),o.price){o.threshold_billing&&o.price.billing_method!==e.UsageBased&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing});let{amount:g,tiers:m}=o.price;o.threshold_billing&&m?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:o.threshold_billing});let h=o.price.billing_method===e.UsageBased&&o.price.allocated_billing===n.ProratedLegacy;o.proration&&o.price.billing_method!==e.Prepaid&&!h&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:o.proration});let y=typeof g=="number",x=Array.isArray(m)&&m.length>0;y||x?y&&x&&s.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:o.price}):s.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:o.price})}if(o.price?.tiers){let g=o.price.tiers.some(m=>m.flat_amount&&m.flat_amount>0);g&&o.price.tier_behavior!==r.VolumeBased&&s.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:o.price}),g&&o.price.tiers.length<=1&&s.push({message:"flat_amount is not supported on single-tier pricing.",input:o.price}),o.price.tiers.some(m=>m.flat_amount!=null&&m.flat_amount<0)&&s.push({message:"flat_amount must be 0 or greater.",input:o.price}),o.price?.tier_behavior===r.VolumeBased&&o.price?.billing_method!==e.Prepaid&&s.push({message:"volume-based pricing is only supported for prepaid features.",input:o.price}),o.price?.tiers.length===0?s.push({message:"tiers cannot be empty.",input:o.price}):o.included&&typeof o.price?.tiers[0].to=="number"&&o.price?.tiers[0].to<=o.included&&s.push({message:"tiers[0].to must be greater than included.",input:o.price})}for(let g of i(o.price))s.push({message:g,input:o.price});return s}}))(Oi,zt,mu,Ur,gu),{FreeTrialParamsV1Schema:uo}=((e,t,n)=>({FreeTrialParamsV1Schema:e.object({duration_length:e.number().meta({description:"Number of duration_type periods the trial lasts."}),duration_type:e.enum(t).default(t.Month).meta({description:"Unit of time for the trial ('day', 'month', 'year')."}),card_required:e.boolean().default(!1).meta({description:"If true, a payment method is required to start the trial and the customer is charged when it ends. Defaults to false."}),on_end:n({schema:e.enum(["bill","revert"]).optional(),defaultValue:"bill",description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."})}).meta({title:"FreeTrialParams",description:"Free trial configuration for a plan."})}))(O,Mr,Fr),{duplicateCheck:_g}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(Ch),{usageLimitIdentity:lo}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(_u),{ApiPriceProcessorsSchema:Nu}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(O,Rh),{ApiFeatureV0Schema:ku}=((e,t)=>({ApiFeatureV0Schema:e.object({id:e.string().meta({description:"The ID of the feature, used to refer to it in other API calls like /track or /check."}),name:e.string().nullish().meta({description:"The name of the feature."}),type:e.enum(t).meta({description:"The type of the feature"}),display:e.object({singular:e.string().meta({description:"The singular display name for the feature."}),plural:e.string().meta({description:"The plural display name for the feature."})}).nullish().meta({description:"Singular and plural display names for the feature."}),credit_schema:e.array(e.object({metered_feature_id:e.string().meta({description:"The ID of the metered feature (should be a single_use feature)."}),credit_cost:e.number().meta({description:"The credit cost of the metered feature."})})).nullish().meta({description:"Credit cost schema for credit system features."}),archived:e.boolean().nullish().meta({description:"Whether or not the feature is archived."})})}))(O,jh),{ApiRevenueCatPlanProcessorSchema:bg}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(O,kh),{ApiFreeTrialV2Schema:yg}=((e,t,n)=>({ApiFreeTrialV2Schema:e.object({duration_length:e.number().meta({description:"Number of duration_type periods the trial lasts."}),duration_type:e.enum(t).meta({description:"Unit of time for the trial duration ('day', 'month', 'year')."}),card_required:e.boolean().meta({description:"Whether a payment method is required to start the trial. If true, customer will be charged after trial ends."}),on_end:e.enum(n).nullish().meta({description:"Behavior when the trial ends. 'bill' charges the customer (default). 'revert' expires the trial and restores the customer's previous plan."})})}))(O,Mr,wi),{CustomerEligibilitySchema:Sg}=((e,t,n,r)=>({CustomerEligibilitySchema:e.object({object:e.literal("customer_eligibility").optional().meta({internal:!0}),trial_available:e.boolean().optional().meta({description:"Whether the trial on this plan is available to this customer. For example, if the customer used the trial in the past, this will be false."}),status:e.enum(t).optional().meta({description:"The customer's current status with this plan. 'active' if attached, 'scheduled' if pending activation."}),canceling:e.boolean().optional().meta({description:"Whether the customer's active instance of this plan is set to cancel."}),trialing:e.boolean().optional().meta({description:"Whether the customer is currently on a free trial of this plan."}),attach_action:e.enum(n).meta({description:"The action that would occur if this plan were attached to the customer."}),scenario:e.enum(r).optional().meta({description:"Legacy attach scenario. Internal use only.",internal:!0})})}))(O,Dh,Fh,Uh),{UsageWindowLimitSchema:hP}=((e,t,n,r,i)=>({UsageWindowLimitSchema:e.object({feature_id:e.string(),internal_feature_id:e.string(),internal_customer_id:e.string(),key:e.string(),dimension_type:t,dimension_feature_id:e.string().nullable(),scope_type:n,entity_id:e.string().nullable(),internal_entity_id:e.string().nullable(),filter_key:e.string().nullable(),filter_properties:e.record(e.string(),e.string()).nullable(),interval:e.enum(r),window_start_at:e.number(),window_end_at:e.number(),limit:e.number(),anchor_customer_entitlement_id:e.string().nullable(),anchor_mode:i.default("billing_cycle"),new_window_id:e.string().optional()})}))(O,Mh,Bh,bu,wu),{FeatureSchema:vg}=((e,t,n,r,i)=>({FeatureSchema:e.object({internal_id:e.string(),org_id:e.string(),created_at:e.number(),env:e.nativeEnum(t),id:e.string().nonempty("Features must have an ID"),name:e.string().nonempty("Features must have a name"),type:e.nativeEnum(n,{message:"Features must have a type"}),config:e.any(),display:e.object({singular:e.string().optional(),plural:e.string().optional()}).nullish(),archived:e.boolean(),event_names:e.array(e.string()).default([]),model_markups:r.nullish(),stripe_meter:i.nullish(),stripe_product_id:e.string().nullish()})}))(O,xi,Lh,io,Vh),{PriceCurrencyConfigSchema:Du}=((e,t)=>({PriceCurrencyConfigSchema:e.object({amount:e.number().nullish(),usage_tiers:e.array(t).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish()})}))(O,oo),{UsagePriceConfigSchema:Ig}=((e,t,n,r,i,a)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(a).optional()})}))(O,Kh,oo,zt,Du,yu),{graduatedCreditRateShape:Fu}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(O,Zh),{FeatureMarkupsOverrideSchema:xg}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(O,ju,io),{usageAlertTargetLimitIdentity:Ag}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(lo),{DiscountConfigSchema:Uu}=((e,t)=>({DiscountConfigSchema:e.object({discount_value:e.number(),duration_type:e.nativeEnum(t),duration_value:e.number(),should_rollover:e.boolean().optional(),apply_to_all:e.boolean().optional(),price_ids:e.array(e.string()).optional(),product_ids:e.array(e.string()).optional()})}))(O,Pu),{RewardEntitlementSchema:Mu}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(O,Ri),{UpdateRewardSchema:gP}=((e,t,n,r,i,a)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(n).optional(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(a).nullish()})}))(O,Au,Ou,Uu,Cu,Mu),{CreateRewardProgram:_P}=((e,t,n)=>({CreateRewardProgram:e.object({id:e.string(),when:e.enum(t),product_ids:e.array(e.string()).optional(),exclude_trial:e.boolean().optional(),internal_reward_id:e.string(),max_redemptions:e.number().optional(),received_by:e.enum(n)})}))(O,ag,og),{AutoTopupPurchaseLimitSchema:Bu}=((e,t)=>({AutoTopupPurchaseLimitSchema:e.object({interval:t.meta({description:"The time interval for the purchase limit window."}),interval_count:e.number().min(1).default(1).meta({description:"Number of intervals in the purchase limit window."}),limit:e.number().min(1).meta({description:"Maximum number of auto top-ups allowed within the interval."})})}))(O,sg),{UsageLimitFilterSchema:Lu}=((e,t,n,r)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),n).meta({description:"Event property equality conditions. A usage event counts toward this cap only when every listed property matches (AND)."}).check(a=>{let o=Object.keys(a.value).length;(o<1||o>r)&&a.issues.push({code:"custom",message:`filter.properties must have between 1 and ${r} keys`,input:a.value})})})}))(O,ph,ug,hh),{UsageAlertBasisSchema:Og}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(O,lg),{refineCustomizePlanV1Schema:Vu}=(e=>({refineCustomizePlanV1Schema:(n,{includeItems:r=!0,includeFreeTrial:i=!0,includeUpdateItems:a=!0,includeLicenses:o=!0}={})=>{let s=["price",r&&"items","add_items","remove_items",a&&"update_items",i&&"free_trial","billing_controls",o&&"upsert_licenses",o&&"remove_licenses"].filter(Boolean),c=u=>u==="update_items"?"deprecated update_items":u;return n.refine(u=>s.some(l=>u[l]!==void 0),{message:`When using customize, at least one of ${s.map(c).join(", ")} must be provided`}).superRefine((u,l)=>{if(o)for(let d of e({upsertLicenses:u.upsert_licenses}))l.addIssue({code:"custom",...d})}).refine(u=>!(u.items!==void 0&&(u.add_items!==void 0||u.remove_items!==void 0||a&&u.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",a?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(dg),{SUPPORTED_SET:Pg}=(e=>({SUPPORTED_SET:new Set(e)}))(pg),{ApiCreditDimensionBaseSchema:Cg}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(O,Ru),{refineGraduatedTiers:qu}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(fg),{ApiFeatureMarkupsOverrideSchema:wg}=((e,t,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:t.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."})})}))(O,ju,io),{AutoTopupPurchaseLimitParamsSchema:Eg}=((e,t)=>({AutoTopupPurchaseLimitParamsSchema:e.extend({count:t.number().min(0).optional().meta({description:"Set the current window's consumed auto top-up count. Omit to leave runtime state unchanged."})})}))(Bu,O),{DUPLICATE_CHECKS:Tg}=((e,t,n,r)=>({DUPLICATE_CHECKS:[e({controlKey:"auto_topups",identityOf:t,field:"feature_id",message:"Only one auto top-up entry is allowed per feature_id"}),e({controlKey:"spend_limits",identityOf:t,field:"feature_id",message:"Only one spend limit entry is allowed per feature_id"}),e({controlKey:"usage_limits",identityOf:n,field:"feature_id",message:"Only one usage limit entry is allowed per feature_id and filter"}),e({controlKey:"usage_alerts",identityOf:r,field:"threshold",message:"Only one usage alert entry is allowed per feature_id, basis, filter, threshold_type and threshold"}),e({controlKey:"overage_allowed",identityOf:t,field:"feature_id",message:"Only one overage_allowed entry is allowed per feature_id"})]}))(_g,wh,lo,Eh),{ApiPlanProcessorsSchema:Rg}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(O,Nh,bg),{FixedPriceConfigSchema:jg}=((e,t,n,r,i)=>({FixedPriceConfigSchema:e.object({type:e.string(),amount:e.number().min(0),interval:e.enum(t),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),n).nullish(),billing_units:e.number().nullish(),usage_tiers:e.array(r).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),feature_id:i,internal_feature_id:i})}))(O,zt,Du,oo,Gh),{CreditDimensionSchema:Ng}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(O,Qh,vu,Fu),{filterUnresolvableUsageLimitAlerts:kg}=((e,t,n)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:a})=>{let o=new Set(a.flatMap(s=>(s??[]).map(e)));return i.flatMap((s,c)=>t(s)&&!o.has(n(s))?[{index:c,usageAlert:s}]:[])}}))(lo,ig,Ag),{CreateRewardSchema:bP}=((e,t,n,r,i,a)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(n).nullish(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(a).nullish()}).refine(s=>s.type!==n.FeatureGrant?!0:s.entitlements&&s.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(s=>s.type!==n.FeatureGrant?!0:s.promo_codes.some(c=>c.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(O,Au,Ou,Uu,Cu,Mu),{AutoTopupSchema:mo}=((e,t)=>({AutoTopupSchema:e.object({feature_id:e.string().meta({description:"The ID of the feature (credit balance) to auto top-up."}),enabled:e.boolean().default(!1).meta({description:"Whether auto top-up is enabled."}),threshold:e.number().meta({description:"When the balance drops below this threshold, an auto top-up will be purchased."}),quantity:e.number().min(1).meta({description:"Amount of credits to add per auto top-up."}),purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur."}),invoice_mode:e.boolean().optional().meta({description:"When true, auto top-up creates a send_invoice invoice instead of auto-charging."})})}))(O,Bu),{DbUsageLimitSchema:po}=((e,t,n,r)=>({DbUsageLimitSchema:e.object({feature_id:e.string().meta({description:"The feature this usage limit applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage limit is enabled."}),limit:e.number().min(0).meta({description:"Maximum units allowed per interval."}),interval:e.enum(t).meta({description:"Interval for the cap, aligned to the customer's billing cycle."}),anchor:n.optional().meta({description:"Window alignment. 'billing_cycle' phases the interval to the customer's renewal time; 'utc' aligns to the UTC calendar."}),filter:r.optional().meta({description:"When set, only usage from events whose properties match counts toward this cap. Omit to count all usage of the feature."})})}))(O,cg,wu,Lu),{DbUsageAlertSchema:fo}=((e,t,n,r,i)=>({DbUsageAlertSchema:e.object({feature_id:e.string().optional().meta({description:"The feature ID this alert applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage alert is enabled."}),threshold:e.number().min(0).meta({description:"The threshold value that triggers the alert. For usage or remaining, this is an absolute count. For usage_percentage or remaining_percentage, this is a percentage (0-100)."}),threshold_type:t.meta({description:"Whether the threshold is an absolute count or a percentage of the usage allowance or remaining balance."}),basis:n.default(r).meta({description:"What 100% means. balance: every grant on the feature. included: the plan allowance only. recurring: grants that reset. usage_limit: the cap of the usage limit with the same feature and filter."}),filter:i.optional().meta({description:"Only valid with basis usage_limit. Points the alert at the usage limit carrying the same filter."}),name:e.string().optional().meta({description:"Optional user-defined label to distinguish multiple alerts on the same feature."})}).check(o=>{let{feature_id:s,threshold_type:c,threshold:u,basis:l,filter:d}=o.value;c==="remaining_percentage"&&u>100&&o.issues.push({code:"custom",input:u,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),l==="usage_limit"&&!s&&o.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&l!=="usage_limit"&&o.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(O,gh,Og,cu,Lu),{isValidCurrencyCode:Dg}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Pg),{ApiCreditDimensionSchema:Fg}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(O,Cg,fu,qu),{AutoTopupParamsSchema:Ug}=((e,t)=>({AutoTopupParamsSchema:e.extend({purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur. Pass count to set the current window's consumed top-ups."})})}))(mo,Eg),{findDuplicateBillingControlIssue:Mg}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(Tg),{CustomerBillingControlsSchema:ho}=((e,t,n,r,i,a)=>({CustomerBillingControlsSchema:e.object({auto_topups:e.array(t).optional().meta({description:"List of auto top-up configurations per feature."}),spend_limits:e.array(n).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(r).optional().meta({description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:e.array(i).optional().meta({description:"List of usage alert configurations per feature."}),overage_allowed:e.array(a).optional().meta({description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})})}))(O,mo,co,po,fo,za),{PriceSchema:Bg}=((e,t,n,r,i,a)=>({PriceSchema:e.object({id:e.string(),internal_product_id:e.string().nullable(),org_id:e.string().optional(),created_at:e.number().optional(),billing_type:e.nativeEnum(t).nullish(),tier_behavior:e.nativeEnum(n).nullish(),is_custom:e.boolean().optional(),config:r.or(i),entitlement_id:e.string().nullish(),proration_config:a.nullable()})}))(O,$h,Ur,jg,Ig,Hh),{CreditSchemaItemBaseSchema:$u}=((e,t,n,r)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,n).optional(),multipliers:e.record(t,r).optional()})}))(O,Tu,Ng,Yh),{GraduatedCreditSchemaItemSchema:Lg}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))($u,Fu),{UpdateProductSchema:yP}=((e,t,n)=>({UpdateProductSchema:e.object({id:e.string().nullish(),name:e.string().min(1,"Product name cannot be empty").optional(),description:e.string().nullish(),is_add_on:e.boolean().optional(),is_default:e.boolean().optional(),group:e.string().nullish(),archived:e.boolean().optional(),config:t.partial().optional(),billing_controls:n.optional()})}))(O,Ti,ho),{DbBillingControlsSchema:Vg}=((e,t,n,r,i,a)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(n).nullish(),usage_limits:e.array(r).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(a).nullish()})}))(O,mo,co,po,fo,za),{CurrencyCodeSchema:Gu}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(O,Dg),{AdditionalCurrencyTierSchema:qg}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,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"]})}))(O,Gu),{ApiCreditSchemaItemBaseSchema:Ku}=((e,t,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(t,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(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(O,Tu,Fg,hg),{ApiFlatCreditSchemaItemSchema:$g}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Ku,O),{rejectDuplicateBillingControls:Gg}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(Mg),{FlatCreditSchemaItemSchema:Kg}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))($u,vu),{ProductSchema:Hg}=((e,t,n,r,i)=>({ProductSchema:e.object({id:e.string(),name:e.string().min(1,"Product name cannot be empty"),description:e.string().nullable(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number(),version_slug:e.string().nullable().default(null),active:e.boolean().default(!1),deleted_at:e.number().nullable().default(null),previous_version_slug:e.string().nullable().default(null),group:e.string(),env:e.enum(t),internal_id:e.string(),org_id:e.string(),created_at:e.number(),processor:e.object({type:e.string(),id:e.string(),additional_ids:e.array(e.string()).optional()}).nullish(),base_variant_id:e.string().nullable(),base_internal_product_id:e.string().nullish(),archived:e.boolean().default(!1),config:n.default(()=>({ignore_past_due:!1})),...r.shape,metadata:i.default(()=>({}))})}))(O,xi,Ti,Vg,Hn),{AdditionalCurrencyPriceSchema:Wg}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(O,Gu),{AdditionalCurrencyTierArraySchema:Hu}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(O,qg,lu,du),{ApiGraduatedCreditSchemaItemSchema:Qg}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Ku,O,fu,qu),{CustomerBillingControlsParamsSchema:ji}=((e,t,n,r,i,a,o,s)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:n,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:r,description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:t({schema:i,description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:t({schema:a,description:"List of usage alert configurations per feature."}),overage_allowed:t({schema:o,description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})}).check(s)}))(O,Ph,Ug,co,po,fo,za,Gg),{CreditSchemaItemSchema:Zg}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(O,Kg,Lg),{PriceTierSchema:Yg}=((e,t,n)=>({PriceTierSchema:e.object({to:e.number().or(e.literal(t)).meta({description:"The maximum amount of usage for this tier.",example:100}),amount:e.number().optional().meta({description:"The price of the product item for this tier.",example:10}),flat_amount:e.number().optional().meta({description:"A flat fee charged for this tier, in addition to the per-unit amount."}),additional_currencies:n.nullish().meta({description:"Per-currency amounts for this tier. Boundaries ('to') are shared across currencies."})}).refine(i=>i.amount!=null||i.flat_amount!=null,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0}))}))(O,tg,Hu),{PlanBillingControlsParamsSchema:Jg}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(r=>{let i=t({usageAlerts:r.value.usage_alerts??[],usageLimitLists:[r.value.usage_limits??[]]});for(let{index:a,usageAlert:o}of i)r.issues.push({code:"custom",message:`No usage limit on this plan matches the usage_limit alert for feature ${o.feature_id}`,input:o,path:["usage_alerts",a,"basis"]})})}))(ji,kg),{AdditionalCurrencyPriceArraySchema:Br}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(O,Wg,lu,du),{ApiUsageTierWithCurrenciesSchema:Wu}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),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(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(O,Ai,Hu),{ApiCreditSchemaItemSchema:Xg}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(O,Qg,$g),{FeatureConfigOverrideSchema:Qu}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(O,Zg,xg),{ProductItemConfigSchema:zg}=((e,t,n,r,i,a,o)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:a.nullish(),feature_override:o.nullish()})}))(O,yu,Pi,Ci,Su,Ri,Qu),{BasePriceParamsSchema:Ni}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({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."})}))(mg,Fr,O,Br),{PlanItemPriceParamsSchema:e_}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??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:t.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(i).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(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,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."})})}))(O,Br,Wu,Ur,zt,Oi,Eu),{ApiFeatureOverrideSchema:Zu}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).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."})})}))(O,Xg,wg),{ApiPlanItemV1Schema:t_}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m,h,y)=>({ApiPlanItemV1Schema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature this item configures."}),feature:t.optional().meta({description:"The full feature object if expanded."}),included:e.number().meta({description:"Number of free units included. For consumable features, balance resets to this number each interval."}),unlimited:e.boolean().meta({description:"Whether the customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"The interval at which the feature balance resets (e.g. 'month', 'year'). For consumable features, usage resets to 0 and included units are restored."}),interval_count:e.number().optional().meta({description:"Number of intervals between resets. Defaults to 1."})}).nullable().meta({description:"Reset configuration for consumable features. Null for non-consumable features like seats where usage persists across billing cycles."}),price:e.object({amount:e.number().optional().meta({description:"Price per billing_units after included usage is consumed. Mutually exclusive with tiers."}),additional_currencies:r.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' (tiered prices carry per-currency amounts on each tier)."}),tiers:e.array(i).optional().meta({description:"Tiered pricing configuration. Each tier's 'to' INCLUDES the included amount. Either 'tiers' or 'amount' is required."}),tier_behavior:e.enum(a).optional(),interval:e.enum(o).meta({description:"Billing interval for this price. For consumable features, should match reset.interval."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().meta({description:"Number of units per price increment. Usage is rounded UP to the nearest billing_units when billed (e.g. billing_units=100 means 101 usage rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:c,max_purchase:e.number().nullable().meta({description:"Maximum units a customer can purchase beyond included. E.g. if included=100 and max_purchase=300, customer can use up to 400 total before usage is capped. Null for no limit."}),processors:u.optional().meta({description:"Payment processors this item price is connected to. Omitted when unset."})}).nullable().meta({description:"Pricing configuration for usage beyond included units. Null if feature is entirely free."}),display:l.optional().meta({description:"Display text for showing this item in pricing pages."}),rollover:e.object({max:e.number().nullable().meta({description:"Maximum rollover units. Null for unlimited rollover."}),max_percentage:e.number().nullable().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(d).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover configuration for unused units. If set, unused included units roll over to the next period."}),proration:e.object({on_increase:e.enum(p).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(g).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry:m.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:h.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),mapping_identity:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})}).check(v=>{let E=v.value.reset?.interval,A=v.value.price?.interval,S=v.value.reset?.interval_count??1,q=v.value.price?.interval_count??1;if(E&&A&&(String(E)!==String(A)||S!==q)&&v.value.price?.billing_method!==s.Prepaid&&v.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:v.value}),v.value!==void 0&&v.value.price!==void 0&&v.value.price!==null){v.value.price.amount&&v.value.price.tiers&&v.value.price.tiers.length>0&&v.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:v.value});for(let ge of y(v.value.price))v.issues.push({code:"custom",message:ge,input:v.value.price})}})}))(O,ku,Dr,Br,Wu,Ur,zt,Oi,Eu,Nu,eo,no,Pi,Ci,Ri,Zu,gu),{EntitlementSchema:n_}=((e,t,n,r,i,a)=>({EntitlementSchema:e.object({id:e.string(),created_at:e.number(),internal_feature_id:e.string(),internal_product_id:e.string().nullable(),internal_reward_id:e.string().nullish(),is_custom:e.boolean().default(!1),allowance_type:e.nativeEnum(t).optional().nullable(),allowance:e.number().nullish(),interval:e.nativeEnum(n).optional().nullable(),interval_count:e.number().default(1),carry_from_previous:e.boolean().default(!1).optional(),entity_feature_id:e.string().nullish(),pooled:e.boolean().default(!1).optional(),org_id:e.string().optional(),feature_id:e.string().optional(),usage_limit:e.number().nullable().optional().default(null),expiry_duration:e.nativeEnum(r).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:a.nullish()})}))(O,Wh,bu,pu,Su,Qu),{ProductItemSchema:Yu}=((e,t,n,r,i,a,o,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(O,Jh,Xh,ku,Ai,zh,eg,Yg,Br,Ur,zg),{ProductV2Schema:Ju}=((e,t,n,r,i,a,o)=>({ProductV2Schema:e.object({internal_id:e.string().nullish(),id:e.string(),name:e.string(),description:e.string().nullish(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number().default(1),version_slug:e.string().nullable().optional(),active:e.boolean().optional(),group:e.string().nullable(),env:e.nativeEnum(t),free_trial:n.nullish(),items:e.array(r),created_at:e.number(),stripe_id:e.string().nullish(),archived:e.boolean().default(!1).nullish(),base_internal_product_id:e.string().nullish(),base_id:e.string().nullish(),config:i.partial().optional(),billing_controls:a.optional(),metadata:o.optional()})}))(O,xi,rg,Yu,Ti,ho,Hn),{PlanItemParamsObjectSchema:r_}=((e,t,n,r,i,a,o,s,c,u,l)=>({PlanItemParamsObjectSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature to configure."}),included:t.optional().meta({description:"Number of free units included. Balance resets to this each interval for consumable features."}),unlimited:e.boolean().optional().meta({description:"If true, customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:r({schema:e.number().optional(),defaultValue:1,description:"Number of intervals between resets. Defaults to 1."})}).optional().meta({description:"Reset configuration for consumable features. Omit for non-consumable features like seats."}),price:i.optional().meta({description:a}),proration:e.object({on_increase:e.enum(o).meta({description:"Billing behavior when quantity increases mid-cycle."}),on_decrease:e.enum(s).meta({description:"Credit behavior when quantity decreases mid-cycle."})}).optional().meta({description:"Proration settings for prepaid features. Controls mid-cycle quantity change billing."}),rollover:e.object({max:e.number().optional().meta({description:"Max rollover units. Omit for unlimited rollover."}),max_percentage:e.number().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(c).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover config for unused units. If set, unused included units carry over."}),expiry:u.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:l.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})})}))(O,to,Dr,Fr,e_,vh,Pi,Ci,no,Ri,Zu),{FullProductWithoutLicensesSchema:SP}=((e,t,n,r,i,a)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(n),entitlements:t.array(r.extend({feature:i})),free_trial:a.nullish(),free_trials:t.array(a).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(Hg,O,Bg,n_,vg,qh),{CreateProductItemParamsSchema:Xu}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))(Yu,to,O,Ai),{CreatePlanItemParamsV1Schema:go}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(r=>{for(let{message:i,input:a}of t(r.value))r.issues.push({code:"custom",message:i,input:a})}).meta({title:"PlanItem",description:"Configuration for a feature item in a plan, including usage limits, pricing, and rollover settings."})}))(r_,gg),{LicenseCustomizeSchema:zu}=((e,t,n,r)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(n).optional(),remove_items:e.array(r).optional()})}))(O,Ni,go,ao),{PlanLicenseParamsSchema:_o}=((e,t)=>({PlanLicenseParamsSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(O,zu),{UpdateProductV2ParamsSchema:vP}=((e,t,n,r,i,a,o,s,c)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:n.id}),name:e.string().refine(l=>l.length>0,{message:"name must be a non-empty string"}).optional().meta({description:n.name}),is_add_on:e.boolean().optional().meta({description:n.is_add_on}),is_default:e.boolean().optional().meta({description:n.is_default}),base_plan_id:e.string().nonempty().regex(t).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."}),description:e.string().nullish().optional().meta({description:n.description}),group:e.string().nonempty().nullable().optional().meta({description:n.group}),archived:e.boolean().optional().meta({description:n.archived}),items:e.array(r).optional(),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata})})}))(O,Ei,Iu,Xu,_o,xu,so,ji,Hn),{CreatePlanParamsV1Schema:i_}=((e,t,n,r,i,a,o,s,c)=>({CreatePlanParamsV1Schema:e.object({id:e.string().nonempty().regex(t).meta({description:"Unique identifier for the plan."}),group:e.string().default("").meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),name:e.string().nonempty().meta({description:"Display name of the plan."}),description:e.string().nullable().default(null).meta({description:"Optional description of the plan."}),add_on:e.boolean().default(!1).meta({description:"If true, this plan can be attached alongside other plans. Otherwise, attaching replaces existing plans in the same group."}),auto_enable:e.boolean().default(!1).meta({description:"If true, plan is automatically attached when a customer is created. Use for free tiers."}),price:n.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(r).optional().meta({description:"Feature configurations for this plan. Each item defines included units, pricing, and reset behavior."}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.optional().meta({description:"Free trial configuration. Customers can try this plan before being charged."}),config:o.optional().meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:"Arbitrary key-value metadata defined by you for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Shared across all versions of the plan."}),create_in_stripe:e.boolean().default(!0).meta({internal:!0})})}))(O,Ei,Ni,go,_o,uo,so,Jg,Hn),{UpdatePlanParamsV1Schema:IP}=((e,t,n,r,i)=>({UpdatePlanParamsV1Schema:e.partial().extend({group:e.shape.group.removeDefault().optional(),version:t.number().optional(),archived:t.boolean().default(!1).optional(),price:n.nullable().optional().meta({description:"The price of the plan. Set to null to remove the base price."}),free_trial:r.nullable().optional().meta({description:"The free trial of the plan. Set to null to remove the free trial."}),base_plan_id:t.string().nonempty().regex(i).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."})})}))(i_,O,Ni,uo,Ei),{CustomizePlanLicenseSchema:bo}=((e,t)=>({CustomizePlanLicenseSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(O,zu),{CreateProductV2ParamsSchema:xP}=((e,t,n,r,i,a,o,s,c,u)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:n.id}),name:e.string().refine(d=>d.length>0,{message:"name must be a non-empty string"}).meta({description:n.name}),description:e.string().nullish().meta({description:n.description}),is_add_on:e.boolean().default(!1).meta({description:n.is_add_on}),is_default:e.boolean().default(!1).meta({description:n.is_default}),group:e.string().nullable().default("").meta({description:n.group}),items:e.array(r).optional().meta({description:n.items}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().default(null).meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata}),create_in_stripe:e.boolean().optional().meta({internal:!0}),archived:e.boolean().optional().meta({internal:!0}),base_internal_product_id:e.string().nullable().optional().meta({internal:!0})}).meta({examples:[u]})}))(O,Ei,Iu,Xu,_o,xu,so,ji,Hn,ng),{CustomizePlanV1BaseSchema:el}=((e,t,n,r,i,a,o,s,c)=>({CustomizePlanV1BaseSchema:e.object({price:t.nullable().optional().meta({description:"Override the base price of the plan. Pass null to remove the base price."}),items:e.array(n).optional().meta({description:"Override the items in the plan (PUT-style \u2014 replaces all existing items). Mutually exclusive with add_items / remove_items / deprecated update_items."}),add_items:e.array(n).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(r).optional().meta({description:"Filters selecting items to remove from the plan."}),update_items:e.array(i).optional().meta({description:"Deprecated. Use remove_items and add_items to replace matched plan items.",internal:!0,deprecated:!0}),free_trial:a.nullable().optional().meta({description:"Override the plan's default free trial. Pass an object to set a custom trial, or null to remove the trial entirely."}),billing_controls:o.optional().meta({description:"Override the plan's billing controls (auto top-ups, spend limits, usage limits, usage alerts, overage allowed) for this customer."}),upsert_licenses:e.array(s).optional().meta({description:"License links to add or override for this customer, keyed by license_plan_id. Omitted fields inherit the plan catalog link (included defaults to 1 when the license is not in the catalog). A bare entry restores the license to pure catalog inheritance."}),remove_licenses:e.array(c).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(O,Ni,go,ao,Oh,uo,ji,bo,Th),{VariantCustomizeSchema:a_}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(Vu,el),{DiffedCustomizePlanV1Schema:AP}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(Vu,el),{ApiPlanV1Schema:OP}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g)=>({ApiPlanV1Schema:e.object({id:e.string().meta({description:"Unique identifier for the plan."}),internal_id:e.string().nullable().optional().meta({description:"Stable row id. Survives renames of plan_id and version_slug, so config files address rows by it.",internal:!0}),name:e.string().meta({description:"Display name of the plan."}),description:e.string().nullable().meta({description:"Optional description of the plan."}),group:e.string().nullable().meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),version:e.number().meta({description:"Version number of the plan. Incremented when plan configuration changes."}),version_slug:e.string().nullable().optional().meta({description:"User-facing version identity. Defaults to v{n} when the version is minted."}),active:e.boolean().optional().meta({description:"Whether this is the active version of the plan. At most one version is active."}),add_on:e.boolean().meta({description:"Whether this is an add-on plan that can be attached alongside a main plan."}),auto_enable:e.boolean().meta({description:"If true, this plan is automatically attached when a customer is created. Used for free plans."}),price:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),additional_currencies:t.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),interval:e.enum(n).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0}),display:r.optional().meta({description:"Display text for showing this price in pricing pages."}),processors:i.optional().meta({description:"Payment processors this base price is connected to. Omitted when unset."})}).nullable().meta({description:"Base recurring price for the plan. Null for free plans or usage-only plans."}),items:e.array(a).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:o.optional().meta({description:"Payment processors this plan is connected to. Omitted when unset."}),free_trial:s.optional().meta({description:"Free trial configuration. If set, new customers can try this plan before being charged."}),created_at:e.number().meta({description:"Unix timestamp (ms) when the plan was created."}),env:e.enum(c).meta({description:"Environment this plan belongs to ('sandbox' or 'live')."}),archived:e.boolean().meta({description:"Whether the plan is archived. Archived plans cannot be attached to new customers."}),config:u.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:l.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:p.optional(),base_variant_id:e.string().nullable().meta({description:"Deprecated. Use variant_details.base_plan_id instead. If this is a variant, the ID of the base plan it was created from.",deprecated:!0}),variant_details:e.object({base_plan_id:e.string().meta({description:"The ID of the base plan this variant was derived from."}),customize:g.optional().meta({description:"The customization that transforms the base plan into this variant."})}).optional().meta({description:"Details about how this variant relates to its latest base plan."})})}))(O,Br,zt,eo,Nu,t_,Rg,yg,xi,Ti,ho,Hn,Sg,a_);import{z as P}from"zod";var o_=P.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),rl=P.enum(["single_use","continuous_use"]),yo=P.record(P.string(),P.union([P.string(),P.number(),P.boolean()]).transform(String).pipe(P.string())),tl=P.string().min(1).max(64).refine(e=>!e.includes("::")),il={credit_amount:P.number(),tier_behavior:P.never().optional(),tiers:P.never().optional()},al={credit_amount:P.never().optional(),tier_behavior:P.literal("graduated"),tiers:P.array(P.strictObject({to:P.union([P.number(),P.literal("inf")]),credit_amount:P.number()}))},s_=P.union([P.strictObject({match:yo,priority:P.number().int().optional(),...il}),P.strictObject({match:yo,priority:P.number().int().optional(),...al})]),c_=P.strictObject({match:yo,factor:P.number().positive().optional(),add:P.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),nl={metered_feature_id:P.string(),feature_amount:P.number().optional(),dimensions:P.record(tl,s_).optional(),multipliers:P.record(tl,c_).optional()},So=P.union([P.strictObject({...nl,...il}),P.strictObject({...nl,...al})]),Di=P.number().min(-100),ol=P.record(P.string(),P.strictObject({markup:Di})).nullish(),Fi=P.record(P.string().regex(/.+\/.+/),P.strictObject({markup:Di.optional(),input_cost:P.number().min(0).optional(),output_cost:P.number().min(0).optional()})).nullish(),u_=P.strictObject({default_markup:Di.optional(),provider_markups:ol,model_markups:Fi}),vo=P.strictObject({schema:P.array(So).optional(),markups:u_.optional()}),l_=P.strictObject({filters:P.array(P.strictObject({property:P.string(),operator:P.string(),value:P.array(P.string())})),aggregate:P.strictObject({type:P.string(),property:P.string().nullable()}),usage_type:rl}),sl=P.strictObject({schema:P.array(So).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:P.boolean().optional(),usage_type:rl.default("single_use").overwrite(()=>"single_use"),default_markup:Di.optional(),provider_markups:ol}),Io=sl.safeExtend({schema:P.array(So).length(0)}),ki={id:o_,name:P.string().min(1),display:P.strictObject({singular:P.string().optional(),plural:P.string().optional()}).nullish(),event_names:P.array(P.string()).default([]),model_markups:Fi,stripe_meter:P.strictObject({id:P.string(),event_name:P.string()}).nullish(),stripe_product_id:P.string().nullish()},xo=e=>P.discriminatedUnion("type",[P.strictObject({...ki,...e,type:P.literal("boolean"),config:P.null()}),P.strictObject({...ki,...e,type:P.literal("metered"),config:l_}),P.strictObject({...ki,...e,type:P.literal("credit_system"),config:sl}),P.strictObject({...ki,...e,type:P.literal("ai_credit_system"),config:Io})]),wP=xo({}),d_=P.strictObject({id:P.boolean(),type:P.boolean(),usage_type:P.boolean()}),m_={internal_id:P.uuid(),org_id:P.uuid(),created_at:P.number(),env:P.enum(["sandbox","live"]),archived:P.boolean(),project_id:P.uuid(),environment_id:P.uuid(),revision:P.number().int().nonnegative(),update_rules:d_},cl=xo(m_),EP=P.strictObject({rows:P.array(cl).max(200),nextCursor:P.uuid().nullable()}),ul=P.strictObject({features:P.array(cl).max(500),limited:P.boolean()}),TP=P.union([xo({action:P.literal("save"),internal_id:P.uuid().nullable(),revision:P.number().int().nonnegative()}),P.strictObject({action:P.enum(["archive","restore","delete"]),internal_id:P.uuid(),revision:P.number().int().nonnegative()})]);import{z as Wn}from"zod";var ll=Wn.number().int().min(0).max(1e8),Lr=Wn.strictObject({kind:Wn.enum(["graduated","volume"]),tiers:Wn.array(Wn.strictObject({upTo:Wn.number().int().min(1).max(1e4).nullable(),unitAmountMinor:ll,flatAmountMinor:ll.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function Ao(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?Lr.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function Ui(e){return Ao({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as R}from"zod";import{z as _}from"zod";import{z}from"zod";var dl={"zh-Hans":{once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{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:{once:"\u521D\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15",repeating:"\u6700\u521D\u306E {months} \u304B\u6708\u9593\u3001\u6BCE\u6708 {discount} \u5272\u5F15",forever:"\u6BCE\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15"},ko:{once:"\uCCAB \uACB0\uC81C {discount} \uD560\uC778",repeating:"\uCCAB {months}\uAC1C\uC6D4 \uB3D9\uC548 \uB9E4\uC6D4 {discount} \uD560\uC778",forever:"\uB9E4 \uACB0\uC81C {discount} \uD560\uC778"},es:{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:{once:"{discount} de r\xE9duction sur le premier paiement",repeating:"{discount} de r\xE9duction par mois pendant les {months} premiers mois",forever:"{discount} de r\xE9duction sur chaque paiement",repeatingOne:"{discount} de r\xE9duction pendant le premier mois"},de:{once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat f\xFCr die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por m\xEAs nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro m\xEAs"},it:{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:{once:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043F\u0435\u0440\u0432\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436",repeating:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043A\u0430\u0436\u0434\u044B\u0439 \u043C\u0435\u0441\u044F\u0446 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",repeatingOne:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u0432 \u043F\u0435\u0440\u0432\u044B\u0439 \u043C\u0435\u0441\u044F\u0446",forever:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043A\u0430\u0436\u0434\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436"},vi:{once:"Gi\u1EA3m {discount} cho l\u1EA7n thanh to\xE1n \u0111\u1EA7u ti\xEAn",repeating:"Gi\u1EA3m {discount} m\u1ED7i th\xE1ng trong {months} th\xE1ng \u0111\u1EA7u",forever:"Gi\u1EA3m {discount} cho m\u1ED7i l\u1EA7n thanh to\xE1n"},th:{once:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01",repeating:"\u0E25\u0E14 {discount} \u0E15\u0E48\u0E2D\u0E40\u0E14\u0E37\u0E2D\u0E19\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",forever:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E17\u0E38\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07"},id:{once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{once:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u062F\u0641\u0639\u0629 \u0627\u0644\u0623\u0648\u0644\u0649",repeating:"\u062E\u0635\u0645 {discount} \u0634\u0647\u0631\u064A\u064B\u0627 \u0644\u0645\u062F\u0629 {period}",forever:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0643\u0644 \u062F\u0641\u0639\u0629"}},FP=["zh-CN","zh-TW","zh-HK","en","ja","ko","es","fr","de","pt-BR","it","ru","vi","th","id","ar"];function Oo(e){let t=Si(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",i=dl[r];return i?{locale:t,copy:i}:{locale:"en",copy:dl.en}}function p_(e,t,n="zh-CN"){let r=hi(t);return Ic(e,t,Oo(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function f_(e,t="zh-CN"){let n=Oo(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e.percentOff/100):p_(e.amountOffCents,e.currency,n)}var ml={zh:"\u524D {months} \u4E2A\u6708\u5185\u5F00\u51FA\u7684\u8D26\u5355\u51CF {discount}","zh-Hant":"\u524D {months} \u500B\u6708\u5167\u958B\u51FA\u7684\u5E33\u55AE\u6E1B {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"\u6700\u521D\u306E {months} \u304B\u6708\u4EE5\u5185\u306E\u8ACB\u6C42\u304C {discount} \u5272\u5F15",ko:"\uCCAB {months}\uAC1C\uC6D4 \uB0B4 \uCCAD\uAD6C\uC11C {discount} \uD560\uC778",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de r\xE9duction sur les factures \xE9mises 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:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u0441\u0447\u0435\u0442\u0430 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",vi:"Gi\u1EA3m {discount} cho h\xF3a \u0111\u01A1n trong {months} th\xE1ng \u0111\u1EA7u",th:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E43\u0E1A\u0E41\u0E08\u0E49\u0E07\u0E2B\u0E19\u0E35\u0E49\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u0641\u0648\u0627\u062A\u064A\u0631 \u0627\u0644\u0635\u0627\u062F\u0631\u0629 \u062E\u0644\u0627\u0644 \u0623\u0648\u0644 {period}"};function pl(e,t="zh-CN",n="month"){let r=Oo(t),i=f_(e.discount,r.locale),a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",o=r.locale.split("-")[0]??"en",s=o==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":o,c=e.duration.type==="repeating"&&n!=="month"?ml[s]??ml.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],u=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return c.replace("{discount}",i).replace("{months}",a).replace("{period}",u)}var qP=z.enum(["draft","active","paused","archived"]),en=z.discriminatedUnion("type",[z.object({type:z.literal("percent"),percentOff:z.number().int().min(1).max(100)}).strict(),z.object({type:z.literal("amount"),amountOffCents:z.number().int().min(1).max(1e8),currency:se}).strict()]),dt=z.discriminatedUnion("type",[z.object({type:z.literal("once")}).strict(),z.object({type:z.literal("repeating"),months:z.number().int().min(1).max(36)}).strict(),z.object({type:z.literal("forever")}).strict()]),Mi=z.discriminatedUnion("type",[z.object({type:z.literal("all")}).strict(),z.object({type:z.literal("plans"),planIds:z.array(z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),h_=z.strictObject({firstPurchaseOnly:z.boolean(),condition:Vn}),$P=z.object({name:z.string().trim().min(1).max(80),description:z.string().max(500),discount:en,duration:dt,appliesTo:Mi,eligibility:h_,selfClaimEnabled:z.boolean().default(!1),startsAt:z.iso.datetime().nullable(),endsAt:z.iso.datetime().nullable(),totalLimit:z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:z.number().int().min(1).max(10),grantWindowHours:z.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}),GP=z.object({code:z.string().trim().transform(e=>e.toUpperCase()).pipe(z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:z.number().int().min(1).max(1e6).nullable(),expiresAt:z.iso.datetime().nullable(),firstPurchaseOnly:z.boolean(),minimumAmountCents:z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:se.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function KP(){return{name:"\u65B0\u4F18\u60E0\u5238",description:"",discount:{type:"percent",percentOff:20},duration:{type:"once"},appliesTo:{type:"all"},eligibility:{firstPurchaseOnly:!1,condition:{}},selfClaimEnabled:!1,startsAt:null,endsAt:null,totalLimit:null,perCustomerLimit:1,grantWindowHours:72}}var Po=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function HP(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return Po(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),Po(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),Po(t.appliesTo,n.appliesTo)||r.push({field:"appliesTo",reason:"immutable"}),t.startsAt!==n.startsAt&&r.push({field:"startsAt",reason:"immutable"}),t.endsAt!==n.endsAt&&(n.endsAt===null||t.endsAt!==null&&Date.parse(n.endsAt)>Date.parse(t.endsAt))&&r.push({field:"endsAt",reason:"only_earlier"}),t.totalLimit!==n.totalLimit&&(n.totalLimit===null||t.totalLimit!==null&&n.totalLimit>t.totalLimit)&&r.push({field:"totalLimit",reason:"only_reduce"}),n.perCustomerLimit>t.perCustomerLimit&&r.push({field:"perCustomerLimit",reason:"only_reduce"}),r}var g_=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function WP(e,t="zh-CN"){return pl(e,t)}function QP(e){return g_(e)}function ZP(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var Vr=z.object({id:z.uuid(),couponId:z.uuid(),status:z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:z.iso.datetime(),expiresAt:z.iso.datetime(),coupon:z.object({name:z.string(),discount:en,duration:dt,appliesTo:Mi}).strict()}).strict(),fl=z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var yl=_.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Co=_.string().regex(/^(0|[1-9]\d{0,14})$/),Qn=_.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),__=_.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),qr=__,Kt=_e.refine(e=>/[1-9]/.test(e)),et=_.iso.datetime({offset:!0}),xn=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},b_=_.array(_.object({upTo:Kt.nullable(),unitAmountMinor:yl,flatAmountMinor:_.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&xn(t.upTo)>xn(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),y_=_.discriminatedUnion("kind",[_.object({kind:_.literal("flat"),units:Kt,unitAmountMinor:yl}).strict(),_.object({kind:_.enum(["graduated","volume"]),units:Kt,tiers:b_}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),S_=_.strictObject({interval:_.enum(["month","year"]),count:_.number().int().min(1).max(12),anchor:_.enum(["membership","calendar"])}),tn=_.object({currency:se,pricing:y_,billingCycle:S_.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function Sl(e){return e.pricing.kind==="flat"&&xn(e.pricing.units)>0n&&xn(e.pricing.unitAmountMinor)===xn(e.pricing.units)*BigInt(10**hi(e.currency))}var hl={requestId:_.uuid(),productVersionId:_.uuid(),internal_feature_id:_.uuid(),currency:se},vl=_.strictObject({interval:_.enum(["hour","day","week","month"]),intervalCount:_.number().int().min(1).max(12),limit:_.number().int().min(1).max(1e6)}),Il=_.discriminatedUnion("kind",[_.object({...hl,kind:_.literal("auto_topup"),threshold:qa,quantity:Kt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:vl.optional()}).strict(),_.object({...hl,kind:_.literal("postpaid"),maxAmountMinorPerPeriod:qr,maxOutstandingMinor:qr}).strict()]),gl={productVersionId:_.uuid(),internal_feature_id:_.uuid(),currency:se},xl=_.discriminatedUnion("kind",[_.object({...gl,kind:_.literal("auto_topup"),threshold:qa,quantity:Kt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:vl.optional(),purchaseAmountMinor:qr,purchaseUnits:Kt}).strict(),_.object({...gl,kind:_.literal("postpaid"),maxAmountMinorPerPeriod:qr,maxOutstandingMinor:qr,cashPrice:tn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Bi=_.object({id:_.uuid(),terms:xl,status:_.enum(["prepared","active","revoked","blocked"]),createdAt:et,acceptedAt:et.nullable(),effectiveAt:et.nullable(),revokedAt:et.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),Al=_.object({authorizationId:_.uuid(),terms:xl,setupUrl:_.url().nullable()}).strict(),Ol=_.object({authorizationId:_.uuid(),accepted:_.literal(!0)}).strict(),Pl=_.object({authorizationId:_.uuid(),requestId:_.uuid()}).strict(),Cl=_.object({internal_feature_id:_.uuid(),entityId:_.uuid().nullable(),interval:_.enum(["day","week","month","year"]),anchor:_.enum(["billing_cycle","utc"]).optional(),basis:_.enum(["usage","credits"]),filter:qt.optional(),limit:_e.nullable(),thresholds:_.array(_.number().positive().max(1)).max(8),includedThresholds:_.array(_.number().positive().max(1)).max(8).optional(),absoluteThresholds:_.array(Kt).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&xn(t)>xn(i)}),"Notification thresholds must increase"),v_=Cl.safeExtend({requestId:_.uuid()}),_l={control:_.literal("overage"),requestId:_.uuid(),internal_feature_id:_.uuid(),entityId:_.uuid().nullable()},I_=_.discriminatedUnion("action",[_.strictObject({..._l,action:_.literal("set"),allowed:_.boolean().nullable(),overageLimit:_e.nullable(),skipOverageBilling:_.boolean()}),_.strictObject({..._l,action:_.literal("remove")})]),wl=_.union([v_,I_]),x_=_.strictObject({internal_feature_id:_.uuid(),entityId:_.uuid().nullable(),allowed:_.boolean().nullable(),overageLimit:_e.nullable(),skipOverageBilling:_.boolean(),interval:_.enum(["day","week","month","year"]),startsAt:et,endsAt:et,used:_.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:_.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:_.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),A_=_.object({internal_feature_id:_.uuid(),entityId:_.uuid().nullable(),interval:_.enum(["day","week","month","year"]),anchor:_.enum(["billing_cycle","utc"]).optional(),basis:_.enum(["usage","credits"]),filter:qt.optional(),startsAt:et,endsAt:et,used:Pt,reserved:Pt,limit:_e.nullable(),thresholds:_.array(_.number().positive().max(1)).max(8),notifiedThresholds:_.array(_.number().positive().max(1)).max(1024),includedThresholds:_.array(_.number().positive().max(1)).max(8).optional(),includedAllowance:_.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:_.array(_.number().positive().max(1)).max(1024).optional(),absoluteThresholds:_.array(Kt).max(8).optional(),notifiedAbsoluteThresholds:_.array(Kt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||_e.safeParse(e.used).success&&_e.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),O_=_.object({authorizationId:_.uuid(),status:_.enum(["idle","pending","blocked"]),taskId:_.uuid().nullable(),invoiceId:_.uuid().nullable(),hostedInvoiceUrl:_.url().nullable(),purchaseCount:_.number().int().nonnegative(),purchaseWindowEndsAt:et.nullable(),attemptCount:_.number().int().nonnegative(),failedAttemptCount:_.number().int().nonnegative(),suspendedAt:et.nullable(),nextAttemptAt:et.nullable(),failureReason:_.string().min(1).max(240).nullable()}).strict(),El=_.object({internal_feature_id:_.uuid().optional(),entityId:_.uuid().optional()}).strict(),wo=_.object({authorizations:_.array(Bi).max(100),limits:_.array(Cl).max(100),overages:_.array(x_).max(100).optional(),windows:_.array(A_).max(200),autoTopups:_.array(O_).max(100),limited:_.boolean()}).strict(),P_=_.object({id:_.uuid(),internal_feature_id:_.uuid(),productVersionId:_.uuid(),authorizationId:_.uuid(),entityId:_.uuid().nullable(),units:_e,amountMinor:Qn,cashPrice:tn}).strict(),$r=_.object({id:_.uuid(),sourceKind:_.enum(["product","usage","manual"]),providerInvoiceId:_.string().min(1).max(240).nullable(),status:_.enum(["accruing","open","pending","paid","failed","void"]),currency:se,startsAt:et.nullable(),endsAt:et.nullable(),amountMinor:_.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:_.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Co,paidAmountMinor:Co,refundedAmountMinor:Co,createdAt:et,hostedInvoiceUrl:_.url().nullable(),adjustment:_.object({originalInvoiceId:_.uuid(),amountMinor:_.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:et.nullable()}).strict().nullable(),lines:_.array(P_).max(100),linesLimited:_.boolean()}).strict(),Tl=_.object({invoiceId:_.uuid(),accepted:_.literal(!0)}).strict(),Rl=_.object({after:_.uuid().nullable(),limit:_.number().int().min(1).max(100)}).strict(),jl=_.object({rows:_.array($r).max(100),nextCursor:_.uuid().nullable()}).strict(),bl=_.strictObject({id:_.string(),coupon:_.string(),start:_.number().nonnegative(),end:_.number().nullable()}),C_=_.strictObject({subscriptionId:_.string(),customerId:_.string(),accountId:_.string(),sourceItems:_.array(_.strictObject({id:_.string(),price_id:_.string(),quantity:_.number().int(),discounts:_.array(bl).optional()})).max(100),items:_.array(_.strictObject({id:_.string(),price:_.string(),quantity:_.number().int(),discounts:_.array(_.strictObject({coupon:_.string().optional(),terms:_.strictObject({id:_.string(),name:_.string().optional(),percent_off:_.number().optional(),amount_off:_.number().optional(),currency:_.string().optional(),duration:_.enum(["once","forever","repeating"]),duration_in_months:_.number().optional()}).optional(),discount:_.string().optional(),receipt:bl.optional()})).max(20)})).max(100)}),Nl=_.strictObject({membershipId:_.uuid(),requestId:_.uuid(),grantIds:_.array(_.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),kl=_.strictObject({membershipId:_.uuid(),operationId:_.uuid(),status:_.enum(["pending","effective"]),execution:C_.nullable(),grants:_.array(_.strictObject({id:_.uuid(),couponId:_.uuid(),name:_.string(),discount:en,duration:dt,startedAt:et.nullable()})).max(20)});import{z as Gr}from"zod";var Kr=Gr.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Hr=Gr.number().int().min(1).max(1e3),An=Gr.object({cap:_e.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Gr.number().positive().max(1e4).nullable(),cycles:Gr.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var Eo={key:kt,name:R.string().trim().min(1).max(80),description:R.string().trim().max(240)},Dl=_e.refine(e=>/[1-9]/.test(e)),Li=R.array(R.object({currency:se,amountMinor:R.number().int().min(0).max(1e8)}).strict()).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique"),To=R.strictObject({units:Dl,prices:R.array(R.strictObject({currency:se,amountMinor:R.number().int().min(0).max(1e8),pricing:Lr.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:R.number().int().min(0).max(1e4),maximumQuantity:R.number().int().min(1).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&Ao({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),w_=R.discriminatedUnion("kind",[R.object({kind:R.literal("access"),internal_feature_id:R.uuid()}).strict(),R.object({kind:R.literal("metered"),internal_feature_id:R.uuid(),usageUnit:R.enum(["count","micro_usd"]),amount:_e.nullable(),reset:Kr,resetCount:Hr,pooled:R.boolean(),rollover:An.nullable().optional(),cashPrice:tn.nullable().optional(),prepaidPrice:To.optional(),feature_override:vo.nullish()}).strict().refine(e=>!e.cashPrice||e.amount!==null,"Cash pricing requires a finite prepaid allowance").refine(e=>!e.rollover||e.amount!==null&&e.reset!=="lifetime","Rollover requires a finite recurring consumable allowance").refine(e=>!e.prepaidPrice||e.amount!==null,"Purchased quantities require a finite included allowance").refine(e=>{if(!e.prepaidPrice||e.amount===null)return!0;try{return No(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),R.object({kind:R.literal("credit"),internal_feature_id:R.uuid(),amount:_e,reset:Kr,resetCount:Hr,rollover:An.nullable(),pooled:R.boolean(),feature_override:vo.nullish(),cashPrice:tn.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&Sl(e.cashPrice),"Itemized invoice credits require a recurring, unpooled allowance without rollover priced at one currency unit per credit").refine(e=>!e.rollover||e.reset!=="lifetime","Rollover requires a recurring allowance")]),Ro=R.array(w_).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),Fl=R.object({days:R.number().int().min(1).max(730),cardRequired:R.boolean(),allowances:Ro}).strict().refine(e=>e.allowances.every(t=>t.kind==="access"||!t.cashPrice&&(t.kind!=="metered"||!t.prepaidPrice)),"Trial allowances do not charge cash overages or purchased quantities"),Ul=R.object({key:kt,internal_feature_id:R.uuid(),productVersionId:R.uuid(),includedQuantity:R.number().int().min(0).max(1e4),maximumQuantity:R.number().int().min(0).max(1e4),prices:Li,pooled_internal_feature_ids:R.array(R.uuid()).max(100),requireAssignment:R.boolean()}).strict().refine(e=>e.maximumQuantity>=e.includedQuantity,"Capacity cannot be less than included seats").refine(e=>new Set(e.pooled_internal_feature_ids).size===e.pooled_internal_feature_ids.length,"Shared entitlements must be unique"),jo=R.discriminatedUnion("kind",[R.object({...Eo,kind:R.literal("membership"),groupId:R.uuid(),membershipType:R.enum(["main","addon"]),interval:R.enum(["free","week","month","year","one_time"]),intervalCount:R.number().int().min(1).max(156).optional(),prices:Li,allowances:Ro,trial:Fl.nullable(),licenses:R.array(Ul).max(20).refine(e=>new Set(e.map(t=>t.key)).size===e.length,"License keys must be unique")}).strict().refine(e=>e.interval==="free"?e.prices.every(t=>t.amountMinor===0):e.prices.every(t=>e.interval==="one_time"?t.amountMinor>0||e.allowances.some(n=>n.kind==="metered"&&n.prepaidPrice?.prices.some(r=>r.currency===t.currency&&r.amountMinor>0)):t.amountMinor>=0),"Prices must match the billing interval").refine(e=>e.interval!=="one_time"||e.trial===null,"Lifetime plans cannot have a subscription trial").refine(e=>e.intervalCount===void 0||(e.interval==="week"||e.interval==="month"||e.interval==="year")&&e.intervalCount<=(e.interval==="year"?3:e.interval==="month"?36:156),"Recurring billing intervals cannot exceed three years").refine(e=>e.allowances.every(t=>t.kind!=="metered"||!t.prepaidPrice||e.interval!=="free"&&t.prepaidPrice.prices.length===e.prices.length&&t.prepaidPrice.prices.every(n=>e.prices.some(r=>r.currency===n.currency))),"Purchased features require a paid plan and all its published currencies"),R.object({...Eo,kind:R.literal("topup"),interval:R.literal("one_time"),prices:Li,internal_feature_id:R.uuid(),amount:Dl,expiresDays:R.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),Ml=R.object({interval:R.enum(["free","week","month","year","one_time"]).optional(),intervalCount:R.number().int().min(1).max(156).nullable().optional(),prices:Li.optional(),allowances:R.object({upsert:Ro,remove:R.array(R.uuid()).max(100)}).strict().refine(e=>new Set(e.remove).size===e.remove.length&&e.upsert.every(t=>!e.remove.includes(t.internal_feature_id)),"An allowance cannot be removed and replaced together").optional(),trial:Fl.nullable().optional(),licenses:R.array(Ul).max(20).optional()}).strict(),Bl=R.object({...Eo,kind:R.literal("variant"),baseProductVersionId:R.uuid(),overrides:Ml}).strict(),fC=R.union([jo,Bl]);function hC(e,t){let n=Bl.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...a}=n.overrides,o=new Map(e.allowances.map(c=>[c.internal_feature_id,c]));for(let c of r?.remove??[])if(!o.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])o.delete(c.internal_feature_id);for(let c of r?.upsert??[])o.set(c.internal_feature_id,c);let s={...structuredClone(e),...structuredClone(a),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...o.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),jo.parse(s)}function gC(e,t){if(e.kind!=="membership"||t.kind!=="membership"||e.groupId!==t.groupId||e.membershipType!==t.membershipType)throw new Error("Variant group and membership type must match the base");let n={};for(let s of["interval","intervalCount","prices","trial","licenses"])(s==="intervalCount"&&["week","month","year"].includes(t.interval)?(e.intervalCount??1)===(t.intervalCount??1):JSON.stringify(e[s])===JSON.stringify(t[s]))||Object.assign(n,{[s]:s==="intervalCount"&&t[s]===void 0?null:structuredClone(t[s])});let r=new Map(e.allowances.map(s=>[s.internal_feature_id,s])),i=new Set(t.allowances.map(s=>s.internal_feature_id)),a=t.allowances.filter(s=>JSON.stringify(r.get(s.internal_feature_id))!==JSON.stringify(s)),o=e.allowances.filter(s=>!i.has(s.internal_feature_id)).map(s=>s.internal_feature_id);return(a.length||o.length)&&(n.allowances={upsert:a,remove:o}),Ml.parse(n)}var _C=R.object({products:R.array(R.object({id:R.uuid(),productId:R.string().min(1),name:R.string(),kind:R.enum(["membership","topup"]),version:R.number().int().positive()}).strict()).max(500),limited:R.boolean()}).strict(),E_=Ju.and(R.object({internal_id:R.uuid(),revision:R.number().int().nonnegative(),licenses:R.array(bo)})),bC=R.strictObject({rows:R.array(E_).max(200),nextCursor:R.uuid().nullable()}),yC=R.object({groups:R.array(R.object({id:R.uuid(),name:R.string(),defaultProductVersionId:R.uuid().nullable()}).strict()).max(500),features:ul.shape.features,products:R.array(R.object({id:R.uuid(),productId:R.uuid(),version:R.number().int().positive(),configuration:jo,baseProductVersionId:R.uuid().nullable()}).strict()).max(500),limited:R.boolean()}).strict();function No(e,t,n){let r=o=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(o))throw new Error("Invalid quantity");let[s,c=""]=o.split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return BigInt(s)*1000000n+BigInt(c.padEnd(6,"0"))};if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let i=r(e)+r(t)*BigInt(n);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let a=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(a?"."+a:"")}import{z as nn}from"zod";var Ll=nn.strictObject({itemKey:nn.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:nn.uuid(),includedAmount:nn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:nn.number().int().min(0).max(1e4),terms:To,pricing:Lr.optional(),unitAmountMinor:nn.number().int().min(0).max(1e8),productId:nn.string().min(1).max(255).nullable(),priceId:nn.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(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)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{No(e.includedAmount,e.terms.units,e.quantity),Ui({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as de}from"zod";var On=de.iso.datetime({offset:!0}),Vl=_e.refine(e=>/[1-9]/.test(e)),ql=de.strictObject({interval:Kr.exclude(["lifetime"]),count:Hr}),T_=de.strictObject({action:de.literal("create"),requestId:de.uuid(),internal_feature_id:de.uuid(),entityId:de.uuid().nullable(),amount:Vl.nullable(),expiresAt:On.nullable(),reset:ql.nullable(),rollover:An.nullable(),nextResetAt:On.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),$l=de.discriminatedUnion("action",[T_,de.strictObject({action:de.literal("update"),requestId:de.uuid(),grantId:de.uuid(),revision:de.number().int().nonnegative(),amount:Vl.nullable(),expiresAt:On.nullable(),rollover:An.nullable(),nextResetAt:On.nullable()}),de.strictObject({action:de.enum(["add","subtract","set_remaining"]),requestId:de.uuid(),grantId:de.uuid(),revision:de.number().int().nonnegative(),amount:_e}),de.strictObject({action:de.literal("revoke"),requestId:de.uuid(),grantId:de.uuid(),revision:de.number().int().nonnegative()})]),ko=de.strictObject({id:de.uuid(),internal_feature_id:de.uuid(),entityId:de.uuid().nullable(),amount:_e.nullable(),reset:ql.nullable(),rollover:An.nullable(),nextResetAt:On.nullable(),startsAt:On,expiresAt:On.nullable(),revision:de.number().int().nonnegative(),revoked:de.boolean(),available:Pt,held:Pt,spent:Pt}),Gl=de.strictObject({customerId:de.uuid(),after:de.uuid().nullable(),limit:de.number().int().min(1).max(100)}),Kl=de.strictObject({rows:de.array(ko).max(100),nextCursor:de.uuid().nullable()});import{z as $}from"zod";var Dt=$.iso.datetime({offset:!0}),Hl=$.strictObject({invoiceId:$.uuid(),after:$.string().min(1).max(180).nullable(),limit:$.number().int().min(1).max(100)}),R_=$.strictObject({kind:$.literal("product"),key:$.string(),productVersionId:$.uuid(),productName:$.string(),itemKey:$.string(),entityId:$.uuid().nullable(),quantity:$.number().int().positive(),subtotalMinor:$.string().regex(/^-?\d+$/),discountMinor:$.string().regex(/^\d+$/),taxMinor:$.string().regex(/^-?\d+$/).nullable(),totalMinor:$.string().regex(/^-?\d+$/),startsAt:Dt.nullable(),endsAt:Dt.nullable(),providerLineId:$.string().nullable(),providerItemId:$.string()}),Wl=$.strictObject({invoice:$r,items:$.array($.discriminatedUnion("kind",[R_,$.strictObject({kind:$.literal("invoice_credit"),key:$.string(),internal_feature_id:$.uuid(),internal_credit_feature_id:$.uuid(),name:$.string(),units:_e,reserved:_e,amountMinor:Qn,grossAmountMinor:Qn,creditsAppliedMinor:Qn,properties:qt,cashPrice:tn,providerItemId:$.string().nullable(),creditProviderItemId:$.string().nullable()}),$.strictObject({kind:$.literal("usage"),key:$.string(),internal_feature_id:$.uuid(),name:$.string(),units:_e,reserved:_e,amountMinor:Qn,cashPrice:tn})])).max(100),nextCursor:$.string().min(1).max(180).nullable()}),j_=$.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Do=$.strictObject({from:Dt,to:Dt,entityId:$.uuid().optional(),snapshotAt:Dt.nullable(),after:$.strictObject({at:Dt,id:$.uuid(),position:$.number().int().nonnegative()}).nullable(),limit:$.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Ql=$.strictObject({customerId:$.uuid(),entityId:$.uuid().nullable(),from:Dt,to:Dt,snapshotAt:Dt,totals:$.array($.strictObject({internal_credit_feature_id:$.uuid(),name:$.string(),consumed:Pt,refunded:Pt,net:j_})).max(1e3),rows:$.array($.strictObject({operationId:$.uuid(),position:$.number().int().nonnegative(),kind:$.enum(["consume","confirm","refund"]),originalId:$.uuid().nullable(),occurredAt:Dt,internal_feature_id:$.uuid(),entitlementName:$.string(),sourceId:$.uuid(),internal_credit_feature_id:$.uuid(),creditName:$.string(),units:Cc,amount:Pt,pricing:$.array(Pc).max(12),properties:qt})).max(100),nextCursor:Do.shape.after});import{z as Z}from"zod";var Yl=Z.object({customerId:Z.uuid()}).strict(),Jl=Z.discriminatedUnion("action",[Z.object({customerId:Z.uuid(),requestId:Z.uuid(),action:Z.literal("assign"),poolId:Z.uuid(),memberCustomerId:Z.uuid()}).strict(),Z.strictObject({customerId:Z.uuid(),requestId:Z.uuid(),action:Z.literal("assign_entity"),poolId:Z.uuid(),entityId:Z.uuid()}),Z.object({customerId:Z.uuid(),requestId:Z.uuid(),action:Z.literal("release"),poolId:Z.uuid(),slotId:Z.uuid()}).strict()]),Wr=Z.number().int().nonnegative(),Fo=Z.iso.datetime({offset:!0}),Uo=Z.strictObject({internalId:Z.uuid(),id:Z.string(),name:Z.string().nullable(),version:Z.number().int().positive()}),Zl=Z.enum(["active","past_due"]),Mo=Z.strictObject({customerId:Z.uuid(),licenses:Z.array(Z.strictObject({id:Z.uuid(),linkId:Z.uuid(),parent:Z.strictObject({customerProductId:Z.uuid(),status:Zl,product:Uo}),product:Uo,planLicense:Z.strictObject({id:Z.uuid(),prepaidOnly:Z.boolean(),isCustom:Z.boolean()}).nullable(),granted:Wr,included:Wr,paidQuantity:Wr,usage:Wr,remaining:Wr,createdAt:Fo}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:Z.array(Z.strictObject({id:Z.uuid(),linkId:Z.uuid(),status:Zl,product:Uo,entity:Z.strictObject({internalId:Z.uuid(),id:Z.string().nullable(),name:Z.string().nullable()}).nullable(),beneficiary:Z.strictObject({internalId:Z.uuid(),id:Z.string().nullable(),name:Z.string().nullable()}).nullable(),startedAt:Fo.nullable(),endedAt:Fo.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:Z.boolean()});import{z as ae}from"zod";import{z as Qe}from"zod";var Me=Qe.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"),Bo=Qe.strictObject({type:Qe.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Qe.boolean(),enum:Qe.array(Qe.string().max(255)).min(1).max(100).optional()}),Zn=Bo.extend({type:Qe.enum([...Bo.shape.type.options,"array"]),items:Bo.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"})}),Yn=Zn.safeExtend({source:Qe.discriminatedUnion("type",[Qe.strictObject({type:Qe.literal("input")}),Qe.strictObject({type:Qe.literal("node")}),Qe.strictObject({type:Qe.enum(["parameter","attribute"]),key:Me})])}),N_=Qe.record(Me,Yn),Vi=Qe.record(Me,Me).refine(e=>Object.keys(e).length<=20);function mt(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=>mt(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&&Qe.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 Lo(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&&Lo(e.items,t.items)}function Pn(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r;if(!Object.hasOwn(o,s))continue;let c=o[s];if(!mt(i,c))throw new Error(`Invalid variable value: ${r}`);n[r]=c}return n}function Cn(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function Vo(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!mt(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as wn}from"zod";var bt=wn.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),Ft=wn.discriminatedUnion("source",[wn.strictObject({source:wn.literal("literal"),value:he}),wn.strictObject({source:wn.literal("variable"),key:wn.string().min(1).max(255),path:bt.optional()})]);function Jn(e,t){if(!t)return e;for(let n of bt.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function En(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Pn(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(he.parse(Jn(n[e.key],e.path)))}function Xl(e,t){let n={},r=Object.entries(e).sort(([i],[a])=>i.split(".").length-a.split(".").length||i.localeCompare(a,"en",{numeric:!0}));for(let[i,a]of r){let o=bt.parse(i).split("."),s=n;for(let u=0;u<o.length-1;u++){let l=o[u],d=o[u+1];if(l===void 0||d===void 0)throw new Error("Invalid binding path");if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>s.length))throw new Error("Invalid array binding index");Object.hasOwn(s,l)||Reflect.set(s,l,/^(0|[1-9]\d*)$/.test(d)?[]:{});let p=Array.isArray(s)?s[Number(l)]:s[l];if(!p||typeof p!="object")throw new Error("Nested input requires an object or array");if(Array.isArray(p)!==/^(0|[1-9]\d*)$/.test(d))throw new Error("Nested input container does not match its path");s=p}let c=o.at(-1);if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(c)||Number(c)>s.length))throw new Error("Invalid array binding index");Reflect.set(s,c,En(a,t))}return n}function qi(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!bt.safeParse(r).success?null:{key:n,path:r}}function qo(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Rt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Mc))]}function Qr(e){return qo(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function WC(e,t){let n=Pn(t.declarations,t);return Object.fromEntries(Qr(e).flatMap(r=>{let i=qi(r,Object.keys(t.declarations)),a=i&&Object.hasOwn(n,i.key)?Jn(n[i.key],i.path):void 0;return a!==void 0?[[r,he.parse(a)]]:[]}))}function QC(e,t,n){let r=i=>i.replace(/\{\{\s*variables\.([^{}]+?)\s*\}\}/g,(a,o)=>(o=o.trim(),o===t||o.startsWith(t+".")?"{{ variables."+n+o.slice(t.length)+" }}":a));return e.screens.map(i=>{if(i.type!=="owned")return i;let a=structuredClone(i.document);for(let o of Object.values(a.strings.locales))for(let s of Object.keys(o))o[s]=r(o[s]);return Rt(a,o=>{if(o.type==="custom_html")for(let s of Object.keys(o.html))o.html[s]=r(o.html[s])}),{...i,document:a}})}function ct(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),d=l.replace(".","").length,p=(l.includes(".")?l.indexOf("."):d)+Number(u),g=p<=0?2-p+d:p>=d?p:d+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var rn=ae.enum(["page","popup","banner"]),k_=3e5,zl=ae.strictObject({type:ae.enum(["string","number","boolean","strings","json"]),nullable:ae.boolean()}),D_=ae.strictObject({inputs:ae.record(jr,zl.extend({required:ae.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ae.record(jr,zl).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),F_=ae.strictObject({kind:rn,schemaVersion:ae.literal(1),name:ae.string().trim().min(1).max(80),screen:ze,contract:D_}),$i=F_.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),ct(e)>k_&&n("Content document exceeds its byte budget",[])});function U_(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var M_=$i.superRefine((e,t)=>{for(let n of Qr(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!U_(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Jt(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),ed=ae.strictObject({id:ae.uuid(),kind:rn,projectId:ae.uuid(),environmentId:ae.uuid(),name:ae.string(),revision:ae.number().int().nonnegative(),status:ae.enum(["draft","published","archived"]),publishedVersionId:ae.uuid().nullable(),createdAt:ae.iso.datetime({offset:!0}),updatedAt:ae.iso.datetime({offset:!0})}),t1=ed.extend({draft:$i}),n1=ae.strictObject({rows:ae.array(ed).max(200),nextCursor:ae.uuid().nullable()}),Zr=ae.strictObject({id:ae.uuid(),kind:rn,resourceId:ae.uuid(),projectId:ae.uuid(),environmentId:ae.uuid(),version:ae.number().int().positive(),sourceRevision:ae.number().int().nonnegative(),document:M_,createdAt:ae.iso.datetime({offset:!0})}),r1=Zr.omit({document:!0}),i1=ae.discriminatedUnion("action",[ae.strictObject({action:ae.literal("create"),kind:rn,id:ae.uuid(),document:$i}),ae.strictObject({action:ae.literal("save"),kind:rn,id:ae.uuid(),revision:ae.number().int().nonnegative(),document:$i}),ae.strictObject({action:ae.enum(["publish","archive"]),kind:rn,id:ae.uuid(),revision:ae.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as td}from"zod";var Xn={funnelId:td.uuid().optional(),funnelVersionId:td.uuid().optional()};import{z as Ne}from"zod";import{z as ye}from"zod";import{z as Pe}from"zod";var B_=Pe.discriminatedUnion("action",[Pe.strictObject({action:Pe.literal("create"),couponId:Pe.uuid(),productBindingId:Pe.uuid(),storeOfferId:Pe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Pe.enum(["introductory","promotional"])}),Pe.strictObject({action:Pe.literal("set_enabled"),id:Pe.uuid(),revision:Pe.number().int().nonnegative(),enabled:Pe.boolean()})]),L_=Pe.array(Pe.strictObject({id:Pe.uuid(),couponId:Pe.uuid(),productBindingId:Pe.uuid(),storeOfferId:Pe.string().min(1).max(255).nullable(),storeOfferType:Pe.enum(["introductory","promotional"]),enabled:Pe.boolean(),revision:Pe.number().int().nonnegative()})).max(500),an=Pe.strictObject({offerKind:Pe.enum(["none","introductory","promotional"]),offerId:Pe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Pe.number().int().min(0).max(1e8),trialDays:Pe.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),nd=Pe.record(Pe.uuid(),an).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function V_(e,t){if(e.nativeOffers!==void 0)return nd.parse(e.nativeOffers)[t]}function q_(e,t,n,r){return an.safeParse(n).success?n.discountMinor<=r.catalogAmountMinor&&n.discountMinor===r.discountMinor&&n.trialDays===r.trialDays&&(t==="membership"||n.offerKind==="none")&&(e==="apple"?n.offerKind==="promotional"==(n.offerId!==null):n.offerKind==="none"==(n.offerId===null)&&(n.offerId===null||/^[a-z0-9][a-z0-9-]*$/.test(n.offerId))):!1}var $o=ye.object({type:ye.literal("native_purchase"),receiptId:ye.uuid(),orderId:ye.uuid(),productVersionId:ye.uuid(),provider:ye.enum(["apple","google"]),productId:ye.string().min(1).max(255),productKind:kc,replacement:ye.strictObject({sourceOrderId:ye.uuid(),sourceProductId:ye.string().min(1).max(255),policy:ye.enum(["apple_store","google_full_price"]),sourceAccountTokens:ye.array(ye.uuid()).max(50)}).nullable(),appAccountToken:ye.uuid().optional(),obfuscatedAccountId:ye.string().min(1).max(64).optional(),obfuscatedProfileId:ye.uuid().optional(),basePlanId:ye.string().min(1).max(255).optional(),offerId:ye.string().min(1).max(255).optional(),offerKind:ye.enum(["none","introductory","promotional"]),currency:se,catalogAmountMinor:ye.number().int().nonnegative().max(1e8),discountMinor:ye.number().int().nonnegative().max(1e8),trialDays:ye.number().int().min(1).max(730).nullable(),seatBundle:ye.array(ye.strictObject({key:ye.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:ye.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:ye.strictObject({offerId:ye.string().min(1).max(255),keyId:ye.string().min(1).max(255),nonce:ye.uuid(),signature:ye.string().min(1).max(1024),timestamp:ye.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{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(i=>i.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)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as f}from"zod";import{z as oe}from"zod/v4";import{z as $_}from"zod/v4";var G_=$_.registry(),{BillingInterval:rd}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{DisplaySchema:K_}=(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')."})})}))(oe),{withSpecDefault:H_}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(G_),{COMMON:id}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:W_}={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:Q_}=(e=>({COMMON_SET:new Set(e)}))(id),{hasNoDuplicateCurrencies:ad}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:od}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Z_}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(oe),{Infinite:Y_}={Infinite:"inf"},{TierBehavior:J_}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:sd}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:X_}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:z_}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:eb}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:tb}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(oe),{ApiCreditTierSchema:cd}=(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."})})}))(oe),{VIOLATION_MESSAGES:nb}={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:ud}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(oe),{ModelMarkupsSchema:rb}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(oe,ud),{InvoiceUsageEntrySchema:ib}=(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()}))(oe),{AttachDiscountSchema:ld}=(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."})}))(oe),{CustomLineItemSchema:ab}=(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."})})}))(oe),{UnixMsTimestampSchema:ob}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(oe),{CreateInvoicePreviewLineSchema:sb}=(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()})}))(oe),{ReissueInvoiceParamsSchema:Go}=(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."})})}))(oe),{InvoiceModeParamsSchema:on}=(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."})}))(oe),{InvoiceTemplateSchema:cb}=(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."})})}))(oe),{BasePriceSchema:ub}=((e,t,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(t).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."})})}))(oe,rd,K_),{CURRENCY_CODES:lb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(id,W_,Q_),{ApiPriceProcessorsSchema:dd}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(oe,Z_),{AllocatedBillingFieldSchema:db}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).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'."})}))(oe,X_),{CreditDimensionNameSchema:mb}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(oe,z_,eb),{ApiCreditMatchSchema:md}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(tb),{findCreditTierViolations:pb}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(nb),{ApiCreditMultiplierSchema:fb}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,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."})}))(oe,md),{ProviderMarkupsSchema:hb}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(oe,ud),{InvoiceFeatureQuantitySchema:pd}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).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(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(oe,sd,ib),{CreateInvoicePreviewSchema:Ko}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),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()})}))(oe,sb),{SUPPORTED_SET:gb}=(e=>({SUPPORTED_SET:new Set(e)}))(lb),{ApiCreditDimensionBaseSchema:_b}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(oe,md),{refineGraduatedTiers:fd}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(pb),{ApiFeatureMarkupsOverrideSchema:bb}=((e,t,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:t.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."})})}))(oe,hb,rb),{isValidCurrencyCode:yb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(gb),{ApiCreditDimensionSchema:Sb}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(oe,_b,cd,fd),{CurrencyCodeSchema:hd}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(oe,yb),{AdditionalCurrencyTierSchema:vb}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,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"]})}))(oe,hd),{ApiCreditSchemaItemBaseSchema:gd}=((e,t,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(t,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(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(oe,mb,Sb,fb),{ApiFlatCreditSchemaItemSchema:Ib}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(gd,oe),{AdditionalCurrencyPriceSchema:xb}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(oe,hd),{AdditionalCurrencyTierArraySchema:Ab}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(oe,vb,ad,od),{ApiGraduatedCreditSchemaItemSchema:Ob}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(gd,oe,cd,fd),{AdditionalCurrencyPriceArraySchema:_d}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(oe,xb,ad,od),{ApiUsageTierWithCurrenciesSchema:Pb}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),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(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(oe,Y_,Ab),{ApiCreditSchemaItemSchema:Cb}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(oe,Ob,Ib),{BasePriceParamsSchema:wb}=((e,t,n,r)=>({BasePriceParamsSchema:e.omit({display:!0}).extend({interval_count:t({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."})}))(ub,H_,oe,_d),{PlanItemPriceParamsSchema:Eb}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??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:t.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(i).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(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,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."})})}))(oe,_d,Pb,J_,rd,sd,db),{ApiFeatureOverrideSchema:Tb}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).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."})})}))(oe,Cb,bb),{InvoiceBasePriceParamsSchema:bd}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(wb,dd),{InvoiceItemPriceParamsSchema:Rb}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(Eb,dd),{InvoiceLicenseQuantitySchema:jb}=((e,t,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:t.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()}))(oe,bd,pd),{InvoiceCustomizeItemSchema:Nb}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.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()}))(oe,Rb,Tb),{InvoiceCustomizeSchema:kb}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.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."})}))(oe,bd,Nb),{InvoicePlanParamsSchema:Db}=((e,t,n,r,i)=>({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:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).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()}))(oe,kb,pd,jb,ld),{CreateInvoiceParamsSchema:zn}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).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:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.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(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(oe,Db,ab,ld,ob);var vd=f.strictObject({requestId:f.uuid(),predecessorOperationId:f.uuid().optional(),invoiceMode:on.optional(),entityId:f.uuid().optional(),billingSubscriptionId:f.uuid().optional(),newBillingSubscription:f.literal(!0).optional(),offerId:f.uuid().optional(),nativeOffer:an.optional(),plans:f.array(f.strictObject({productVersionId:f.uuid(),seatQuantities:f.record(kt,f.number().int().min(0).max(1e4)).optional(),featureQuantities:f.record(f.uuid(),f.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(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:f.enum(["stripe","apple","google"]),currency:se}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Rn=f.strictObject({operationId:f.uuid()}),$e=f.number().int().min(0).max(1e8),Fb=f.strictObject({lineId:f.uuid(),productVersionId:f.uuid(),productName:f.string().min(1).max(80),interval:f.enum(["free","week","month","year","one_time"]),intervalCount:f.number().int().min(1).max(156).optional(),baseAmountMinor:$e,seats:f.array(f.strictObject({key:kt,quantity:f.number().int().min(0).max(1e4),includedQuantity:f.number().int().min(0).max(1e4),maximumQuantity:f.number().int().min(0).max(1e4),unitAmountMinor:$e})).max(20),prepaid:f.array(Ll).max(100).optional(),catalogAmountMinor:$e,trial:f.strictObject({days:f.number().int().min(1).max(730),cardRequired:f.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+Ui({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"),Id=f.string().regex(/^[A-Za-z0-9_-]{1,200}$/),Ub=f.strictObject({id:Id,name:f.string().min(1).max(40),percent_off:f.number().gt(0).max(100).optional(),amount_off:f.number().int().positive().optional(),currency:f.string().regex(/^[a-z]{3}$/).optional(),duration:f.enum(["once","repeating","forever"]),duration_in_months:f.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"),Mb=f.strictObject({subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:f.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:f.array(f.strictObject({id:f.string(),price_id:f.string(),quantity:f.number().int().nonnegative(),discounts:f.array(f.strictObject({id:f.string(),coupon:f.string(),start:f.number(),end:f.number().nullable()})).optional()})).min(1).max(100),prorationDate:f.number().int().nonnegative(),amountMinor:f.number().int().positive(),periodStartMs:f.number(),periodEndMs:f.number()}),xd=f.strictObject({invoiceMode:on.optional(),append:Mb.optional(),provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),mode:f.enum(["payment","subscription"]),lineItems:f.array(f.strictObject({price:f.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:f.number().int().min(1).max(1e4),priceId:f.uuid(),productName:f.string().min(1).max(80),amountMinor:f.number().int().min(0).max(1e8),currency:f.string().regex(/^[a-z]{3}$/),interval:f.enum(["week","month","year","one_off"]),intervalCount:f.number().int().min(1).max(52),slot:f.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:f.strictObject({mode:f.enum(["graduated","volume"]),tiers:f.array(f.strictObject({upTo:f.number().int().min(1).max(1e6).nullable(),unitAmountMinor:f.number().int().min(0).max(1e8),flatAmountMinor:f.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:f.array(f.strictObject({coupon:Id,terms:Ub})).max(1),trialPeriodDays:f.number().int().min(1).max(730).nullable(),metadata:f.strictObject({grooveCheckoutId:f.uuid(),grooveCustomerId:f.uuid()}),expiresAt:f.iso.datetime({offset:!0})}),Yr=f.strictObject({operationId:f.uuid(),entityId:f.uuid().nullable(),billingSubscriptionId:f.uuid().nullable(),discount:f.strictObject({offerId:f.uuid(),couponId:f.uuid(),discount:en,duration:dt,amountMinor:$e,allocations:f.array(f.strictObject({productVersionId:f.uuid(),amountMinor:$e})).min(1).max(20),expiresAt:f.iso.datetime({offset:!0})}).nullable(),charge:f.strictObject({effectiveAt:f.iso.datetime({offset:!0}),periodEndsAt:f.iso.datetime({offset:!0}),debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e}).nullable(),expiresAt:f.iso.datetime({offset:!0}),provider:f.enum(["stripe","apple","google"]),nativeOffer:an.optional(),currency:se,lines:f.array(Fb).min(1).max(20),catalogAmountMinor:$e,automaticTax:f.boolean(),execution:xd.nullable()}).refine(e=>e.provider==="stripe"?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(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.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&&(e.provider==="stripe"||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(e.provider==="stripe"?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(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),er=f.strictObject({operationId:f.uuid(),orderId:f.uuid(),append:f.boolean().optional(),invoiceMode:f.boolean().optional(),status:f.enum(["pending","complete","cancelled","failed"]),executor:f.enum(["indiana","merchant"]),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:xd.nullable(),currency:se,catalogAmountMinor:$e,taxMinor:$e,totalMinor:f.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.boolean(),nativePurchase:$o.nullable()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Ki=f.strictObject({enabled:f.literal(!0),featureIds:f.array(f.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Ad=f.strictObject({requestId:f.uuid(),invoiceMode:on.optional(),membershipId:f.uuid(),carryOverBalances:Ki.optional(),carryOverUsages:Ki.optional(),membershipIds:f.array(f.uuid()).min(1).max(20).optional(),prorationBehavior:f.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:f.enum(["immediate","renewal","store"]),change:f.discriminatedUnion("type",[f.strictObject({type:f.literal("plan"),productVersionId:f.uuid()}),f.strictObject({type:f.literal("seats"),licenseKey:kt,quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("quantity"),internal_feature_id:f.uuid(),quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("cancel")}),f.strictObject({type:f.literal("uncancel")}),f.strictObject({type:f.literal("billing_cycle"),billingCycleAnchor:f.union([f.literal("now"),f.number().int().positive().max(0xe677d21fdbff)])})])}).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"),Gi=f.string().regex(/^price_[A-Za-z0-9]+$/),yd=f.strictObject({grooveUpdateId:f.uuid(),grooveCustomerId:f.uuid()}),Sd=f.strictObject({price:Gi.nullable(),priceId:f.uuid().optional(),quantity:f.number().int().min(0).max(1e4)}),Od=f.strictObject({provider:f.literal("stripe"),invoiceMode:on.optional(),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),action:f.enum(["update","cancel","schedule","release"]),update:f.strictObject({items:f.array(Sd).max(20),remove:f.array(Gi).max(20),restoreItems:f.array(f.strictObject({price:Gi,quantity:f.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:f.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:f.number().int().positive().optional(),paymentBehavior:f.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:f.boolean().optional(),clearCancelAt:f.literal(!0).optional(),billingCycleAnchorNow:f.literal(!0).optional(),metadata:yd}).nullable(),cancel:f.strictObject({prorate:f.literal(!1),invoiceNow:f.literal(!1)}).nullable(),schedule:f.strictObject({currentItems:f.array(f.strictObject({price:Gi,quantity:f.number().int().min(0).max(1e4)})).max(20),nextItems:f.array(Sd).min(1).max(20),switchAt:f.number().int().positive(),interval:f.enum(["week","month","year"]),intervalCount:f.number().int().min(1).max(52),resetBillingCycleAnchor:f.literal(!0).optional(),metadata:yd}).nullable(),release:f.strictObject({schedule:f.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:f.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Ho=f.strictObject({carryOverBalances:Ki.optional(),carryOverUsages:Ki.optional(),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),expiresAt:f.iso.datetime({offset:!0}),currency:se,creditMinor:$e,debitMinor:$e,discountMinor:$e,taxMinor:$e,totalMinor:$e,retainedProductVersionIds:f.array(f.uuid()).max(19),execution:Od}),Bb=f.strictObject({operationId:f.uuid(),invoiceMode:f.boolean().optional(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:f.enum(["indiana","merchant"]),execution:Od.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Lb=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.literal("store"),effectiveAt:f.null(),expiresAt:f.iso.datetime({offset:!0}),currency:se,creditMinor:f.null(),debitMinor:f.null(),discountMinor:f.null(),taxMinor:f.null(),totalMinor:f.null(),retainedProductVersionIds:f.array(f.uuid()).max(19),store:f.strictObject({provider:f.enum(["apple","google"]),productId:f.string().min(1).max(255),catalogAmountMinor:$e,policy:f.enum(["apple_store","google_full_price"])})}),Vb=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","pending","effective","cancelled","failed"]),timing:f.literal("store"),effectiveAt:f.iso.datetime({offset:!0}).nullable(),checkoutUrl:f.null(),nativePurchase:$o.nullable()}),Pd=f.union([Ho,Lb]),Wo=f.union([Bb,Vb]),Jr=f.number().int().positive().max(2e8),Tn=f.number().int().min(0).max(2e8),Cd=f.strictObject({requestId:f.uuid(),invoiceId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:Jr.optional(),entitlementAction:f.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),wd=f.strictObject({provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:f.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Jr,currency:f.string().regex(/^[a-z]{3}$/),metadata:f.strictObject({indianaRefundId:f.uuid()}),idempotencyKey:f.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:f.array(f.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Ed=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().regex(/^in_[A-Za-z0-9]+$/),currency:se,paidMinor:Tn,refundedMinor:Tn,pendingMinor:Tn,amountMinor:Jr,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),revokes:f.strictObject({customerProductIds:f.array(f.uuid()).max(100),subscriptionIds:f.array(f.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:wd,expiresAt:f.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&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"),Hi=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().regex(/^in_[A-Za-z0-9]+$/),status:f.enum(["quoted","pending","succeeded","failed","expired"]),executor:f.enum(["indiana","merchant"]),currency:se,amountMinor:Jr,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),refundId:f.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:wd.nullable(),failureReason:f.string().min(1).max(200).nullable(),createdAt:f.iso.datetime({offset:!0}),completedAt:f.iso.datetime({offset:!0}).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"),C1=f.strictObject({invoiceId:f.uuid(),currency:se,paidMinor:Tn,refundedMinor:Tn,pendingMinor:Tn,refundableMinor:Tn,executor:f.enum(["indiana","merchant"]).nullable(),canRefund:f.boolean(),operations:f.array(Hi).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),w1=f.strictObject({requestId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:Jr.optional(),entitlementAction:f.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var Td=Ne.strictObject({requestId:Ne.uuid(),targets:Ne.array(Ne.strictObject({membershipId:Ne.uuid(),action:Ne.enum(["cancel","uncancel"]),timing:Ne.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Wi=Ne.strictObject({batchId:Ne.uuid()}),qb=Ne.strictObject({operationId:Ne.uuid(),membershipIds:Ne.array(Ne.uuid()).min(1).max(20),provider:Ne.enum(["stripe","apple","google"]),action:Ne.enum(["cancel","uncancel"]),timing:Ne.enum(["immediate","renewal"]),status:Ne.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ho.nullable(),managementUrl:Ne.url().nullable(),failureCode:Ne.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Xr=Ne.strictObject({batchId:Ne.uuid(),ready:Ne.boolean(),status:Ne.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Ne.iso.datetime({offset:!0}),acceptedAt:Ne.iso.datetime({offset:!0}).nullable(),groups:Ne.array(qb).min(1).max(100)});import{z as le}from"zod";var $b=le.string().trim().min(1).max(240),Qo={requestId:le.uuid(),reason:$b},Qi=le.discriminatedUnion("action",[le.strictObject({...Qo,action:le.literal("start"),productVersionId:le.uuid(),entityId:le.uuid().optional(),days:le.number().int().min(1).max(730).optional()}),le.strictObject({...Qo,action:le.literal("extend"),membershipId:le.uuid(),days:le.number().int().min(1).max(730)}),le.strictObject({...Qo,action:le.literal("end"),membershipId:le.uuid()})]),Rd=le.strictObject({operationId:le.uuid()}),jd=le.iso.datetime({offset:!0}),Gb=le.strictObject({provider:le.literal("stripe"),executor:le.enum(["indiana","merchant"]),accountId:le.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:le.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:le.union([le.literal("now"),jd]),prorationBehavior:le.literal("none")}),Zo=le.strictObject({operationId:le.uuid(),action:le.enum(["start","extend","end"]),status:le.enum(["pending","effective"]),managedBy:le.enum(["indiana","stripe"]),membershipIds:le.array(le.uuid()).min(1).max(20),endsAt:jd.nullable(),execution:Gb.nullable()}).refine(e=>e.execution!==null==(e.managedBy==="stripe"&&e.status==="pending")&&e.action==="end"==(e.endsAt===null)&&(e.action!=="start"||e.managedBy==="indiana")&&(e.execution===null||e.execution.trialEnd==="now"==(e.action==="end")),"Only a pending Stripe trial change carries execution instructions"),k1=le.strictObject({groupId:le.uuid(),productVersionId:le.uuid(),enabled:le.boolean()});import{z as Ae}from"zod";var Nd=Ae.strictObject({requestId:Ae.uuid(),currency:se,makeDefault:Ae.boolean()}),kd=Ae.strictObject({setupId:Ae.uuid()}),Kb=Ae.strictObject({provider:Ae.literal("stripe"),executor:Ae.literal("merchant"),accountId:Ae.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Ae.literal("setup"),currency:Ae.string().regex(/^[a-z]{3}$/),customer:Ae.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Ae.uuid(),metadata:Ae.strictObject({grooveProjectId:Ae.uuid(),grooveEnvironmentId:Ae.uuid(),grooveCustomerId:Ae.uuid(),groovePaymentSetupId:Ae.uuid()}),setDefaultPaymentMethod:Ae.boolean(),expiresAt:Ae.iso.datetime({offset:!0})}),Yo=Ae.strictObject({id:Ae.uuid(),provider:Ae.literal("stripe"),status:Ae.enum(["prepared","complete","expired"]),currency:se,makeDefault:Ae.boolean(),url:Ae.url().nullable(),createdAt:Ae.iso.datetime({offset:!0}),expiresAt:Ae.iso.datetime({offset:!0}),completedAt:Ae.iso.datetime({offset:!0}).nullable(),execution:Kb.nullable()});import{z as Ge}from"zod";var Dd=Ge.union([Ge.string(),Ge.number(),Ge.boolean(),Ge.null()]),Fd=Ge.strictObject({customerId:Ge.uuid()}),Ud=Ge.strictObject({customerId:Ge.uuid(),provider:Ge.literal("stripe"),checkedAt:Ge.iso.datetime({offset:!0}),status:Ge.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ge.number().int().nonnegative(),differences:Ge.array(Ge.strictObject({subscriptionId:Ge.string().startsWith("sub_"),itemId:Ge.string().nullable(),field:Ge.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Dd,actual:Dd})).max(1e4)});import{z as ie}from"zod";var Zi=ie.iso.datetime({offset:!0}),Yi=ie.strictObject({createdAt:Zi,id:ie.uuid()}),Ji=ie.strictObject({customerId:ie.uuid().optional(),entityId:ie.uuid().optional(),productId:ie.string().min(1).max(256).optional(),provider:ie.enum(["stripe","apple","google","free"]).optional(),status:ie.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Yi.optional(),limit:ie.number().int().min(1).max(100).optional()}),Jo={id:ie.uuid(),customerId:ie.uuid(),entityId:ie.uuid().nullable(),productId:ie.string().min(1).max(256),productVersionId:ie.uuid(),name:ie.string().min(1).max(120),provider:ie.enum(["stripe","apple","google","free"]),createdAt:Zi},Hb=ie.strictObject({...Jo,status:ie.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ie.boolean(),billingSubscriptionId:ie.uuid().nullable()}),Wb=ie.strictObject({...Jo,status:ie.enum(["active","ended","refunded"]),orderId:ie.uuid().nullable(),transactionId:ie.uuid().nullable(),currency:se.nullable(),amountMinor:ie.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),Qb=ie.strictObject({...Jo,status:ie.enum(["blocked","resolved"]),conflict:ie.strictObject({detectedAt:Zi,blockingMembershipIds:ie.array(ie.uuid()).min(1).max(100),transactionId:ie.uuid()}),resolvedAt:Zi.nullable()}),Md=Ji.extend({status:ie.enum(["blocked","resolved"]).optional()}),Bd=ie.strictObject({customerId:ie.uuid(),orderId:ie.uuid()}),Ld=ie.strictObject({orderId:ie.uuid(),status:ie.enum(["blocked","resolved"])}),Vd=ie.strictObject({items:ie.array(Hb).max(100),nextCursor:Yi.nullable()}),qd=ie.strictObject({items:ie.array(Wb).max(100),nextCursor:Yi.nullable()}),$d=ie.strictObject({items:ie.array(Qb).max(100),nextCursor:Yi.nullable()});import{z as Ee}from"zod";var Gd=Ee.union([Ee.strictObject({intent:Ee.literal("read"),requestId:Ee.uuid(),purchaseIntentId:Ee.uuid()}),Ee.strictObject({requestId:Ee.uuid(),provider:Ee.literal("apple"),purchaseIntentId:Ee.uuid(),productId:Ee.string().min(1).max(255).optional(),signedTransaction:Ee.string().min(1).max(131072)}),Ee.strictObject({requestId:Ee.uuid(),provider:Ee.literal("google"),purchaseIntentId:Ee.uuid(),productId:Ee.string().min(1).max(255).optional(),purchaseToken:Ee.string().min(1).max(16384)})]),Kd=Ee.strictObject({requestId:Ee.uuid(),orderId:Ee.uuid(),purchaseIntentId:Ee.uuid(),status:Ee.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:se,refunded:Ee.boolean(),completion:Ee.strictObject({transactionIds:Ee.array(Ee.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ee.boolean()}).nullable()});import{z as j}from"zod";var zo=j.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Zb=j.record(j.string(),j.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Yb=3,zr=20,Jb=Yb*zr,Xo=j.strictObject({type:j.literal("product"),productId:zo}),Hd={type:j.literal("group"),key:j.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:j.string().trim().min(1).max(80)},Xb=j.discriminatedUnion("type",[Xo,j.strictObject({...Hd,items:j.array(Xo).max(zr)})]),zb=j.discriminatedUnion("type",[Xo,j.strictObject({...Hd,items:j.array(Xb).max(zr)})]),ey=j.array(zb).max(zr).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>zr||i>Jb)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function es(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:es(t))}function Q1(e){function t(n,r){return n.flatMap(i=>i.type==="product"?[{productId:i.productId,groups:r}]:t(i.items,[...r,i.name]))}return t(e.items,[])}var tr=j.strictObject({lookupKey:j.string().trim().min(1).max(200),displayName:j.string().trim().min(1).max(1500),items:ey,metadata:Zb}),ty=j.strictObject({product:j.record(j.string(),j.json()),prices:j.array(j.record(j.string(),j.json())),entitlements:j.array(j.record(j.string(),j.json())),freeTrials:j.array(j.record(j.string(),j.json())),licenses:j.array(j.record(j.string(),j.json()))}),Wd=tr.extend({id:j.uuid(),projectId:j.uuid(),environmentId:j.uuid(),state:j.enum(["active","archived"]),isCurrent:j.boolean(),revision:j.number().int().nonnegative(),publishedVersionId:j.uuid().nullable(),createdAt:j.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Qd=j.strictObject({id:j.uuid(),offeringId:j.uuid(),projectId:j.uuid(),environmentId:j.uuid(),version:j.number().int().positive(),document:tr,productEvidence:j.record(zo,ty),createdAt:j.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=es(e.document);(!n.length||iy(e.document).length>0||Object.keys(e.productEvidence).length!==n.length||n.some(r=>!Object.hasOwn(e.productEvidence,r)))&&t.addIssue({code:"custom",message:"Published Offering requires evidence for every Product"})}),ny=j.strictObject({rows:j.array(Wd).max(200),versions:j.array(Qd).max(500)}),Z1=j.discriminatedUnion("action",[j.strictObject({action:j.literal("create"),document:tr}),j.strictObject({action:j.literal("save"),id:j.uuid(),revision:j.number().int().nonnegative(),document:tr}),j.strictObject({action:j.enum(["publish","set_current","archive","restore"]),id:j.uuid(),revision:j.number().int().nonnegative()})]),Y1=j.strictObject({record:Wd,version:Qd.nullable()}),Zd=j.discriminatedUnion("type",[j.strictObject({type:j.literal("current")}),j.strictObject({type:j.literal("id"),id:j.uuid()}),j.strictObject({type:j.literal("lookup_key"),lookupKey:j.string().min(1).max(200)}),j.strictObject({type:j.literal("version"),versionId:j.uuid()})]),ry=j.strictObject({internalId:zo,id:j.string(),name:j.string().nullable(),version:j.number().int().positive(),archived:j.boolean()}),J1=ny.extend({products:j.array(ry).max(500)});function iy(e){let t=[];es(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as Xi}from"zod";var Yd=Xi.strictObject({id:Xi.uuid(),offeringId:Xi.uuid(),version:Xi.number().int().positive(),document:tr});import{z as Le}from"zod";import{z as J}from"zod";import{z as nr}from"zod";var zi=nr.strictObject({items:nr.array(nr.strictObject({productVersionId:nr.string().min(1).max(200),label:nr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:nr.string().min(1).max(200).nullable(),grouping:Lc.optional()});function iw(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as Be}from"zod";var ay=Be.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ea=Be.discriminatedUnion("type",[Be.object({type:Be.literal("fixed"),productVersionId:Be.string().min(1).max(200)}).strict(),Be.object({type:Be.literal("picker"),pickerId:ay,allowedProductVersionIds:Be.array(Be.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Ht=Be.discriminatedUnion("type",[Be.object({type:Be.literal("modal"),size:Be.enum(["sm","md","lg"])}).strict(),Be.object({type:Be.literal("sheet"),size:Be.enum(["sm","md","lg"])}).strict(),Be.object({type:Be.literal("fullscreen")}).strict(),Be.object({type:Be.literal("inline")}).strict()]);var ts=J.discriminatedUnion("type",[J.strictObject({type:J.literal("event"),event:J.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),J.strictObject({type:J.literal("open_url"),url:J.url().refine(e=>new URL(e).protocol==="https:")})]),oy=ze,sy=J.discriminatedUnion("type",[J.object({type:J.literal("checkout"),product:ea}).strict(),J.object({type:J.literal("close")}).strict(),J.object({type:J.literal("action"),action:ts}).strict()]),rr=J.object({schemaVersion:J.literal(3),kind:J.literal("paywall"),name:J.string().trim().min(1).max(80),presentation:Ht,requirement:Gn.optional(),products:zi,offeringVersionId:J.uuid().nullable(),offeringId:J.uuid(),screen:oy,buttons:J.record(J.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sy)}).strict(),hw=rr.superRefine((e,t)=>{(e.screen.surface!=="paywall"||e.screen.actions.some(r=>!["event","navigate"].includes(r.type)||r.close))&&t.addIssue({code:"custom",message:"Paywall screen is incomplete"});for(let r of uy(e))t.addIssue({code:"custom",message:r});for(let r of cy(e))t.addIssue({code:"custom",message:r});Jt(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function cy(e){let t=e.products.items.map(a=>a.productVersionId),n=Bc(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!Vc(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Rt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Rt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function uy(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Nr(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(p=>p.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let d=e.buttons[u];s.id!==n.id&&d&&d.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Jd=J.object({id:J.uuid(),projectId:J.uuid(),environmentId:J.uuid(),revision:J.number().int().nonnegative(),state:J.enum(["active","archived"]),publishedVersionId:J.uuid().nullable(),updatedAt:J.iso.datetime({offset:!0}),draft:rr}).strict(),gw=J.object({rows:J.array(Jd).max(200),nextCursor:J.uuid().nullable()}).strict(),_w=Jd.omit({draft:!0}).extend({name:J.string(),productCount:J.number().int().nonnegative()}).strict(),bw=J.discriminatedUnion("action",[J.object({action:J.literal("save"),id:J.uuid().nullable(),revision:J.number().int().nonnegative(),document:rr}).strict(),J.object({action:J.enum(["publish","archive"]),id:J.uuid(),revision:J.number().int().nonnegative()}).strict()]),yw=J.object({paywalls:J.array(J.object({id:J.uuid(),paywallId:J.uuid(),version:J.number().int().positive(),name:J.string().min(1).max(80),presentation:Ht,buttons:rr.shape.buttons}).strict()).max(500),limited:J.boolean()}).strict();import{z as ce}from"zod";import{z as tt}from"zod";var sn=tt.string().regex(/^[a-f0-9]{64}$/),ly=Uc.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Xd=tt.strictObject({couponDigests:tt.record(tt.uuid(),sn),variables:tt.record($t,tt.record(tt.uuid(),tt.partialRecord(tt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),tt.string()))),locales:tt.record($t,Kn.extend({nodes:tt.record(tt.string(),tt.strictObject({base:ly})),plans:tt.object({}).strict(),pickers:tt.object({}).strict()}).omit({paywall:!0}))});import{z as xe}from"zod";import{z as ta}from"zod";var ns=ta.strictObject({eventsEnabled:ta.boolean(),experimentViewsEnabled:ta.boolean(),featureUsageEnabled:ta.boolean()}),Pw=Object.freeze({eventsEnabled:!1,experimentViewsEnabled:!0,featureUsageEnabled:!1});function Cw(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var rs=Xt.extend({analyticsConfig:ns,remoteFeatures:xe.array(xe.string().min(1).max(255)).max(500)}),dy=rs.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),zd=xe.strictObject({attributes:Tt,features:xe.array(xe.string().min(1).max(255)).min(1).max(500).optional(),customerId:xe.uuid().optional()}),my=xe.strictObject({value:he,source:xe.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:xe.boolean(),off:xe.boolean(),ruleId:xe.string(),experimentResult:Hc.optional()}),em=xe.strictObject({generation:Xt.shape.generation,evaluatedAt:Xt.shape.evaluatedAt,expiresAt:Xt.shape.expiresAt,features:xe.record(xe.string(),my)}),tm=xe.strictObject({customerId:xe.uuid().optional(),events:xe.array(xe.strictObject({eventUuid:xe.uuid(),timestamp:xe.iso.datetime({offset:!0}),name:xe.string().min(1).max(255),properties:xe.record(xe.string(),he).default({}),deviceId:xe.string().min(1).max(255).optional(),sessionId:xe.string().min(1).max(255).optional()})).min(1).max(100)}),nm=xe.strictObject({inserted:xe.number().int().nonnegative(),duplicates:xe.number().int().nonnegative(),rejected:xe.number().int().nonnegative(),skipped:xe.number().int().nonnegative(),analyticsConfig:ns});import{z as T}from"zod";function is(e,t=[]){let n=[];Rt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(Ga(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function rm(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>rm(t)??[])}}function py(e){let t=e.pages.map(i=>{let a=rm(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(Ga({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function na(e,t=[]){let n=ze.parse(structuredClone(py(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=is(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Oe}from"zod";var Bw=Oe.enum(["local","remote"]),ei=Oe.strictObject({port:Oe.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:he.optional(),sticky:Oe.array(Oe.strictObject({expected:yi.nullable(),next:yi})).max(100),exposures:Oe.array(he).max(100),features:Oe.array(he).max(100)}),ra=Oe.strictObject({type:Oe.literal("evaluate"),receiptId:Oe.uuid(),environmentId:Oe.uuid(),policyRevision:Oe.number().int().nonnegative(),attributes:Tt,sticky:Oe.record(Oe.string(),yi)}),im=ra.extend({runId:Oe.uuid(),versionId:Oe.uuid(),nodeId:Oe.string().min(1).max(64),visit:Oe.number().int().nonnegative(),revision:Oe.number().int().nonnegative()}),as=ra.omit({type:!0,receiptId:!0}).extend({type:Oe.literal("evaluate_segment")}),am=Oe.strictObject({nodeId:Oe.string().min(1).max(64),result:ei}),om=as.extend({runId:Oe.uuid(),versionId:Oe.uuid(),nodeId:Oe.string().min(1).max(64),visit:Oe.number().int().nonnegative(),revision:Oe.number().int().nonnegative(),parameters:jt,answers:vn,variables:Oe.record(Oe.string(),he)});import{z as M}from"zod";import{z as ve}from"zod";var os=he,fy=["parameters","answers","results","variables"];function ss(e){return fy.some(t=>e===t||e.startsWith(t+"."))}function ia(e){let t={};for(let[r,i]of Object.entries(Pn(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!ss(r))),variables:t}}function cs(e,t){return bi(ia(t),e,t.savedGroups)}function ti(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i.startsWith("$")||t.add(i),i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.attributeKey=="string"&&t.add(a.attributeKey),["$and","$or","$nor","$not"].includes(i)&&n(a)}return n(e),[...t]}import{z as hy}from"zod";var aa=hy.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var us=ve.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),sm=ve.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),oa=jt.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),ls=ve.record(us,ve.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),gy=Ft,cm=ve.strictObject({type:ve.literal("external_task"),endpointId:ve.uuid(),taskKey:us,inputs:ve.record(us,gy).refine(e=>Object.keys(e).length<=20),outputs:ls}),um=ve.strictObject({maxAttempts:ve.number().int().min(1).max(5),retryDelaySeconds:ve.number().int().min(1).max(30),backoff:ve.enum(["fixed","exponential"]),requestTimeoutSeconds:ve.number().int().min(1).max(10),timeoutSeconds:ve.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline"),Xw={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},zw=ve.strictObject({outcome:ve.enum(["success","failure"]),data:oa});function eE(e,t){let n=oa.parse(t);if(Object.keys(n).length!==Object.keys(e).length||Object.entries(e).some(([r,i])=>!Object.hasOwn(n,r)||(i==="strings"?!Array.isArray(n[r])||!n[r].every(a=>typeof a=="string"):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function tE(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=En(i,t);return oa.parse(n)}var nE=ve.discriminatedUnion("operation",[ve.strictObject({operation:ve.literal("signal"),runId:ve.uuid(),nodeId:sm,eventName:aa,eventId:ve.uuid(),data:oa}),ve.strictObject({operation:ve.literal("read_results"),runId:ve.uuid()})]),rE=ve.strictObject({scope:we,runId:ve.uuid(),eventId:ve.uuid(),accepted:ve.boolean()}),_y=ve.record(sm,os),iE=ve.strictObject({scope:we,runId:ve.uuid(),results:_y});var yt={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},lm="00000000-0000-0000-0000-000000000000";import{z as F}from"zod";import{z as W}from"zod";var ds=W.array(W.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),ir=W.intersection(Tt,W.looseObject({tags:ds.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),sa=W.string().trim().max(80),ca=W.union([W.email().max(254),W.literal("")]),ua=W.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),dm=W.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),mm=W.object({externalUserId:dm.optional(),name:sa.default(""),email:ca.default(""),attributes:ir.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ar=W.discriminatedUnion("type",[W.strictObject({type:W.literal("id"),value:W.uuid()}),W.strictObject({type:W.literal("externalUserId"),value:dm})]),or=W.strictObject({name:sa.optional(),email:ca.optional(),attributes:ir.optional(),fingerprint:ua.optional()}),jn=e=>!e.customerData||e.customer?.type==="externalUserId",Nn="customerData requires an externalUserId customer",sr=W.object({id:W.uuid(),externalUserId:W.string().min(1).max(255).nullable(),name:sa,email:ca,attributes:ir,createdAt:W.iso.datetime()}).strict(),pm=W.object({customer:sr,changed:W.boolean(),replayed:W.boolean()}).strict(),by=W.discriminatedUnion("type",[W.object({type:W.literal("id"),value:W.uuid()}).strict(),W.object({type:W.literal("externalUserId"),value:W.string().trim().min(1).max(255)}).strict()]),yy=W.object({name:sa.optional(),email:ca.optional(),attributes:ir.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:W.array(W.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:W.strictObject({add:ds,remove:ds}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),ms=W.object({lookup:by}).strict(),fm=ms.extend({requestId:W.uuid(),patch:yy}).strict(),hm=W.object({search:W.string().trim().max(200).default(""),tag:W.string().trim().max(40).default(""),planId:W.string().max(200).default(""),versionId:W.string().max(200).default(""),holdingStatus:W.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:W.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:W.union([W.iso.datetime(),W.literal("")]).default(""),createdUntil:W.union([W.iso.datetime(),W.literal("")]).default(""),offset:W.coerce.number().int().min(0).max(1e5).default(0),limit:W.coerce.number().int().min(1).max(100).default(50)}).strict(),gm=W.object({customers:sr.array(),hasMore:W.boolean(),total:W.number().int().nonnegative().nullable(),evaluatedAt:W.iso.datetime()}).strict();var ni=F.discriminatedUnion("type",[F.strictObject({type:F.literal("literal"),value:he}),F.strictObject({type:F.literal("variable"),key:Me,path:bt.optional()}),F.strictObject({type:F.literal("feature"),featureKey:F.string().min(1).max(128)})]),Sy=F.strictObject({requestId:F.uuid(),decisionId:F.uuid(),customerId:F.uuid(),externalUserId:F.string().min(1).max(255).nullable(),versionId:F.uuid(),receiptId:F.uuid(),value:he}),ps={funnelId:F.uuid(),requestId:F.uuid(),customer:ar,customerData:or.optional(),attributes:Tt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},_E=F.discriminatedUnion("operation",[F.strictObject({operation:F.literal("decide"),...ps}).refine(jn,Nn),F.strictObject({operation:F.literal("read_decision"),decisionId:F.uuid()}),F.strictObject({operation:F.literal("evaluate_decision"),decisionId:F.uuid(),requestId:F.uuid(),nodeId:F.string().min(1).max(64),visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),receiptId:F.uuid(),policyRevision:F.number().int().nonnegative(),generation:F.string().min(1).max(256),result:ei}),F.strictObject({operation:F.literal("feature_config"),funnelId:F.uuid()}),F.strictObject({operation:F.literal("commit_decision_segment"),decisionId:F.uuid(),requestId:F.uuid(),nodeId:F.string().min(1).max(64),visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),policyRevision:F.number().int().nonnegative(),generation:F.string().min(1).max(256),steps:F.array(am).max(32),boundary:F.strictObject({nodeId:F.string().min(1).max(64),visit:F.number().int().nonnegative()}).optional()}),F.strictObject({operation:F.literal("segment_configuration"),funnelId:F.uuid(),versionId:F.uuid()}),F.strictObject({operation:F.literal("configuration"),funnelId:F.uuid(),versionId:F.uuid().optional()}),F.strictObject({operation:F.literal("local_configuration"),funnelId:F.uuid()}),F.strictObject({operation:F.literal("report_used"),decisionId:F.uuid(),eventId:F.uuid(),occurredAt:F.iso.datetime({offset:!0}),reference:F.string().min(1).max(128).optional()})]),bE=F.strictObject({scope:we,decisionId:F.uuid(),requestId:F.uuid(),status:F.enum(["pending","completed","failed"]),decision:Sy.nullable(),evaluation:F.discriminatedUnion("type",[im,om]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),yE=F.strictObject({scope:we,decisionId:F.uuid(),eventId:F.uuid(),source:F.literal("caller_reported")});import{z as Ve}from"zod";var _m=Ve.strictObject({type:Ve.literal("bundle"),paywall:Ft.optional(),offering:Ft.optional(),coupons:Ft,data:Ft}),la=e=>Ve.strictObject({type:Ve.literal(e),id:Ve.uuid()}),vy=Ve.strictObject({type:Ve.literal("bundle"),paywallVersionId:Ve.uuid().optional(),offeringVersionId:Ve.uuid().optional(),couponIds:Ve.array(Ve.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:he});function OE(e,t,n){let r=a=>En(a,t),i=Ve.array(la("reward")).max(20).parse(r(e.coupons));for(let a of[e.paywall,e.offering,e.coupons]){if(!a)continue;let o=r(a);for(let s of Array.isArray(o)?o:[o])if(!s||typeof s!="object"||Array.isArray(s)||!Object.values(n).some(c=>c.type===s.type&&c.id===s.id))throw new Error("Bundle resource outside pinned references")}return vy.parse({type:"bundle",...e.paywall?{paywallVersionId:la("paywall_version").parse(r(e.paywall)).id}:{},...e.offering?{offeringVersionId:la("offering_version").parse(r(e.offering)).id}:{},couponIds:i.map(a=>a.id),data:r(e.data)})}var PE=Ve.strictObject({type:Ve.literal("bundle"),offering:la("offering_version").nullable(),paywall:Ve.strictObject({versionId:Ve.uuid(),paywallId:Ve.uuid(),offeringVersionId:Ve.uuid()}).nullable(),coupons:Ve.array(Vr).max(20),data:he});function CE(e){let t=a=>a?.source==="literal"&&a.value&&typeof a.value=="object"&&!Array.isArray(a.value)&&typeof a.value.id=="string"?a.value.id:void 0,n=e.coupons.source==="literal"&&Array.isArray(e.coupons.value)?e.coupons.value:[],r=t(e.paywall),i=t(e.offering);return{type:"bundle",...r?{paywallVersionId:r}:{},...i?{offeringVersionId:i}:{},couponIds:n.flatMap(a=>a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?[a.id]:[]),data:e.data.source==="literal"?e.data.value:{variable:e.data.key}}}import{z as Ct}from"zod";import{z as Ze}from"zod";var bm=Ze.union([Ze.string(),Ze.number().finite(),Ze.boolean(),Ze.null()]),Iy=Ze.union([bm,Ze.array(bm).min(1).max(20)]),xy=Ze.record(bt,Iy).refine(e=>Object.keys(e).length<=10),fs=Ze.strictObject({path:bt,type:Ze.enum(["string","number","boolean","strings"]),nullable:Ze.boolean().optional(),aggregation:Ze.enum(["count","exists"]).optional(),where:xy.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});function RE(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{let i=fs.parse(r),a=Jn(t,i.path);if(i.nullable&&a==null)return[n,null];if(i.aggregation){if(!Array.isArray(a))throw new Error("Collection projection requires an array");let s=a.filter(c=>Object.entries(i.where??{}).every(([u,l])=>{let d=Jn(c,u);return Array.isArray(l)?l.some(p=>p===d):l===d}));return[n,i.aggregation==="count"?s.length:s.length>0]}let o=i.type==="strings"?Ze.array(Ze.string()):i.type==="string"?Ze.string():i.type==="number"?Ze.number().finite():Ze.boolean();return[n,o.parse(a)]}))}var Ay=["checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],ym=Ct.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Oy=Ft,Sm=Ct.discriminatedUnion("type",[cm,Ct.strictObject({type:Ct.literal("claim_offer"),coupon:Ft}),Ct.strictObject({type:Ct.literal("event"),event:ym}),Ct.strictObject({type:Ct.literal("api"),operation:Ct.enum(Ay),inputs:Ct.record(bt,Oy).refine(e=>Object.keys(e).length<=40),outputs:Ct.record(ym,fs).refine(e=>Object.keys(e).length<=20)})]);function UE(e,t){return Xl(e,t)}var De=aa,Py=M.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),pt={id:De,name:M.string().trim().min(1).max(80),position:M.strictObject({x:M.number().finite(),y:M.number().finite()}).optional()},Cy={success:De,cancel:De,unavailable:De,failure:De},hs=M.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),gs=M.enum(["same_window","new_window"]),wy=M.discriminatedUnion("type",[M.strictObject({...pt,type:M.literal("entry"),next:De}),M.strictObject({...pt,type:M.literal("screen"),screenId:De,presentation:Ht,outputs:M.record(De,De),offering:M.discriminatedUnion("source",[M.strictObject({source:M.literal("variable"),key:Me}),M.strictObject({source:M.literal("fixed"),versionId:M.uuid()})]).optional()}),M.strictObject({...pt,type:M.literal("offering"),configuration:M.discriminatedUnion("source",[M.strictObject({source:M.literal("fixed"),versionId:M.uuid()}),M.strictObject({source:M.literal("feature"),featureKey:M.string().min(1).max(128)})]),writes:M.strictObject({value:Me}),next:De}),M.strictObject({...pt,type:M.literal("coupon"),couponId:M.uuid(),writes:M.strictObject({value:Me}),next:De}),M.strictObject({...pt,type:M.literal("coupons"),couponIds:M.array(M.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:M.strictObject({value:Me}),next:De}),M.strictObject({...pt,type:M.literal("output"),value:M.discriminatedUnion("type",[...ni.options,_m,M.strictObject({type:M.literal("selection"),screenId:De,offeringKey:Me})])}),M.strictObject({...pt,type:M.literal("condition"),cases:M.array(M.strictObject({condition:Vn,target:De})).min(1).max(50),default:De}),M.strictObject({...pt,type:M.literal("feature"),featureKey:M.string().min(1).max(128),writes:M.strictObject({value:Me}),next:De}),M.strictObject({...pt,type:M.literal("split"),experimentId:M.uuid(),routes:M.record(Py,De).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:De}),M.strictObject({...pt,type:M.literal("action"),...Cy,execution:um,action:Sm,writes:Vi.optional()}),M.strictObject({...pt,type:M.literal("external_page"),appManifest:Qc.optional(),url:hs,openIn:gs,opened:De,failed:De}),M.strictObject({...pt,type:M.literal("end"),outcome:M.enum(["completed","closed","ineligible","failed"]),output:ni.optional()}),M.strictObject({...pt,type:M.literal("wait"),writes:Vi.optional(),wait:M.discriminatedUnion("type",[M.strictObject({type:M.literal("duration"),delaySeconds:M.number().int().min(1).max(2592e3),elapsed:De}),M.strictObject({type:M.literal("event"),eventName:De,outputs:ls,timeoutSeconds:M.number().int().min(1).max(2592e3),received:De,timeout:De})])})]),_s=M.strictObject({version:M.literal(5),entry:De,nodes:M.array(wy).min(1).max(yt.flowNodes)}),bs=_s.superRefine((e,t)=>{Ey(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function da(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function Ey(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,d,p)=>{n.push(l),t?.({message:l,reason:d,path:p?["nodes",e.nodes.indexOf(p)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>yt.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>yt.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let d of da(l))d===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(d)||i(`Missing target ${d}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let d of da(r.get(l)))u(d);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}function Ty(e,t){let n=e.cases.findIndex(r=>cs(r.condition,t));return{ruleIndex:n<0?null:n,target:e.cases[n]?.target??e.default}}function JE(e,t,n,r){let i=e.nodes.find(c=>c.id===t.nodeId),a=[...t.history];if(!i||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let o,s=[];switch(n.type){case"start":if(i.type!=="entry")throw new Error("Flow already started");o=i.next;break;case"next":if(i.type!=="screen"||!Object.hasOwn(i.outputs,n.output)||i.outputs[n.output]===void 0)throw new Error("Invalid screen output");{let c=i.outputs[n.output];if(c===void 0)throw new Error("Invalid screen output");o=c}a.push(i.id);break;case"back":if(i.type!=="screen"||!a.length)throw new Error("No previous screen");if(o=a.pop(),e.nodes.find(c=>c.id===o)?.type!=="screen")throw new Error("Invalid screen history");break;case"condition":if(i.type!=="condition")throw new Error("Not a condition node");{let c=Ty(i,r);o=c.target,s.push({nodeId:i.id,...c})}break;case"feature":if(i.type!=="feature")throw new Error("Not a Feature node");o=i.next;break;case"configuration":if(i.type!=="offering"&&i.type!=="coupon")throw new Error("Not a configuration node");o=i.next;break;case"assignment":if(i.type!=="split")throw new Error("Not an Experiment node");{let c=n.variantId===null?i.notParticipating:i.routes[n.variantId];if(!c)throw new Error("Unknown native Variant key");o=c}break;case"result":if(i.type!=="action")throw new Error("Not a capability invocation");o=i[n.result];break;case"page":if(i.type!=="external_page")throw new Error("Not an external page");o=i[n.result];break;case"wait":if(i.type!=="wait")throw new Error("Not a wait node");if(i.wait.type==="duration"){if(n.result!=="elapsed")throw new Error("Invalid timer result");o=i.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid event result");o=i.wait[n.result]}break}if(!e.nodes.some(c=>c.id===o))throw new Error("Target does not exist");return{state:{nodeId:o,history:a.slice(-yt.pages),status:"running"},entered:[o],routed:s}}var ma={maxTransitions:1e4,runTimeoutSeconds:2592e3},eT={detailBytes:16384};function vm(e,t){return Number.isInteger(e)&&e>=1&&e<=ma.maxTransitions&&Number.isInteger(t)&&t>=0&&t<e}var tT="Run transition budget exhausted";function nT(e,t,n){return vm(e,t)||n&&vm(e,t-1)}function Im(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of ti(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as C}from"zod";var cr=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),pa=e=>C.record(C.string(),he).refine(t=>ct(t)<=e,"Funnel evidence exceeds its byte budget"),uT=C.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Ss=C.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),ri=C.discriminatedUnion("type",[C.strictObject({type:C.literal("flag"),key:C.string().min(1).max(128)}),C.strictObject({type:C.literal("experiment"),id:C.uuid()}),C.strictObject({type:C.literal("saved_group"),id:C.uuid()}),C.strictObject({type:C.literal("config"),key:C.string().min(1).max(128)}),C.strictObject({type:C.literal("constant"),key:C.string().min(1).max(128)}),C.strictObject({type:C.literal("paywall_version"),id:C.uuid()}),C.strictObject({type:C.literal("offering_version"),id:C.uuid()}),C.strictObject({type:C.literal("reward"),id:C.uuid()})]),ur=C.strictObject({schemaVersion:C.literal(1),kind:Ss,selector:ri.nullable(),context:pa(131072),contract:C.strictObject({version:C.number().int().positive(),evaluator:C.string().min(1).max(128),policyRevision:C.number().int().nonnegative()})}).refine(e=>ct(e)<=131072,"Node input exceeds its byte budget"),xm=C.strictObject({schemaVersion:C.literal(1),kind:Ss,outcome:C.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:pa(131072),route:C.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:pa(131072)}).refine(e=>ct(e)<=131072,"Node result exceeds its byte budget"),lT=C.strictObject({schemaVersion:C.literal(1),operations:C.record(cr,C.strictObject({attempts:C.number().int().nonnegative(),maxAttempts:C.number().int().min(1).max(5),deadlineAt:C.iso.datetime({offset:!0}),retryAt:C.iso.datetime({offset:!0}).nullable(),error:C.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:C.strictObject({type:cr,id:C.uuid()}).nullable()}))}).refine(e=>ct(e)<=65536,"Execution state exceeds its byte budget"),kn={receiptId:C.uuid()},ys=C.iso.datetime({offset:!0}),dT=C.discriminatedUnion("type",[C.strictObject({type:C.literal("node_entered"),details:C.strictObject({kind:Ss})}),C.strictObject({type:C.literal("presentation_shown"),details:C.strictObject({...kn,source:C.literal("client"),occurredAt:ys.optional()})}),C.strictObject({type:C.literal("decision_accepted"),details:C.strictObject(kn)}),C.strictObject({type:C.literal("signal_received"),details:C.strictObject({signalId:C.uuid(),nodeId:cr,eventName:cr,data:pa(8192),source:C.literal("server"),occurredAt:ys})}),C.strictObject({type:C.literal("signal_consumed"),details:C.strictObject({...kn,signalId:C.uuid()})}),C.strictObject({type:C.literal("wait_elapsed"),details:C.strictObject(kn)}),C.strictObject({type:C.literal("wait_timeout"),details:C.strictObject(kn)}),C.strictObject({type:C.literal("operation_completed"),details:C.strictObject({...kn,operation:cr,reference:C.strictObject({type:cr,id:C.uuid()}).nullable()})}),C.strictObject({type:C.literal("execution_recovered"),details:C.strictObject({generation:C.number().int().positive(),reason:C.enum(["interrupted","expired_lease","delivery_failed"])})}),C.strictObject({type:C.literal("execution_failed"),details:C.strictObject({generation:C.number().int().positive(),code:C.string().regex(/^[a-z_]{1,64}$/)})}),C.strictObject({type:C.literal("run_completed"),details:C.strictObject({outcome:C.enum(["completed","ineligible","failed"])})}),C.strictObject({type:C.literal("run_closed"),details:C.strictObject({source:C.enum(["client","server","expiry"])})}),C.strictObject({type:C.literal("treatment_used"),details:C.strictObject({...kn,source:C.enum(["client","server"]),occurredAt:ys,reference:C.string().min(1).max(128).optional()})})]);var St=T.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ry=T.discriminatedUnion("type",[T.strictObject({id:St,type:T.literal("owned"),publicData:Xd.optional(),document:ze.refine(e=>["page","popup","onboarding"].includes(e.surface)&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),T.strictObject({id:St,type:T.literal("paywall"),paywallVersionId:T.uuid()})]),Is={kind:T.literal("funnel"),schemaVersion:T.literal(4),screens:T.array(Ry).max(yt.pages),references:T.record(St,ri).refine(e=>Object.keys(e).length<=500),inputs:T.array(T.strictObject({variable:St,screenId:St,componentId:St,required:T.boolean()})).max(yt.questions),variables:T.record(Me,Yn).refine(e=>Object.keys(e).length<=yt.logicNodes),outputSchema:Zn,execution:T.strictObject({runTimeoutSeconds:T.number().int().min(1).max(ma.runTimeoutSeconds),maxTransitions:T.number().int().min(1).max(ma.maxTransitions)})},ga=T.strictObject({...Is,graph:_s});function jy(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function ha(e){return Array.isArray(e)?e.some(ha):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===lm:ha(n))}function Ny(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=na(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!kr(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),jy(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&ha(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ha(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function Am(e,t){for(let{message:n,reason:r,path:i}of Ny(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function Om(e,t){let n=(g,m,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:m}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,m)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===m);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(m=>g!==m&&m.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,m){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(m)]);let h=s.get(g)??new Set;h.add(m.id),s.set(g,h)}for(let[g,m]of e.graph.nodes.entries()){let h=["graph","nodes",g],y=m.type==="feature"?m.featureKey:m.type==="offering"&&m.configuration.source==="feature"?m.configuration.featureKey:m.type==="output"&&m.value.type==="feature"?m.value.featureKey:m.type==="end"&&m.output?.type==="feature"?m.output.featureKey:null;y&&!a("flag",y)&&n("Flag selectors require an explicit GB resource reference","feature",h);let x=m.type==="feature"||m.type==="offering"||m.type==="coupon"||m.type==="coupons"||m.type==="action"&&m.action.type==="api"?["value"]:m.type==="action"&&m.action.type==="external_task"?Object.keys(m.action.outputs):m.type==="wait"&&m.wait.type==="event"?Object.keys(m.wait.outputs):[],v="writes"in m?m.writes??{}:{};(x.length!==Object.keys(v).length||x.some(A=>!Object.hasOwn(v,A))||new Set(Object.values(v)).size!==Object.values(v).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[A,S]of Object.entries(v)){u(S,m);let q=e.variables[S],L=m.type==="offering"?"offering_version":m.type==="coupon"?"reward":m.type==="action"&&m.action.type==="api"?"json":m.type==="action"&&m.action.type==="external_task"?m.action.outputs[A]:m.type==="wait"&&m.wait.type==="event"?m.wait.outputs[A]:void 0;(q?.source.type!=="node"||L&&q.type!==L)&&n("Node writer source or output type does not match declaration","variable",h)}if(m.type==="coupons"){let A=e.variables[m.writes.value];(A?.type!=="array"||A.items?.type!=="reward"||A.items.nullable||A.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let S of m.couponIds)a("reward",S)||n("Coupons require Reward references","coupon",h)}if(m.type==="split"&&!a("experiment",m.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),m.type==="coupon"&&!a("reward",m.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),m.type==="action"&&m.action.type==="claim_offer"&&m.action.coupon.source==="literal"){let A=m.action.coupon.value;(!A||typeof A!="object"||Array.isArray(A)||A.type!=="reward"||typeof A.id!="string"||Object.keys(A).length!==2||!a("reward",A.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(m.type==="offering"&&m.configuration.source==="fixed"&&!a("offering_version",m.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),m.type==="screen"&&m.offering?.source==="variable"&&e.variables[m.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),m.type==="action"&&m.action.type==="claim_offer"&&m.action.coupon.source==="variable"&&(e.variables[m.action.coupon.key]?.type!=="reward"||m.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),m.type==="screen"){let A=i.get(m.screenId);if(m.offering?.source==="fixed"&&!a("offering_version",m.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),A?.type==="paywall"&&m.offering&&n("Paywall owns its fixed Offering Version","offering",h),A?.type==="paywall"&&!a("paywall_version",A.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),A?.type==="owned"){let S=A.document.pages[0];if(!S){n("Owned screen requires a page","screen",h);continue}Jt(A.document).some(L=>!L.complete)&&n("Owned screens require complete local content","translations",h);let q=new Set(A.document.actions.map(L=>L.id));(q.size!==Object.keys(m.outputs).length||Object.keys(m.outputs).some(L=>!q.has(L)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),Nr(S.root,L=>{!m.offering&&(L.type==="plan_picker"||(L.type==="stack"||L.type==="button")&&L.bind?.plan||L.type==="customer_data"&&["customer_plans","credit_packs"].includes(L.data.source))&&n("Product presentation requires an Offering Version","offering",h),L.type==="customer_data"&&Object.values(L.data.outputs??{}).some(ge=>ge!==void 0&&!q.has(ge))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}m.type==="end"&&["completed","ineligible"].includes(m.outcome)&&!m.output&&n("Completed and ineligible ends require a declared output","output",h),m.type==="end"&&m.output?.type==="literal"&&!mt(e.outputSchema,m.output.value)&&n("Terminal output does not match outputSchema","output",h),m.type==="output"&&m.value.type==="literal"&&!mt(e.outputSchema,m.value.value)&&n("Terminal output does not match outputSchema","output",h);let E=m.type==="output"?m.value:m.type==="end"?m.output:void 0;if(E?.type==="variable"&&!E.path){let A=e.variables[E.key];A&&!Lo(A,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(m.type==="screen"){let A=i.get(m.screenId);if(A?.type==="owned")for(let S of qo(A.document))(/^(input|params)\./.test(S)||S.startsWith("variables.")&&!qi(S.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(m.type==="condition")for(let A of m.cases){for(let S of qn(A.condition))a("saved_group",S)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let S of ti(A.condition))S.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(m.type==="output"&&m.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[A,S]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let q=m.value[A];if(q)if(q.source==="literal"){let L=A==="coupons"?q.value:[q.value];(!Array.isArray(L)||L.length>20||L.some(ge=>!mt({type:S,nullable:!1},ge)||!a(S,ge.id))||A==="coupons"&&new Set(L.map(ge=>ge.id)).size!==L.length)&&n("Bundle requires distinct scoped resource references",A==="coupons"?"coupon":A==="paywall"?"paywall":"offering",[...h,"value",A])}else{let L=e.variables[q.key];(q.path||!L||L.nullable||(A==="coupons"?L.type!=="array"||L.items?.type!=="reward"||L.items.nullable:L.type!==S))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,m]of e.graph.nodes.entries()){let h=m.type==="screen"?i.get(m.screenId):void 0,y=[...Im(m,c),...h?.type==="owned"?Qr(h.document).map(x=>qi(x,c)?.key??x):[]];for(let x of new Set(y)){let S=function(q){if(q===m.id)return!0;if(A.has(q))return!1;A.add(q);let L=e.graph.nodes.find(Ie=>Ie.id===q);return L?(E.has(q)?L.type==="action"?[L.cancel,L.unavailable,L.failure]:L.type==="wait"&&L.wait.type==="event"?[L.wait.timeout]:[]:da(L)).some(S):!1};var p=S;if(!Object.hasOwn(e.variables,x)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let v=e.variables[x];if(m.type==="screen"&&v.source.type==="input"&&e.inputs.some(q=>q.screenId===m.screenId&&q.variable===x)||v.source.type==="parameter"||v.source.type==="attribute")continue;let E=v.source.type==="input"?new Set(e.inputs.filter(q=>q.variable===x&&q.required).flatMap(q=>o.filter(L=>L.screenId===q.screenId).map(L=>L.id))):s.get(x)??new Set,A=new Set;(!E.size||S(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,m]of e.inputs.entries()){e.variables[m.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(m.screenId),y=h?.type==="owned"?kr(h.document,m.componentId):null;if((y?.type!=="stack"||!y.interaction||!["input","toggle","select","multiselect","tabs"].includes(y.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),y?.type==="stack"&&y.interaction){let x=y.interaction.type==="toggle"?"boolean":y.interaction.type==="multiselect"?"strings":"string";e.variables[m.variable]?.type!==x&&n("Input variable type does not match component","inputBinding",["inputs",g]);let v=e.variables[m.variable]?.enum;v&&!y.children.filter(E=>!E.hidden).every(E=>v.includes(E.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,m]of Object.entries(e.variables))m.enum&&m.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),m.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,d=0;for(let g of e.screens)if(g.type==="owned"){for(let m of g.document.pages)Nr(m.root,()=>{l++});d+=g.document.actions.length}(l>yt.components||d>yt.actions||ct(e)>yt.documentBytes)&&n("Funnel document exceeds its budget","budget")}var ky=T.strictObject({...Is,graph:bs}).superRefine(Om),Ut=T.strictObject({...Is,graph:bs,displayName:T.string().trim().min(1).max(80)}).superRefine(Om),Pm=Ut.superRefine(Am),TT=ky.superRefine(Am),fa=T.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),lr={requestId:T.uuid(),nodeId:St,visit:T.number().int().nonnegative(),revision:T.number().int().nonnegative(),customerToken:fa.optional()},Dy=T.discriminatedUnion("type",[T.strictObject({type:T.literal("screen"),output:St,answers:vn,selection:T.record(St,T.union([T.string().max(200),T.boolean()])).optional()}),T.strictObject({type:T.literal("paywall_quote"),actionId:St,productVersionId:T.uuid(),offerId:T.uuid().optional(),nativeOffer:an.optional(),predecessor:T.strictObject({operationId:T.uuid().nullable(),generation:T.number().int().positive()}).optional()}),T.strictObject({type:T.literal("paywall_confirm"),operationId:T.uuid()}),T.strictObject({type:T.literal("paywall_cancel"),operationId:T.uuid()}),T.strictObject({type:T.literal("client_action"),receiptId:T.uuid(),outcome:T.enum(["success","cancel","failure","opened","failed"])})]),Fy=T.object({nodeId:St,visit:T.number().int().nonnegative(),revision:T.number().int().nonnegative(),components:T.record(St,T.object({resourceKey:T.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:T.number().int().min(1).max(1e5),after:Ii.nullable(),filter:T.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),RT=T.discriminatedUnion("operation",[T.strictObject({operation:T.literal("start"),funnelId:T.uuid(),requestId:T.uuid(),customer:ar.optional(),customerData:or.optional(),locale:T.string().min(1).max(35),parameters:jt}).refine(jn,Nn),T.strictObject({operation:T.literal("get"),settlementRequestId:T.uuid().optional(),data:Fy.optional(),purchase:T.strictObject({receiptId:T.uuid(),operationId:T.uuid()}).optional(),customerToken:fa.optional()}),T.strictObject({operation:T.literal("resume"),requestId:T.uuid(),customerToken:fa.optional()}),T.strictObject({operation:T.literal("submit"),...lr,input:Dy}),T.strictObject({operation:T.literal("back"),...lr}),T.strictObject({operation:T.literal("shown"),...lr}),T.strictObject({operation:T.literal("close"),...lr}),T.strictObject({operation:T.literal("commit_segment"),...lr,policyRevision:T.number().int().nonnegative(),generation:T.string().min(1).max(256)}),T.strictObject({operation:T.literal("evaluate"),...lr,receiptId:T.uuid(),policyRevision:T.number().int().nonnegative(),generation:T.string().min(1).max(256),result:ei}),T.strictObject({operation:T.literal("review"),receiptId:T.uuid().optional(),customerToken:fa.optional()})]);function vs(e,t){if(!e||e.hidden)return null;if(e.id===t)return e;if(e.type!=="stack")return null;for(let n of e.children){let r=vs(n,t);if(r)return r}return null}function Uy(e,t,n,r,i){let a=e.graph.nodes.find(u=>u.id===t);if(a?.type!=="screen")throw new Error("Input is only accepted on a screen");let o=e.screens.find(u=>u.id===a.screenId),s=e.inputs.filter(u=>u.screenId===a.screenId),c={...r};for(let[u,l]of Object.entries(n)){let d=s.find(h=>h.variable===u);if(!d||o?.type!=="owned")throw new Error("Unknown screen input");let p=vs(o.document.pages[0]?.root,d.componentId);if(p?.type!=="stack"||!p.interaction)throw new Error("Input is unavailable");let g=p.interaction;switch(g.type){case"input":if(typeof l!="string"||l.length>g.maxLength)throw new Error("Invalid input text");if(l&&g.keyboard==="email"&&!T.email().safeParse(l).success)throw new Error("Invalid email");if(l&&g.keyboard==="url"&&!T.url().safeParse(l).success)throw new Error("Invalid URL");break;case"toggle":if(typeof l!="boolean")throw new Error("Invalid toggle value");break;case"select":case"tabs":if(typeof l!="string"||!p.children.some(h=>h.id===l&&!h.hidden))throw new Error("Invalid selected option");break;case"multiselect":if(!Array.isArray(l)||new Set(l).size!==l.length||l.length>g.max||i&&l.length<g.min||l.some(h=>!p.children.some(y=>y.id===h&&!y.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}let m=e.variables[u];if(m?.source.type!=="input"||!mt(m,l))throw new Error("Invalid input variable");c[u]=l}if(i)for(let u of s){let l=c[u.variable];if(u.required&&(l===void 0||l===""||Array.isArray(l)&&l.length===0))throw new Error(`Required input: ${u.variable}`);l!==void 0&&!Object.hasOwn(n,u.variable)&&Uy(e,t,{[u.variable]:l},{},!1);let d=o?.type==="owned"?vs(o.document.pages[0]?.root,u.componentId):null;if(d?.type==="stack"&&d.interaction?.type==="multiselect"&&Array.isArray(l)&&l.length<d.interaction.min)throw new Error("Not enough selected options")}return c}function _a(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(m){for(let h of qn(m))l(h)}function l(m){if(i.has(m)||!Object.hasOwn(t.savedGroups,m))return;let h=t.savedGroups[m];h&&(i.add(m),c.set(m,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function d(m){for(let h of["hashAttribute","fallbackAttribute"])if(m[h]!==void 0&&ss(m[h]))throw new Error(`Funnel GB ${h} uses a reserved flow namespace`);u(m.condition);for(let h of m.parentConditions??[])p(h.id),u(h.condition)}function p(m,h=!1){let y=Object.hasOwn(t.features,m)?t.features[m]:void 0;if(!y){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(m)||(n.add(m),o.set(m,y),a.push(()=>{for(let x of y.rules??[]){d(x);for(let v of x.tracks??[])d(v.experiment)}}))}function g(m){let h=Object.hasOwn(t.experiments,m)?t.experiments[m]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(m)||(r.add(m),s.set(m,h),a.push(()=>d(h)))}for(let m of e.graph.nodes){m.type==="feature"&&p(m.featureKey,!0),m.type==="split"&&g(m.experimentId),m.type==="condition"&&m.cases.forEach(y=>u(y.condition)),m.type==="offering"&&m.configuration.source==="feature"&&p(m.configuration.featureKey,!0);let h=m.type==="output"?m.value:m.type==="end"?m.output:null;h?.type==="feature"&&p(h.featureKey,!0)}for(let m of a)m();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as K}from"zod";import{z as ii}from"zod";var Cm=ii.object({defaultLocale:$t,locales:ii.record($t,ii.object({name:ii.string().max(80),description:ii.string().max(500)}).strict())}).strict().superRefine((e,t)=>{let n=Object.keys(e.locales);(!n.length||n.length>20||!e.locales[e.defaultLocale])&&t.addIssue({code:"custom",message:"Invalid content languages"}),new TextEncoder().encode(JSON.stringify(e)).length>5e4&&t.addIssue({code:"custom",message:"Content exceeds 50 KB"})});function BT(e,t){let n=e.displayCopy;if(!n)return{name:e.name,description:""};let r=Object.keys(n.locales).filter(s=>n.locales[s]?.name.trim()),i=Oc([t],r,n.defaultLocale),a=n.locales[i],o=n.locales[n.defaultLocale];return{name:a?.name.trim()?a.name:o?.name.trim()?o.name:e.name,description:a?.description.trim()?a.description:o?.description.trim()?o.description:""}}var My=["customer_data","coupon_code"],By=K.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),wm=K.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),ba=(e,t)=>new Set(e.map(t)).size===e.length,Ly=K.strictObject({currency:se,amountMinor:K.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Vy=K.strictObject({featureId:K.uuid(),name:K.string().trim().min(1).max(120),allowance:K.string().max(40).nullable(),access:K.boolean()}),qy=K.strictObject({stripe:K.strictObject({prices:K.array(Ly).min(1).max(50)}).optional(),apple:K.strictObject({productIds:K.array(By).min(1).max(10)}).optional(),google:K.strictObject({products:K.array(K.strictObject({productId:wm,basePlanId:wm.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!ba(e.stripe.prices,n=>n.currency)||e.apple&&!ba(e.apple.productIds,n=>n)||e.google&&!ba(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),$y=K.strictObject({name:K.string().trim().min(1).max(80),interval:K.enum(["free","week","month","year","one_time"]),intervalCount:K.number().int().min(1).max(100),trial:K.strictObject({days:K.number().int().min(1).max(730),cardRequired:K.boolean()}).nullable(),benefits:K.array(Vy).max(50).refine(e=>ba(e,t=>t.featureId),"Duplicate benefit"),channels:qy}),Gy=K.strictObject({digest:sn,content:K.strictObject({discount:en,duration:dt,appliesTo:Mi,displayCopy:Cm.nullable(),firstPurchaseOnly:K.boolean(),qualificationRequired:K.boolean(),startsAt:K.iso.datetime().nullable(),endsAt:K.iso.datetime().nullable(),grantWindowHours:K.number().int().positive(),perCustomerLimit:K.number().int().positive()})}),Ky=K.discriminatedUnion("type",[K.strictObject({type:K.literal("checkout"),product:ea}),K.strictObject({type:K.literal("close")}),K.strictObject({type:K.literal("action"),action:ts})]),Em=K.strictObject({kind:K.literal("paywall"),formatVersion:K.literal(1),name:K.string().trim().min(1).max(80),offeringVersionId:K.uuid(),presentation:Ht,screen:ze,products:zi,catalog:K.record(K.uuid(),$y),buttons:K.record(jr,Ky),coupons:K.record(K.uuid(),Gy)}).superRefine((e,t)=>{let n=h=>t.addIssue({code:"custom",message:h}),{screen:r}=e;r.surface!=="paywall"&&n("Screen must be a Paywall"),is(r,My).forEach(n),Jt(r).some(h=>!h.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Rt(r,h=>{let y="bind"in h?h.bind:void 0;y?.promotionCode&&n("Promotion codes must not be published"),y?.plan&&i.add(y.plan),y?.coupon&&a.add(y.coupon),h.type==="plan_picker"&&(h.planIds?.forEach(x=>i.add(x)),h.defaultPlan&&i.add(h.defaultPlan)),h.type==="text"&&h.feature&&o.add(h.feature.id)});let s=e.products.items.map(h=>h.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(h=>!Object.hasOwn(e.catalog,h)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let h of i)u.has(h)||n("Screen references a Product that is not displayed");for(let h of Object.values(e.catalog))!h.channels.stripe&&!h.channels.apple&&!h.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(h=>h.benefits.map(y=>y.featureId)));for(let h of o)l.has(h)||n("Feature text must read a displayed benefit");let d=r.actions.filter(h=>h.type!=="navigate");r.actions.some(h=>h.type!=="event"&&h.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==d.length||d.some(h=>!Object.hasOwn(e.buttons,h.id)))&&n("Buttons must match the screen's actions");let g=!1;for(let h of Object.values(e.buttons)){if(h.type!=="checkout")continue;g=!0,(h.product.type==="fixed"?[h.product.productVersionId]:h.product.allowedProductVersionIds).some(x=>!u.has(x))&&n("Checkout may only sell displayed Products")}g||n("A Paywall needs a checkout button");let m=Object.keys(e.coupons);(m.length!==a.size||m.some(h=>!a.has(h)))&&n("Coupons must be exactly the bound Coupons")}),Tm=K.strictObject({state:K.enum(["published","archived"]),controlRevision:K.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:K.uuid(),versions:K.record(K.uuid(),K.strictObject({version:K.number().int().positive(),artifact:K.string().min(1),sourceDigest:K.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Hy={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},xs=ce.string().regex(/^[a-f0-9]{64}$/),As=ce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Wy=we.extend({environmentId:ce.uuid()}),Rm=ce.strictObject({features:ce.array(ce.string()).max(500),experiments:ce.record(ce.uuid(),ce.array(ce.string()).max(20)),savedGroups:ce.array(ce.string()).max(1e3)}),Ps=ce.strictObject({kind:ce.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:ce.number().int().positive(),url:ce.string().min(1).max(2048),sha256:xs,byteLength:ce.number().int().positive().max(Hy.maxArtifactBytes),generation:xs.optional()}),Qy=ce.strictObject({state:ce.enum(["active","paused","archived"]),controlRevision:As,evaluationMode:ce.enum(["local","remote"]),evaluationRevision:As,currentVersionId:ce.uuid(),versions:ce.record(ce.uuid(),ce.strictObject({artifact:ce.string(),dependencies:Rm,definitionDigest:sn.optional(),couponDigests:ce.record(ce.uuid(),sn).optional()}))}),sR=ce.strictObject({kind:ce.literal("sdk_configuration"),schemaVersion:ce.literal(1),scope:Wy,revision:As,generation:xs,policy:ce.strictObject({refreshIntervalSeconds:ce.number().positive().max(15),maxControlAgeSeconds:ce.number().positive().max(60)}),gb:ce.strictObject({features:ce.string().nullable(),pageExperiments:ce.string().nullable()}),artifacts:ce.record(ce.string(),Ps),funnels:ce.record(ce.uuid(),Qy),paywalls:ce.record(ce.uuid(),Tm).optional()}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function Os(e){if(Array.isArray(e))return`[${e.map(Os).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Os(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Zy(e){return gi(_i(typeof e=="string"?new TextEncoder().encode(e):e))}function cR(e){return Zy(Os(e))}function uR(e,t){for(let o of Object.values(e.references))if(o.type==="flag"&&(!Object.hasOwn(t.features,o.key)||t.remoteFeatures.includes(o.key))||o.type==="experiment"&&!Object.hasOwn(t.experiments,o.id)||o.type==="saved_group"&&!Object.hasOwn(t.savedGroups,o.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=_a(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let o of e.graph.nodes){let s=o.type==="feature"?o.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=o.type==="feature"?e.variables[o.writes.value]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(d=>[...Object.hasOwn(d,"force")?[d.force]:[],...d.variations??[],...(d.tracks??[]).flatMap(p=>p.experiment.variations)])].some(d=>d===void 0||!mt(u,d)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of qn(o)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&a(c.condition)}};for(let o of e.graph.nodes)if(o.type==="condition")for(let s of o.cases)a(s.condition);for(let o of Object.values(n.features))for(let s of o.rules??[]){a(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}for(let c of s.tracks??[])a(c.experiment.condition)}for(let o of Object.values(n.experiments)){a(o.condition);for(let s of o.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");a(s.condition)}}for(let o of e.graph.nodes)if(o.type==="split"){let s=n.experiments[o.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!o.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return Rm.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([o,s])=>[o,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function lR(e){return Ut.parse(e)}var jm=Le.strictObject({...Xn,selector:Le.discriminatedUnion("type",[Le.strictObject({type:Le.literal("paywall"),paywallId:Le.uuid()}),Le.strictObject({type:Le.literal("version"),versionId:Le.uuid()})]),customerId:Le.uuid().optional(),commerce:vi,locale:Le.string().min(1).max(35),requirement:Gn.optional()}),ai=Le.strictObject({id:Le.uuid(),paywallId:Le.uuid(),version:Le.number().int().positive(),document:rr.omit({requirement:!0,offeringId:!0}),offering:Le.strictObject({id:Le.uuid()}),content:Le.strictObject({environmentId:Le.uuid(),offeringVersionId:Le.uuid(),artifact:Ps.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Kn,check:Rr.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),dr=Le.strictObject(ai.shape).omit({document:!0,offering:!0}).extend({content:ai.shape.content.unwrap()});function Nm(e){let{document:t,offering:n,...r}=e;return dr.parse(r)}function vR(e,t){let n=Em.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");return ai.parse({...e,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as nt}from"zod";var km={requestId:nt.uuid(),sourceId:nt.uuid(),expectedAvailable:$n},Dm=nt.discriminatedUnion("action",[nt.strictObject({...km,action:nt.enum(["add","subtract","set_remaining"]),amount:_e}),nt.strictObject({...km,action:nt.literal("edit"),granted:_e,expiresAt:nt.iso.datetime({offset:!0}).nullable(),nextResetAt:nt.iso.datetime({offset:!0}).nullable(),expectedRevision:nt.number().int().nonnegative()})]),Cs=nt.strictObject({sourceId:nt.uuid(),available:$n,held:$n,spent:$n,adjustmentGrantId:nt.uuid().nullable()}),Fm=Cs.extend({granted:$n,expiresAt:nt.iso.datetime({offset:!0}).nullable(),nextResetAt:nt.iso.datetime({offset:!0}).nullable(),revision:nt.number().int().nonnegative()});import{z as ft}from"zod";var Um=ft.discriminatedUnion("action",[ft.object({action:ft.literal("upsert"),externalId:ft.string().min(1).max(128),name:ft.string().trim().min(1).max(80)}).strict(),ft.object({action:ft.literal("archive"),entityId:ft.uuid()}).strict()]),Mm=ft.object({id:ft.uuid(),externalId:ft.string().min(1).max(128),name:ft.string().min(1).max(80),archived:ft.boolean()}).strict();import{z as Ye}from"zod";import{z as Fn}from"zod";var Lm=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Bm=Fn.string().regex(/.+\/.+/),ws=Fn.number().min(-100),Dn=Fn.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Yy=Fn.strictObject({input:Dn,output:Dn,cache_read:Dn.optional(),cache_write:Dn.optional(),reasoning:Dn.optional(),input_audio:Dn.optional(),output_audio:Dn.optional()}),Es=(e,t)=>Fn.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),TR=Fn.strictObject({defaultMarkup:ws,providerMarkups:Es(Fn.string().min(1),ws),modelMarkups:Es(Bm,ws),customModels:Es(Bm,Yy.partial())});import{z as ee}from"zod";var Un=ee.iso.datetime({offset:!0}),cn=ee.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Jy=ee.discriminatedUnion("kind",[ee.object({kind:ee.literal("absolute"),from:Un,to:Un}).strict(),ee.object({kind:ee.literal("last_days"),days:ee.union([ee.literal(1),ee.literal(7),ee.literal(30),ee.literal(90)])}).strict(),ee.object({kind:ee.literal("billing_cycles"),membershipId:ee.uuid(),count:ee.number().int().min(1).max(12),includeCurrent:ee.boolean()}).strict()]),Vm=ee.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),Xy=ee.object({key:ee.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:ee.array(ee.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Mn=ee.object({range:Jy,timezone:Vm,filterBy:ee.array(Xy).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:ee.enum(["hour","day","week","month"]),internal_feature_id:ee.uuid().nullable(),entityId:ee.uuid().nullable(),topN:ee.number().int().min(1).max(50).nullable(),groupBy:ee.union([ee.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),ee.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:ee.object({bucket:Un,group:ee.string().max(240),isOther:ee.boolean(),internal_feature_id:ee.uuid(),resourceId:ee.uuid()}).strict().nullable(),limit:ee.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),qm=ee.object({from:Un,to:Un,interval:ee.enum(["hour","day","week","month"]),timezone:Vm,rows:ee.array(ee.object({bucket:Un,group:ee.string().max(240),isOther:ee.boolean(),internal_feature_id:ee.uuid(),resourceId:ee.uuid(),consumedUnits:cn,refundedUnits:cn,reservedUnits:cn,charged:cn,refunded:cn,reserved:cn,netUnits:cn,netCharged:cn}).strict()).max(100),nextCursor:ee.object({bucket:Un,group:ee.string().max(240),isOther:ee.boolean(),internal_feature_id:ee.uuid(),resourceId:ee.uuid()}).strict().nullable()}).strict();var mr=Ye.string().regex(/^(0|[1-9]\d{0,29})$/),$m=Ye.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ts=Ye.strictObject({bucket:Ye.iso.datetime({offset:!0}),group:Ye.string().max(240),isOther:Ye.boolean(),internal_feature_id:Ye.uuid()}),Gm=Ye.strictObject({...Mn.shape,groupBy:Ye.union([Ye.enum(["customer","entity","entitlement"]),Ye.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ts.nullable()}).superRefine((e,t)=>{let n=Mn.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Km=Ye.strictObject({from:Ye.iso.datetime({offset:!0}),to:Ye.iso.datetime({offset:!0}),interval:Mn.shape.interval,timezone:Mn.shape.timezone,rows:Ye.array(Ye.strictObject({...Ts.shape,eventCount:mr,units:$m,tokenEventCount:mr,tokens:Ye.strictObject(Object.fromEntries(Lm.map(e=>[e,mr]))),totalTokens:mr,providerCostEventCount:mr,providerCostUsd:$m,invalidTelemetryEventCount:mr})).max(100),nextCursor:Ts.nullable()});import{z as Ue}from"zod";var Hm=Ue.object({requestId:Ue.uuid(),items:Ue.array(Ue.object({customerId:Ue.uuid(),command:Er.options[1]}).strict()).min(1).max(1e3)}).strict().refine(e=>new Set(e.items.map(t=>t.customerId+":"+t.command.idempotencyKey)).size===e.items.length,"Each logical event must appear once in a batch"),Wm=Ue.object({batchId:Ue.uuid(),after:Ue.number().int().min(-1).max(999),limit:Ue.number().int().min(1).max(100)}).strict(),Qm=Ue.object({batchId:Ue.uuid(),status:Ue.enum(["queued","complete"]),total:Ue.number().int().min(1).max(1e3),processed:Ue.number().int().min(0).max(1e3),items:Ue.array(Ue.object({position:Ue.number().int().min(0).max(999),customerId:Ue.uuid(),idempotencyKey:Ue.string().min(1).max(120),status:Ue.enum(["queued","accepted","rejected","failed"]),receipt:Tr.nullable(),errorCode:Ue.enum(["invalid_request","forbidden","conflict","internal_error"]).nullable()}).strict().refine(e=>e.status==="queued"?e.receipt===null&&e.errorCode===null:e.status==="failed"?e.receipt===null&&e.errorCode!==null:e.receipt!==null&&e.errorCode===null&&e.receipt.accepted===(e.status==="accepted"))).max(100),nextAfter:Ue.number().int().min(0).max(999).nullable()}).strict();import{z as I}from"zod";var zy=I.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Zm=I.enum(["draft","active","paused","archived"]),Ym=I.string().min(1).max(256),Jm=I.array(Ym).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),eS=I.strictObject({duration:I.enum(["day","week","month","year"]),length:I.number().int().min(1).max(3660)}),tS=I.strictObject({internal_feature_id:I.uuid(),allowance:I.number().nonnegative().max(1e15).nullable(),expiry:eS.nullable()}),nS=I.discriminatedUnion("type",[I.strictObject({type:I.literal("feature_grant"),grants:I.array(tS).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),I.strictObject({type:I.literal("free_product"),productId:Ym,duration:dt}),I.strictObject({type:I.literal("invoice_credits"),amount:I.number().positive().max(1e8),duration:dt,rollover:I.boolean(),productIds:Jm})]),rS=I.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Xm=I.object({key:rS,name:I.string().trim().min(1).max(80),configuration:nS}).strict(),zm=I.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Rs=I.object({code:zm,maxUses:I.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:I.boolean()}).strict(),ep=I.object({key:I.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:I.string().trim().min(1).max(80),rewardId:I.uuid(),redeemOn:I.enum(["customer_creation","checkout"]),receivedBy:I.enum(["referrer","all"]),maxRedemptions:I.number().int().min(1).max(1e6).nullable(),productIds:Jm,excludeTrial:I.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),tp={id:I.uuid(),projectId:I.uuid(),environmentId:I.uuid(),revision:I.number().int().nonnegative(),status:Zm,createdAt:I.iso.datetime({offset:!0}),updatedAt:I.iso.datetime({offset:!0})},iS=Xm.extend(tp).strict(),aS=ep.safeExtend(tp).strict(),GR=I.strictObject({id:I.uuid(),key:I.string(),name:I.string(),type:zy,status:Zm}),KR=I.discriminatedUnion("action",[I.object({action:I.literal("save"),id:I.uuid().nullable(),revision:I.number().int().nonnegative(),input:Xm}).strict(),I.object({action:I.enum(["activate","pause","resume","archive","delete"]),id:I.uuid(),revision:I.number().int().nonnegative()}).strict()]),HR=I.discriminatedUnion("action",[I.object({action:I.literal("save"),id:I.uuid().nullable(),revision:I.number().int().nonnegative(),input:ep}).strict(),I.object({action:I.enum(["activate","pause","resume","archive","delete"]),id:I.uuid(),revision:I.number().int().nonnegative()}).strict()]),np=I.object({id:I.uuid(),rewardId:I.uuid(),programId:I.uuid().nullable(),customerId:I.uuid(),referrerId:I.uuid().nullable(),status:I.enum(["pending","applied","unavailable"]),result:I.record(I.string(),I.unknown()).nullable(),createdAt:I.iso.datetime({offset:!0})}).strict(),rp=I.object({code:zm,requestId:I.uuid()}).strict(),ip=I.strictObject({redemptionId:I.uuid(),currency:se,requestId:I.uuid(),accepted:I.literal(!0)}),oS=I.strictObject({type:I.literal("checkout"),orderId:I.uuid(),productVersionId:I.uuid(),currency:se,duration:dt,renewalAmountMinor:I.number().int().positive().max(1e8),status:I.enum(["created","pending","trialing","paid","cancelled","failed"]),url:I.url().nullable()}),ap=I.discriminatedUnion("type",[oS,I.strictObject({type:I.literal("subscription"),operationId:I.uuid(),membershipId:I.uuid(),productVersionId:I.uuid(),currency:se,duration:dt,renewalAmountMinor:I.number().int().positive().max(1e8),status:I.enum(["pending","running","applied","failed"])})]),op=I.object({programId:I.uuid(),requestId:I.uuid()}).strict(),sp=I.object({id:I.uuid(),programId:I.uuid(),code:Rs.shape.code,createdAt:I.iso.datetime({offset:!0})}).strict(),WR=I.object({rows:I.array(iS).max(100),nextCursor:I.uuid().nullable()}).strict(),QR=I.object({rows:I.array(aS).max(100),nextCursor:I.uuid().nullable()}).strict(),sS=Rs.extend({id:I.uuid(),redemptions:I.number().int().nonnegative()}).strict(),cS=I.strictObject({id:I.uuid(),programId:I.uuid().nullable(),customerId:I.uuid().nullable(),referrerId:I.uuid().nullable(),code:I.string().nullable(),status:I.enum(["pending","triggered","applied"]),createdAt:I.iso.datetime({offset:!0})}),ZR=I.object({codes:I.array(sS).max(100),redemptions:I.array(cS).max(100),customers:I.record(I.uuid(),I.string()),codesCursor:I.uuid().nullable(),redemptionsCursor:I.uuid().nullable()}).strict(),YR=I.discriminatedUnion("action",[I.object({action:I.literal("create"),rewardId:I.uuid(),revision:I.number().int().nonnegative(),input:Rs}).strict(),I.object({action:I.literal("remove"),rewardId:I.uuid(),revision:I.number().int().nonnegative(),codeId:I.uuid()}).strict()]);import{z as b}from"zod";import{z as U}from"zod";var Mt={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},oi=e=>new Set(e).size===e.length,js=U.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),uS=U.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),si=U.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),lS=U.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),cp=U.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),zR=["isOn","isOff","getFeatureValue","evalFeature","eval_feature"],up=U.strictObject({id:U.uuid(),repo:uS,platform:U.enum(["github","gitlab","bitbucket"]),branches:U.array(si).min(1).max(4).refine(oi),workflow:U.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:U.array(U.uuid()).min(1).max(4).refine(oi),include:U.array(cp).min(1).max(16),exclude:U.array(cp).max(16),methods:U.array(U.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(oi),maxAgeHours:U.number().int().min(1).max(720)}),lp=up.extend({revision:U.number().int().positive()}),ej=U.strictObject({repository:up,expectedRevision:U.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),dp=U.strictObject({repositoryId:U.uuid(),branch:si}),dS=U.array(js).max(Mt.keys).refine(oi),mp=U.strictObject({repository:lp.omit({keyIds:!0}),branch:si,keys:dS,keySetHash:U.string().regex(/^[a-f0-9]{64}$/)}),mS=U.strictObject({filePath:lS,startingLineNumber:U.number().int().min(1).max(1e7)}),Ns=U.strictObject({protocol:U.literal(1),repositoryId:U.uuid(),branch:si,workflow:U.string().max(200),configurationRevision:U.number().int().positive(),keySetHash:U.string().regex(/^[a-f0-9]{64}$/),commit:U.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:U.uuid(),runNumber:U.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:U.number().int().min(1).max(1e4),scannerVersion:U.literal("1"),scannedAt:U.iso.datetime({offset:!0}),coverage:U.strictObject({complete:U.literal(!0),files:U.number().int().min(0).max(Mt.files),sourceBytes:U.number().int().min(0).max(Mt.sourceBytes),unresolvedCalls:U.number().int().min(0).max(1e6),unsupportedFiles:U.number().int().min(0).max(Mt.files)}),features:U.array(U.strictObject({key:js,refs:U.array(mS).max(Mt.referencesPerKey)})).max(Mt.keys)}).superRefine((e,t)=>{oi(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>Mt.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),ks=U.strictObject({scanId:U.uuid(),commit:U.string(),receivedAt:U.string(),references:U.number().int().nonnegative(),removedReferences:U.number().int().nonnegative()}),pS=ks.extend({repositoryId:U.uuid(),branch:si,workflow:U.string(),digest:U.string(),configurationRevision:U.number().int().positive(),runNumber:U.number().int().positive(),runAttempt:U.number().int().positive(),scannedAt:U.string(),keySetHash:U.string(),coverage:Ns.shape.coverage}),fS=U.strictObject({repositories:U.array(lp).max(Mt.repositories),scans:U.array(pS).max(Mt.repositories*Mt.branches)}),hS=U.strictObject({key:js,references:U.number().int().nonnegative(),coveredTargets:U.number().int().nonnegative(),expiredTargets:U.number().int().nonnegative(),uncertainTargets:U.number().int().nonnegative()}),tj=U.strictObject({available:U.boolean().default(!0),settings:fS,expectedTargets:U.number().int().min(0).max(80),features:U.array(hS).max(2001),truncated:U.boolean()});import{z as vt}from"zod";var Ds=vt.strictObject({customerId:vt.uuid(),eventId:vt.string().trim().min(1).max(200),grantId:vt.uuid(),productVersionId:vt.uuid(),subscriptionId:vt.string().trim().min(1).max(255),occurredAt:vt.iso.datetime({offset:!0})}),pp=Ds.extend({id:vt.uuid(),couponId:vt.uuid(),status:vt.literal("redeemed"),source:vt.literal("merchant"),recordedAt:vt.iso.datetime({offset:!0})});import{z as G}from"zod";var Fs=G.strictObject({name:G.string().trim().min(1).max(255),memo:G.string().max(1e4).nullable().optional(),footer:G.string().max(1e4).nullable().optional(),net_terms_days:G.number().int().positive().nullable().optional()}),gS=Fs.extend({id:G.string().min(1).max(255),created_at:G.number().nullable()}),fp=G.strictObject({items:G.array(gS).max(50),nextCursor:G.uuid().nullable()}),sj=G.discriminatedUnion("action",[G.strictObject({action:G.literal("create"),requestId:G.uuid(),values:Fs}),G.strictObject({action:G.literal("update"),id:G.string().min(1).max(255),values:Fs}),G.strictObject({action:G.literal("delete"),id:G.string().min(1).max(255)})]),hp=G.discriminatedUnion("action",[G.strictObject({action:G.literal("create"),requestId:G.uuid(),params:zn}),G.strictObject({action:G.enum(["finalize","send","pay","void"]),requestId:G.uuid(),invoiceId:G.uuid()}),G.strictObject({action:G.literal("reissue"),requestId:G.uuid(),invoiceId:G.uuid(),params:Go})]),Us=G.strictObject({id:G.uuid(),customerId:G.uuid(),providerInvoiceId:G.string().nullable(),status:G.enum(["draft","open","paid","void","uncollectible"]),currency:G.string(),totalMinor:G.string().regex(/^-?\d+$/),paidMinor:G.string().regex(/^\d+$/),refundedMinor:G.string().regex(/^\d+$/),hostedInvoiceUrl:G.url().nullable(),createdAt:G.number(),collectionMethod:G.enum(["send_invoice","charge_automatically"]).nullable()}),gp=Us.extend({lines:G.array(G.strictObject({id:G.uuid(),description:G.string(),amountMinor:G.string().regex(/^-?\d+$/),netAmountMinor:G.string().regex(/^-?\d+$/),quantity:G.number().nullable(),periodStart:G.number().nullable(),periodEnd:G.number().nullable()})).max(1e3)}),ci=G.strictObject({taskId:G.uuid(),status:G.enum(["ready","running","done","dead"]),invoice:Us.nullable(),errorCode:G.string().nullable()}),_p=G.strictObject({items:G.array(Us).max(50),nextCursor:G.uuid().nullable(),operations:G.array(ci).max(50),operationsLimited:G.boolean()}),cj=on;var _S=b.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","code-references:read","code-references:write","app-manifests:write"]),bp={scope:we,permissions:b.array(_S),expiresAt:b.iso.datetime().nullable()},Yj=b.discriminatedUnion("kind",[b.object({...bp,kind:b.literal("server"),keyId:b.string().min(1)}),b.object({...bp,kind:b.literal("customer"),customerId:b.string().min(1),identityKind:b.enum(["identified","guest"]),expiresAt:b.iso.datetime()})]),k=b.object({requestId:b.uuid(),scope:we}).strict(),bS=mm.safeExtend({fingerprint:ua.optional()}).strict(),yS=k.extend({customer:sr,created:b.boolean()}),SS=b.enum(["unassigned","unknown","scheduled","active","expired"]),Jj=b.object({customerId:b.string().min(1),evaluatedAt:b.iso.datetime(),status:SS,validity:Xa.nullable(),planVersion:au.nullable(),holdings:b.array(b.object({id:b.uuid(),planVersionId:b.uuid(),source:b.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:b.array(b.object({featureId:b.string(),featureKey:b.string(),featureName:b.string(),type:b.enum(["boolean","metered"]),allowance:b.number().int().nonnegative().nullable(),used:b.number().finite().nonnegative(),remaining:b.number().finite().nonnegative().nullable(),allowed:b.boolean(),sources:b.array(b.object({holdingId:b.uuid(),planVersionId:b.uuid(),group:b.string(),kind:b.enum(["main","addon"]),allowance:b.number().nullable()})).optional()}))});function yp(){return k.extend({offer:Vr.nullable(),reason:fl.nullable()})}var N={listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:b.strictObject({cursor:b.uuid().optional()}),response:k.extend({templates:fp})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:b.strictObject({customerId:b.uuid(),params:zn}),response:k.extend({preview:Ko})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:b.strictObject({customerId:b.uuid(),requestId:b.uuid(),params:zn}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:k.extend({operation:ci})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:b.strictObject({customerId:b.uuid(),command:hp}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:k.extend({operation:ci})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:b.strictObject({customerId:b.uuid(),taskId:b.uuid()}),response:k.extend({operation:ci})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:b.strictObject({customerId:b.uuid(),cursor:b.uuid().optional()}),response:k.extend({invoices:_p})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:b.strictObject({customerId:b.uuid(),invoiceId:b.uuid()}),response:k.extend({invoice:gp})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:dp,response:k.extend({config:mp})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Ns,response:k.extend({receipt:ks})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:b.strictObject({}),response:k.extend({payload:rs})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:zd,response:k.merge(em)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:tm,response:k.merge(nm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:b.strictObject({customerId:b.uuid(),sourceId:b.uuid()}),response:k.extend({balance:Fm})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:b.strictObject({customerId:b.uuid(),command:Dm}),response:k.extend({balance:Cs})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:b.strictObject({internal_feature_id:b.uuid(),customerId:b.uuid().optional(),entityId:b.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:k.extend({internal_feature_id:b.uuid(),config:Io,model_markups:Fi})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:b.strictObject({customerId:b.uuid(),query:Ec}),response:k.extend({usage:$a})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:b.strictObject({customerId:b.uuid(),command:Tc}),response:k.extend({usage:$a})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:b.strictObject({customerId:b.uuid(),command:$l}),response:k.extend({grant:ko})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Gl,response:k.extend({grants:Kl})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:b.union(Gd.options.map(e=>e.extend({customerId:b.uuid().optional(),customerToken:b.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:k.extend({operation:Kd})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Nd.extend({customerId:b.uuid().optional()}),response:k.extend({setup:Yo})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:kd.extend({customerId:b.uuid().optional()}),response:k.extend({setup:Yo})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Td.safeExtend({customerId:b.uuid()}),response:k.extend({batch:Xr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Wi.extend({customerId:b.uuid()}),response:k.extend({batch:Xr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Wi.extend({customerId:b.uuid()}),response:k.extend({batch:Xr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Wi.extend({customerId:b.uuid()}),response:k.extend({batch:Xr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:b.discriminatedUnion("action",[Qi.options[0].extend({customerId:b.uuid()}),Qi.options[1].extend({customerId:b.uuid()}),Qi.options[2].extend({customerId:b.uuid()})]),response:k.extend({trial:Zo})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Rd.extend({customerId:b.uuid()}),response:k.extend({trial:Zo})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Ji,response:k.extend({subscriptions:Vd})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Ji,response:k.extend({purchases:qd})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Md,response:k.extend({conflicts:$d})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Bd,response:k.extend({resolution:Ld})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Fd,response:k.extend({verification:Ud})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:vd.safeExtend({...Xn,customerId:b.uuid().optional()}),response:k.extend({quote:Yr})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Rn.extend({customerId:b.uuid().optional(),intent:b.enum(["confirm","cancel"]).optional()}),response:k.extend({operation:er})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Rn.extend({customerId:b.uuid().optional()}),response:k.extend({operation:er})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Ad.safeExtend({customerId:b.uuid().optional()}),response:k.extend({quote:Pd})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Rn.extend({customerId:b.uuid().optional(),intent:b.enum(["confirm","cancel"]).optional()}),response:k.extend({operation:Wo})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Rn.extend({customerId:b.uuid().optional()}),response:k.extend({operation:Wo})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Cd.safeExtend({customerId:b.uuid()}),response:k.extend({quote:Ed})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Rn.extend({customerId:b.uuid()}),response:k.extend({operation:Hi})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Rn.extend({customerId:b.uuid()}),response:k.extend({operation:Hi})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:El,response:k.extend({controls:wo})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Il,response:k.extend({prepared:Al})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Ol,response:k.extend({authorization:Bi})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Nl,response:k.extend({coupons:kl})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Pl,response:k.extend({authorization:Bi})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Rl,response:k.extend({invoices:jl})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Tl,response:k.extend({invoice:$r})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:b.object({customerId:b.uuid(),command:wl}).strict(),response:k.extend({controls:wo})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:b.object({customerId:b.uuid(),command:Um}).strict(),response:k.extend({entity:Mm})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:b.strictObject({customerId:b.uuid().nullable(),query:Gm}),response:k.extend({analytics:Km})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:b.object({customerId:b.uuid().nullable(),query:Mn}).strict(),response:k.extend({analytics:qm})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Hm,response:k.extend({batchId:b.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Wm,response:k.extend({batch:Qm})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Dc.extend({customerId:b.string().min(1).optional()}),response:k.extend({check:Rr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:b.strictObject({kind:rn,selector:b.discriminatedUnion("type",[b.strictObject({type:b.literal("resource"),id:b.uuid()}),b.strictObject({type:b.literal("version"),id:b.uuid()})]),customerId:b.string().min(1).optional()}),response:k.extend({content:Zr})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:jm,response:k.extend({paywall:dr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:b.strictObject({...Xn,selector:Zd,customerId:b.string().min(1).optional(),commerce:vi,requirement:Gn.optional()}),response:k.extend({offering:Yd,candidates:b.array(Fc).max(20),availability:b.array(b.strictObject({productVersionId:b.uuid(),available:b.boolean(),reason:b.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Rr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:b.object({customerId:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),response:k.extend({holdings:Rc})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:b.object({customerId:b.uuid().optional(),query:jc}).strict(),response:k.extend({ledger:Nc})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Hl.extend({customerId:b.uuid().optional()}),response:k.extend({detail:Wl})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Do.safeExtend({customerId:b.uuid().optional()}),response:k.extend({statement:Ql})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:b.object({customerId:b.uuid().optional(),command:Er.options[0]}).strict(),response:k.extend({quote:wc})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:b.strictObject({customerId:b.uuid(),command:b.union([b.strictObject({eventName:b.string().min(1),quantity:_e.optional(),properties:qt.optional(),entityId:b.uuid().optional(),idempotencyKey:b.string().min(1).max(120)}),b.strictObject({internal_feature_id:b.uuid(),quantity:_e.optional(),properties:qt.optional(),entityId:b.uuid().optional(),idempotencyKey:b.string().min(1).max(120)})])}),response:k.extend({receipts:b.array(Tr).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:b.object({customerId:b.uuid(),command:Er.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:k.extend({receipt:Tr})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:rp,response:k.extend({redemption:np})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:op,response:k.extend({referralCode:sp})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:ip,response:k.extend({checkout:ap})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Yl,response:k.extend({seats:Mo})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Jl,response:k.extend({seats:Mo})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:bS,response:yS},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:ms,response:k.extend({customer:sr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:hm,response:k.extend(gm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:fm,response:k.extend(pm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:b.object({customerId:b.uuid()}).strict(),response:k.extend({customerToken:b.string().min(1),expiresAt:b.iso.datetime(),sessionId:b.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:b.strictObject({customerId:b.uuid(),customerToken:b.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:k.extend({customerToken:b.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:b.uuid(),expiresAt:b.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:b.strictObject({customerId:b.uuid(),sessionId:b.uuid().optional()}),response:k.extend({revoked:b.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:b.strictObject({guestToken:b.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ua.optional()}),response:k.extend({customerId:b.uuid(),guestToken:b.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:b.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:b.strictObject({guestToken:b.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:k.extend({customerId:b.uuid(),customerToken:b.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:b.uuid(),expiresAt:b.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:b.strictObject({guestToken:b.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:b.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:b.uuid()}),response:k.extend({customer:sr,switched:b.boolean(),replayed:b.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:b.strictObject({code:b.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:b.uuid()}),response:yp()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:b.object({}).strict(),response:k.extend({offers:b.array(Vr)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:b.object({customerId:b.string().min(1).max(255).optional(),couponId:b.uuid(),...Xn,requestId:b.uuid(),couponContentDigest:b.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:yp()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Ds,response:k.extend({receipt:pp})}},Xj={listInvoiceTemplates:N.listInvoiceTemplates,previewInvoice:N.previewInvoice,createInvoice:N.createInvoice,manageInvoice:N.manageInvoice,readInvoiceOperation:N.readInvoiceOperation,listInvoices:N.listInvoices,getInvoice:N.getInvoice,getCodeReferenceConfig:N.getCodeReferenceConfig,submitCodeReferences:N.submitCodeReferences,getFeatures:N.getFeatures,evaluateFeatures:N.evaluateFeatures,trackEvents:N.trackEvents,setupPayment:N.setupPayment,readPaymentSetup:N.readPaymentSetup,previewSubscriptionBatch:N.previewSubscriptionBatch,confirmSubscriptionBatch:N.confirmSubscriptionBatch,readSubscriptionBatch:N.readSubscriptionBatch,abandonSubscriptionBatch:N.abandonSubscriptionBatch,manageSubscriptionTrial:N.manageSubscriptionTrial,readSubscriptionTrial:N.readSubscriptionTrial,listSubscriptions:N.listSubscriptions,listPurchases:N.listPurchases,listSubscriptionConflicts:N.listSubscriptionConflicts,retrySubscriptionConflict:N.retrySubscriptionConflict,readAiPricing:N.readAiPricing,readUsage:N.readUsage,setUsage:N.setUsage,previewRefund:N.previewRefund,refund:N.refund,readRefund:N.readRefund,previewUpdate:N.previewUpdate,update:N.update,readSubscriptionUpdate:N.readSubscriptionUpdate,restoreNativePurchase:N.restoreNativePurchase,verifySubscriptions:N.verifySubscriptions,previewAttach:N.previewAttach,attach:N.attach,readSubscriptionOperation:N.readSubscriptionOperation,manageBalanceGrant:N.manageBalanceGrant,readBalanceSource:N.readBalanceSource,adjustBalance:N.adjustBalance,listBalanceGrants:N.listBalanceGrants,readBillingControls:N.readBillingControls,prepareBillingAuthorization:N.prepareBillingAuthorization,confirmBillingAuthorization:N.confirmBillingAuthorization,setBillingCoupons:N.setBillingCoupons,revokeBillingAuthorization:N.revokeBillingAuthorization,listBillingInvoices:N.listBillingInvoices,confirmBillingAdjustment:N.confirmBillingAdjustment,manageBillingLimits:N.manageBillingLimits,createCustomer:N.createCustomer,getCustomer:N.getCustomer,listCustomers:N.listCustomers,updateCustomer:N.updateCustomer,createSession:N.createSession,renewSession:N.renewSession,revokeSessions:N.revokeSessions,createGuestCustomer:N.createGuestCustomer,resumeGuestSession:N.resumeGuestSession,claimGuestCustomer:N.claimGuestCustomer,checkEntitlement:N.checkEntitlement,resolveOffering:N.resolveOffering,resolveContent:N.resolveContent,resolvePaywall:N.resolvePaywall,readHoldings:N.readHoldings,readLedger:N.readLedger,readBillingInvoice:N.readBillingInvoice,readCreditStatement:N.readCreditStatement,quoteBalance:N.quoteBalance,trackUsage:N.trackUsage,mutateBalance:N.mutateBalance,manageUsageEntity:N.manageUsageEntity,readUsageAnalytics:N.readUsageAnalytics,readCreditAnalytics:N.readCreditAnalytics,submitUsageBatch:N.submitUsageBatch,readUsageBatch:N.readUsageBatch,listOffers:N.listOffers,grantOffer:N.grantOffer,recordCouponRedemption:N.recordCouponRedemption,redeemCoupon:N.redeemCoupon,redeemReward:N.redeemReward,createReferralCode:N.createReferralCode,claimRewardProduct:N.claimRewardProduct,readSeats:N.readSeats,manageSeat:N.manageSeat};import{z as ke}from"zod";var Sp=ke.union([$c,ke.string().max(200).regex(/^\/template-covers\/[a-z0-9-]+-[a-f0-9]{16}\.webp$/)]),vS=ke.strictObject({thumbnail:Sp,full:Sp}),iN=ke.object({id:ke.uuid(),key:ke.string().nullable(),label:ke.string().min(1).max(80),description:ke.string().max(300),category:ke.string().min(1).max(40),tags:ke.array(ke.string().max(30)).max(10),surface:Gc,source:ke.enum(["official","private"]),cover_image:vS.nullable().default(null),document:ze,revision:ke.number().int().positive(),archived_at:ke.string().nullable(),created_at:ke.string()}).strict(),aN=ke.object({projectId:ke.uuid(),environmentId:ke.uuid(),label:ke.string().trim().min(1).max(80),description:ke.string().trim().max(300),category:ke.string().trim().min(1).max(40),document:ze}).strict(),oN=ke.object({projectId:ke.uuid(),environmentId:ke.uuid(),id:ke.uuid(),revision:ke.number().int().positive()}).strict();import{z as Ms}from"zod";var ui=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Bs(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>bi(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new ui("Required GB Feature is unavailable");i=wr(e.featureKey,t),o=i.value,Object.assign(r,Cn(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new ui("Required GB Experiment is unavailable");if(a=Ac(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new ui("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:wr(e.configuration.featureKey,t).value;o={type:"offering_version",id:Ms.uuid().parse(u)},Object.assign(r,Cn(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,Cn(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function vp(e,t,n){Ms.uuid().parse(e),Ms.number().int().nonnegative().parse(t);let r=gi(_i(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as Ke}from"zod";var Ip=Ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),bN=Ke.strictObject({operation:Ke.literal("resolve_screen"),funnelId:Ke.uuid(),versionId:Ke.uuid(),screenId:Ip,locale:$t,customerId:Ke.uuid().optional()}),yN=Ke.strictObject({scope:we,funnelId:Ke.uuid(),versionId:Ke.uuid(),screenId:Ip,locale:$t,coupons:Ke.record(Ke.uuid(),Ke.strictObject({available:Ke.boolean(),offer:Ke.strictObject({id:Ke.uuid(),expiresAt:Ke.iso.datetime()}).nullable()})),couponDigests:Ke.record(Ke.uuid(),sn)});import{z as D}from"zod";var un=D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vs=D.enum(["running","waiting","completed","closed","ineligible","failed"]),IS=D.discriminatedUnion("type",[ra,as,D.strictObject({type:D.literal("wait"),receiptId:D.uuid(),kind:D.enum(["timer","event","operation"]),deadline:D.iso.datetime({offset:!0}).nullable(),eventName:un.optional()}),D.strictObject({type:D.literal("open_url"),receiptId:D.uuid(),url:hs,openIn:gs}),D.strictObject({type:D.literal("event"),receiptId:D.uuid(),event:un})]),xS=D.strictObject({type:D.literal("funnel"),id:D.uuid(),versionId:D.uuid()}),AS={id:un,presentation:Ht,outputs:D.array(un).max(250),inputs:Ka,values:D.record(D.string(),he).optional(),offeringKey:Me.optional(),capabilities:Kn,customerData:qc,dataCursors:D.record(un,Ii.nullable())},OS=D.strictObject({...AS,content:D.strictObject({type:D.literal("document"),document:ze})}),Ls=D.strictObject({id:D.uuid(),source:xS,revision:D.number().int().nonnegative(),visit:D.number().int().nonnegative(),nodeId:un,nodeType:D.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Vs,stopped:D.boolean(),canBack:D.boolean(),authenticated:D.boolean(),locale:D.string().min(1).max(35),answers:vn,parameters:jt,variables:D.record(D.string(),he),output:he.nullable(),screen:OS.nullable(),paywall:D.strictObject({receiptId:D.uuid(),resolution:D.union([ai,dr]),quote:Yr.nullable(),operation:er.nullable(),purchaseRequestId:D.uuid().nullable(),selectionGeneration:D.number().int().nonnegative().optional(),canReselect:D.boolean().optional()}).nullable(),instruction:IS.nullable(),pendingRequest:D.strictObject({requestId:D.uuid(),authenticationRequired:D.boolean()}).nullable(),runExpiresAt:D.iso.datetime({offset:!0}),credentialExpiresAt:D.iso.datetime({offset:!0}).nullable()}),qs=D.strictObject({scope:we,run:Ls,settlement:D.strictObject({requestId:D.uuid(),state:D.enum(["pending","unknown","settled"]),operationId:D.uuid().nullable(),receiptId:D.uuid().nullable().optional()}).optional(),purchase:D.strictObject({receiptId:D.uuid(),quote:Yr.nullable(),operation:er.nullable(),canReselect:D.boolean().optional()}).optional(),review:D.strictObject({activeOperationId:D.uuid().nullable(),pages:D.array(D.strictObject({receiptId:D.uuid(),nodeId:un,visit:D.number().int().nonnegative()})).max(100),page:D.strictObject({receiptId:D.uuid(),nodeId:un,visit:D.number().int().nonnegative(),document:ze,answers:vn,inputs:Ka,values:D.record(D.string(),he).optional()}).nullable(),coupons:D.array(D.strictObject({grantId:D.uuid(),status:D.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:D.string().nullable()})).max(100),purchases:D.array(D.strictObject({receiptId:D.uuid(),operationId:D.uuid(),status:D.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:D.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:D.uuid().optional()}),$s=qs.extend({run:Ls.extend({paywall:Ls.shape.paywall.unwrap().extend({resolution:dr}).nullable()})});function kN(e){return $s.parse({...e,run:{...e.run,paywall:e.run.paywall?{...e.run.paywall,resolution:"document"in e.run.paywall.resolution?Nm(e.run.paywall.resolution):e.run.paywall.resolution}:null}})}var DN="X-Indiana-Server-Key";import{z as ot}from"zod";import{z as ya}from"zod";var BN=ya.strictObject({operation:ya.literal("renew_run"),runId:ya.uuid(),customerId:ya.uuid()}),xp=qs.refine(e=>!!e.runToken,"Renewal returns a credential"),Ap=$s.refine(e=>!!e.runToken,"Renewal returns a credential");var WN=ot.discriminatedUnion("operation",[ot.strictObject({operation:ot.literal("campaign_decide"),...ps}).refine(jn,Nn),ot.strictObject({operation:ot.literal("campaign_start"),funnelId:ot.uuid(),requestId:ot.uuid(),customer:ar,customerData:or.optional(),locale:ot.string().min(1).max(35),parameters:jt,cooldownSeconds:ot.number().int().min(1).max(2592e3)}).refine(jn,Nn)]),PS=ot.union([ot.strictObject({scope:we,suppressed:ot.literal(!0),reason:ot.enum(["frequency","in_progress"]),retryAt:ot.iso.datetime({offset:!0})}),xp]),QN=ot.union([PS.options[0],Ap]);import{z as me}from"zod";var pr=me.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pp=me.strictObject({entry:pr,nodes:me.array(me.strictObject({id:pr,type:me.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:me.record(me.string(),pr),writes:me.record(Me,Me),resources:me.strictObject({screenId:pr.optional(),paywallVersionId:me.uuid().optional(),couponId:me.uuid().optional(),couponIds:me.array(me.uuid()).max(20).optional(),experimentId:me.uuid().optional(),featureKey:me.string().optional(),offeringVersionId:me.uuid().optional()})})).min(1).max(500)}),Op={scope:we,funnelId:me.uuid(),versionId:me.uuid(),evaluationRevision:me.number().int().nonnegative(),expiresAt:me.iso.datetime({offset:!0}).nullable(),topology:Pp},fr=me.discriminatedUnion("evaluationMode",[me.strictObject({...Op,evaluationMode:me.literal("local"),growth:Xt,conditions:me.record(pr,me.array(me.strictObject({condition:Vn,port:me.string()})))}),me.strictObject({...Op,evaluationMode:me.literal("remote")})]),CS=fr.options[0].extend({evaluation:me.strictObject({maxTransitions:me.number().int().min(1).max(1e4),variables:me.record(Me,Yn),outputSchema:Zn,terminals:me.record(pr,me.strictObject({outcome:me.enum(["completed","closed","ineligible","failed"]),output:ni.nullable()}))})});function wS(e){return Pp.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=me.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function ES(e){let t=Ut.parse(e.document),n=e.evaluationMode==="local"?Xt.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:wS(t)};return fr.parse(e.evaluationMode==="remote"?r:{...r,growth:_a(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function ik(e){let t=ES(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ut.parse(e.document);return CS.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as Se}from"zod";var Sa=Se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),TS=Se.discriminatedUnion("type",[Se.strictObject({type:Se.literal("page_version"),id:Se.uuid()}),Se.strictObject({type:Se.literal("popup_version"),id:Se.uuid()}),Se.strictObject({type:Se.literal("banner_version"),id:Se.uuid()})]),RS=Se.strictObject({type:Se.literal("banner_version"),id:Se.uuid()}),Cp=e=>e==="page"?Se.strictObject({id:Sa,type:Se.literal("page"),pageId:Se.uuid(),pageVersionId:Se.uuid().nullable()}):Se.strictObject({id:Sa,type:Se.literal("popup"),popupId:Se.uuid(),popupVersionId:Se.uuid().nullable()}),wp=ga.omit({schemaVersion:!0,screens:!0,references:!0}).extend({schemaVersion:Se.literal(5),screens:Se.array(Se.discriminatedUnion("type",[Cp("page"),Cp("popup"),Se.strictObject({id:Sa,type:Se.literal("paywall"),paywallVersionId:Se.uuid()})])).max(100),references:Se.record(Sa,Se.union([ri,TS])).refine(e=>Object.keys(e).length<=500)}),lk=Se.union([ga,wp]),jS=wp.extend({displayName:Se.string().trim().min(1).max(80)}).superRefine((e,t)=>{for(let[n,r]of e.screens.entries())(r.type==="page"&&r.pageVersionId===null||r.type==="popup"&&r.popupVersionId===null)&&t.addIssue({code:"custom",path:["screens",n],message:"Publish the referenced content first"})});function NS(e,t,n){let r=new Map(n.map(o=>[o.id,Zr.parse(o)]));for(let o of Object.values(e.references)){if(!["page_version","popup_version","banner_version"].includes(o.type)||!("id"in o))continue;let s=r.get(o.id);if(!s||`${s.kind}_version`!==o.type||s.projectId!==t.projectId||s.environmentId!==t.environmentId)throw new Error("Missing or foreign declared content version")}for(let o of e.graph.nodes){if(o.type!=="output"||o.value.type!=="literal")continue;let s=o.value.value;if(!s||typeof s!="object"||Array.isArray(s)||s.type!=="banner_version")continue;let c=RS.parse(s);if(!Object.values(e.references).some(u=>u.type==="banner_version"&&u.id===c.id))throw new Error("Undeclared Banner output version")}let i=e.screens.map(o=>{if(o.type==="paywall")return o;let s=o.type==="page"?o.pageVersionId:o.popupVersionId,c=o.type==="page"?o.pageId:o.popupId,u=s?r.get(s):void 0;if(!u||u.kind!==o.type||u.document.kind!==o.type||u.resourceId!==c||u.projectId!==t.projectId||u.environmentId!==t.environmentId)throw new Error(`Missing or foreign fixed ${o.type} version for ${o.id}`);if(!Object.values(e.references).some(d=>d.type===`${o.type}_version`&&"id"in d&&d.id===u.id))throw new Error(`Undeclared fixed content version for ${o.id}`);for(let[d,p]of Object.entries(u.document.contract.inputs)){let g=e.variables[d];if(p.required&&(!g||g.type!==p.type||!p.nullable&&g.nullable))throw new Error(`Unbound content input ${d} for ${o.id}`)}return{id:o.id,type:"owned",document:u.document.screen}}),a=Object.fromEntries(Object.entries(e.references).filter(([,o])=>!["page_version","popup_version","banner_version"].includes(o.type)));return ga.parse({...e,schemaVersion:4,screens:i,references:a})}function dk(e,t,n){let{displayName:r,...i}=jS.parse(e);return Pm.parse({...NS(i,t,n),displayName:r})}var Gs={zh:["\u5168\u90E8\u4ED8\u8D39\u5957\u9910","\u6307\u5B9A\u5957\u9910","\u6240\u6709\u5BA2\u6237","\u4EC5\u9996\u8D2D","\u9700\u8981\u6807\u7B7E","\u5F00\u59CB","\u622A\u6B62","\u65E0\u622A\u6B62\u65E5\u671F","\u9886\u53D6\u540E\u6709\u6548","\u5C0F\u65F6","\u6BCF\u4EBA\u6B21\u6570","\u603B\u540D\u989D"],"zh-Hant":["\u5168\u90E8\u4ED8\u8CBB\u65B9\u6848","\u6307\u5B9A\u65B9\u6848","\u6240\u6709\u5BA2\u6236","\u50C5\u9996\u8CFC","\u9700\u8981\u6A19\u7C64","\u958B\u59CB","\u622A\u6B62","\u7121\u622A\u6B62\u65E5\u671F","\u9818\u53D6\u5F8C\u6709\u6548","\u5C0F\u6642","\u6BCF\u4EBA\u6B21\u6578","\u7E3D\u540D\u984D"],en:["All paid plans","Selected plans","All customers","First purchase only","Required tags","Starts","Ends","No end date","Valid after claim","hours","Uses per customer","Total limit"],ja:["\u5168\u6709\u6599\u30D7\u30E9\u30F3","\u5BFE\u8C61\u30D7\u30E9\u30F3","\u3059\u3079\u3066\u306E\u304A\u5BA2\u69D8","\u521D\u56DE\u8CFC\u5165\u9650\u5B9A","\u5FC5\u8981\u306A\u30BF\u30B0","\u958B\u59CB","\u7D42\u4E86","\u7D42\u4E86\u65E5\u306A\u3057","\u53D7\u53D6\u5F8C\u306E\u6709\u52B9\u671F\u9593","\u6642\u9593","\u9867\u5BA2\u3054\u3068\u306E\u5229\u7528\u56DE\u6570","\u5229\u7528\u4E0A\u9650"],ko:["\uBAA8\uB4E0 \uC720\uB8CC \uC694\uAE08\uC81C","\uC9C0\uC815 \uC694\uAE08\uC81C","\uBAA8\uB4E0 \uACE0\uAC1D","\uCCAB \uAD6C\uB9E4\uB9CC","\uD544\uC218 \uD0DC\uADF8","\uC2DC\uC791","\uC885\uB8CC","\uC885\uB8CC\uC77C \uC5C6\uC74C","\uC218\uB839 \uD6C4 \uC720\uD6A8 \uAE30\uAC04","\uC2DC\uAC04","\uACE0\uAC1D\uBCC4 \uC0AC\uC6A9 \uD69F\uC218","\uCD1D \uD55C\uB3C4"],es:["Todos los planes de pago","Planes seleccionados","Todos los clientes","Solo primera compra","Etiquetas requeridas","Inicio","Fin","Sin fecha de fin","Validez tras reclamar","horas","Usos por cliente","L\xEDmite total"],fr:["Tous les forfaits payants","Forfaits s\xE9lectionn\xE9s","Tous les clients","Premier achat uniquement","\xC9tiquettes requises","D\xE9but","Fin","Sans date de fin","Validit\xE9 apr\xE8s obtention","heures","Utilisations par client","Limite totale"],de:["Alle kostenpflichtigen Tarife","Ausgew\xE4hlte Tarife","Alle Kunden","Nur erster Kauf","Erforderliche Tags","Beginn","Ende","Kein Enddatum","G\xFCltigkeit nach Erhalt","Stunden","Nutzungen pro Kunde","Gesamtlimit"],pt:["Todos os planos pagos","Planos selecionados","Todos os clientes","Apenas primeira compra","Etiquetas necess\xE1rias","In\xEDcio","Fim","Sem data final","Validade ap\xF3s resgate","horas","Usos por cliente","Limite total"],it:["Tutti i piani a pagamento","Piani selezionati","Tutti i clienti","Solo primo acquisto","Tag richiesti","Inizio","Fine","Senza data finale","Validit\xE0 dopo il ritiro","ore","Utilizzi per cliente","Limite totale"],ru:["\u0412\u0441\u0435 \u043F\u043B\u0430\u0442\u043D\u044B\u0435 \u043F\u043B\u0430\u043D\u044B","\u0412\u044B\u0431\u0440\u0430\u043D\u043D\u044B\u0435 \u043F\u043B\u0430\u043D\u044B","\u0412\u0441\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u044B","\u0422\u043E\u043B\u044C\u043A\u043E \u043F\u0435\u0440\u0432\u0430\u044F \u043F\u043E\u043A\u0443\u043F\u043A\u0430","\u041D\u0435\u043E\u0431\u0445\u043E\u0434\u0438\u043C\u044B\u0435 \u0442\u0435\u0433\u0438","\u041D\u0430\u0447\u0430\u043B\u043E","\u041E\u043A\u043E\u043D\u0447\u0430\u043D\u0438\u0435","\u0411\u0435\u0437 \u0434\u0430\u0442\u044B \u043E\u043A\u043E\u043D\u0447\u0430\u043D\u0438\u044F","\u0421\u0440\u043E\u043A \u043F\u043E\u0441\u043B\u0435 \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u0438\u044F","\u0447\u0430\u0441\u043E\u0432","\u0418\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0439 \u043D\u0430 \u043A\u043B\u0438\u0435\u043D\u0442\u0430","\u041E\u0431\u0449\u0438\u0439 \u043B\u0438\u043C\u0438\u0442"],vi:["M\u1ECDi g\xF3i tr\u1EA3 ph\xED","G\xF3i \u0111\u01B0\u1EE3c ch\u1ECDn","M\u1ECDi kh\xE1ch h\xE0ng","Ch\u1EC9 l\u1EA7n mua \u0111\u1EA7u","Th\u1EBB b\u1EAFt bu\u1ED9c","B\u1EAFt \u0111\u1EA7u","K\u1EBFt th\xFAc","Kh\xF4ng c\xF3 ng\xE0y k\u1EBFt th\xFAc","Hi\u1EC7u l\u1EF1c sau khi nh\u1EADn","gi\u1EDD","L\u01B0\u1EE3t m\u1ED7i kh\xE1ch","T\u1ED5ng gi\u1EDBi h\u1EA1n"],th:["\u0E17\u0E38\u0E01\u0E41\u0E1E\u0E47\u0E01\u0E40\u0E01\u0E08\u0E41\u0E1A\u0E1A\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19","\u0E41\u0E1E\u0E47\u0E01\u0E40\u0E01\u0E08\u0E17\u0E35\u0E48\u0E40\u0E25\u0E37\u0E2D\u0E01","\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32\u0E17\u0E38\u0E01\u0E04\u0E19","\u0E40\u0E09\u0E1E\u0E32\u0E30\u0E01\u0E32\u0E23\u0E0B\u0E37\u0E49\u0E2D\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01","\u0E41\u0E17\u0E47\u0E01\u0E17\u0E35\u0E48\u0E08\u0E33\u0E40\u0E1B\u0E47\u0E19","\u0E40\u0E23\u0E34\u0E48\u0E21","\u0E2A\u0E34\u0E49\u0E19\u0E2A\u0E38\u0E14","\u0E44\u0E21\u0E48\u0E21\u0E35\u0E27\u0E31\u0E19\u0E2A\u0E34\u0E49\u0E19\u0E2A\u0E38\u0E14","\u0E2D\u0E32\u0E22\u0E38\u0E2B\u0E25\u0E31\u0E07\u0E23\u0E31\u0E1A\u0E2A\u0E34\u0E17\u0E18\u0E34\u0E4C","\u0E0A\u0E31\u0E48\u0E27\u0E42\u0E21\u0E07","\u0E04\u0E23\u0E31\u0E49\u0E07\u0E15\u0E48\u0E2D\u0E25\u0E39\u0E01\u0E04\u0E49\u0E32","\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E31\u0E49\u0E07\u0E2B\u0E21\u0E14"],id:["Semua paket berbayar","Paket terpilih","Semua pelanggan","Hanya pembelian pertama","Tag wajib","Mulai","Berakhir","Tanpa tanggal akhir","Masa berlaku setelah klaim","jam","Penggunaan per pelanggan","Batas total"],ar:["\u062C\u0645\u064A\u0639 \u0627\u0644\u062E\u0637\u0637 \u0627\u0644\u0645\u062F\u0641\u0648\u0639\u0629","\u0627\u0644\u062E\u0637\u0637 \u0627\u0644\u0645\u062D\u062F\u062F\u0629","\u062C\u0645\u064A\u0639 \u0627\u0644\u0639\u0645\u0644\u0627\u0621","\u0627\u0644\u0634\u0631\u0627\u0621 \u0627\u0644\u0623\u0648\u0644 \u0641\u0642\u0637","\u0627\u0644\u0648\u0633\u0648\u0645 \u0627\u0644\u0645\u0637\u0644\u0648\u0628\u0629","\u062A\u0628\u062F\u0623","\u062A\u0646\u062A\u0647\u064A","\u0628\u0644\u0627 \u062A\u0627\u0631\u064A\u062E \u0627\u0646\u062A\u0647\u0627\u0621","\u0627\u0644\u0635\u0644\u0627\u062D\u064A\u0629 \u0628\u0639\u062F \u0627\u0644\u0645\u0637\u0627\u0644\u0628\u0629","\u0633\u0627\u0639\u0627\u062A","\u0627\u0644\u0627\u0633\u062A\u062E\u062F\u0627\u0645\u0627\u062A \u0644\u0643\u0644 \u0639\u0645\u064A\u0644","\u0627\u0644\u062D\u062F \u0627\u0644\u0625\u062C\u0645\u0627\u0644\u064A"]};function fk(e,t,n=[],r={}){let i=Si(t)??"en",[a="en",...o]=i.split("-"),s=a==="zh"&&!o.includes("Hans")&&o.some(h=>["Hant","TW","HK","MO"].includes(h))?"zh-Hant":a,c=Gs[s]??Gs.en,u=Gs[s]?i:"en",l=h=>new Intl.NumberFormat(u).format(h),d=h=>new Intl.DateTimeFormat(u,{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(new Date(h))+" UTC",p=[e.appliesTo.type==="all"?c[0]:`${c[1]}${n.length?`: ${n.slice(0,3).join(", ")+(n.length>3?` (+${l(n.length-3)})`:"")}`:""}`,e.eligibility.firstPurchaseOnly?c[3]:c[2],Object.keys(e.eligibility.condition).length||r.qualificationRequired?`${c[4]}${r.includeQualificationTags!==!1&&Ep(e.eligibility.condition)?`: ${Ep(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),g=[e.startsAt?`${c[5]}: ${d(e.startsAt)}`:null,e.endsAt?`${c[6]}: ${d(e.endsAt)}`:c[7]].filter(Boolean).join(" \xB7 "),m=[p,g,`${c[8]}: ${l(e.grantWindowHours)} ${c[9]}`,`${c[10]}: ${l(e.perCustomerLimit)}`,e.totalLimit===null?null:`${c[11]}: ${l(e.totalLimit)}`].filter(Boolean).join(" \xB7 ");return{eligibility:p,validity:g,terms:m}}function Ep(e){let t=e.tags;if(!t||typeof t!="object"||Array.isArray(t))return"";let n=t.$all??t.$in;return Array.isArray(n)&&n.every(r=>typeof r=="string")?n.join(", "):""}import{z as Y}from"zod";var It=Y.string().min(1).max(255),ln=Y.number().finite().nonnegative(),Tp=Y.strictObject({properties:Y.record(Y.string().min(1).max(64),Y.union([Y.string().min(1).max(128),Y.number().finite(),Y.boolean()]).transform(String).pipe(Y.string())).refine(e=>Object.keys(e).length>=1&&Object.keys(e).length<=4)}),kS=Y.strictObject({feature_id:It,enabled:Y.boolean().default(!1),threshold:Y.number().finite(),quantity:Y.number().finite().min(1),purchase_limit:Y.strictObject({interval:Y.enum(["hour","day","week","month"]),interval_count:Y.number().finite().min(1).default(1),limit:Y.number().finite().min(1)}).optional(),invoice_mode:Y.boolean().optional()}),DS=Y.strictObject({feature_id:It.optional(),enabled:Y.boolean().default(!1),limit_type:Y.enum(["absolute","usage_percentage"]).optional(),overage_limit:ln.optional(),skip_overage_billing:Y.boolean().optional()}).refine(e=>e.overage_limit===void 0&&e.skip_overage_billing===void 0||e.feature_id!==void 0,"A feature is required for overage limits and billing controls"),FS=Y.strictObject({feature_id:It,enabled:Y.boolean().default(!0),limit:ln,interval:Y.enum(["day","week","month","year"]),anchor:Y.enum(["billing_cycle","utc"]).optional(),filter:Tp.optional()}),US=Y.strictObject({feature_id:It.optional(),enabled:Y.boolean().default(!0),threshold:ln,threshold_type:Y.enum(["usage","usage_percentage","remaining","remaining_percentage"]),basis:Y.enum(["balance","included","recurring","usage_limit"]).default("balance"),filter:Tp.optional(),name:Y.string().optional()}).refine(e=>e.threshold_type!=="remaining_percentage"||e.threshold<=100,"Remaining percentage cannot exceed 100").refine(e=>e.basis!=="usage_limit"||e.feature_id!==void 0,"Usage-limit alerts require a feature").refine(e=>e.filter===void 0||e.basis==="usage_limit","Filters apply only to usage-limit alerts"),MS=Y.strictObject({feature_id:It,enabled:Y.boolean().default(!1)}),BS=Y.strictObject({auto_topups:Y.array(kS).nullable(),spend_limits:Y.array(DS).nullable(),usage_limits:Y.array(FS).nullable(),usage_alerts:Y.array(US).nullable(),overage_allowed:Y.array(MS).nullable()}),bk=BS.omit({auto_topups:!0}),LS=ir,yk=Y.strictObject({internal_id:Y.uuid(),id:It.nullable(),project_id:Y.uuid(),environment_id:Y.uuid(),name:Y.string().max(80).nullable(),email:Y.string().max(254).nullable(),metadata:LS.nullable(),created_at:Y.number().finite().nonnegative().max(864e13)}),Sk=Y.strictObject({id:It,internal_product_id:It,product_id:It.nullable(),status:Y.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:ln.nullable(),free_trial_id:It.nullable(),trial_ends_at:ln.nullable(),starts_at:ln.nullable(),access_starts_at:ln.nullable(),ended_at:ln.nullable(),product:Y.strictObject({internal_id:It,id:It,name:Y.string(),version:Y.number().int().positive(),is_add_on:Y.boolean()})});import{z as pe}from"zod";var rt=pe.number().int().nonnegative(),Rp=pe.strictObject({at:pe.iso.datetime({offset:!0}),id:pe.uuid()}),Ok=pe.strictObject({versionId:pe.uuid().nullable(),from:pe.iso.datetime({offset:!0}).nullable(),to:pe.iso.datetime({offset:!0}).nullable(),after:Rp.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),Pk=pe.strictObject({funnelId:pe.uuid(),snapshotAt:pe.iso.datetime({offset:!0}),versions:pe.array(pe.strictObject({id:pe.uuid(),version:pe.number().int().positive(),createdAt:pe.iso.datetime({offset:!0})})).max(100),versionsLimited:pe.boolean(),overall:pe.strictObject({started:rt,completed:rt,closed:rt,failed:rt,waiting:rt,paid:rt}),decisions:pe.strictObject({queries:rt,completed:rt,reportedUsed:rt,pending:rt,failed:rt}),revenue:pe.array(pe.strictObject({currency:se,grossMinor:pe.string().regex(/^\d+$/),refundMinor:pe.string().regex(/^\d+$/),netMinor:pe.string().regex(/^-?\d+$/)})).max(100),nodes:pe.array(pe.strictObject({versionId:pe.uuid(),nodeId:pe.string(),visits:rt,completed:rt,shown:rt,waiting:rt})).max(1e4),recentRuns:pe.array(pe.strictObject({id:pe.uuid(),versionId:pe.uuid(),customerId:pe.uuid(),status:Vs,nodeId:pe.string(),visit:rt,createdAt:pe.iso.datetime({offset:!0}),updatedAt:pe.iso.datetime({offset:!0})})).max(100),nextCursor:Rp.nullable()});import{z as xt}from"zod";import{z as Je}from"zod";var jp=Je.discriminatedUnion("provider",[Je.strictObject({provider:Je.literal("apple"),orderId:Je.uuid(),receiptId:Je.uuid(),signedTransaction:Je.string().min(1).max(131072)}),Je.strictObject({provider:Je.literal("google"),orderId:Je.uuid(),receiptId:Je.uuid(),purchaseToken:Je.string().min(1).max(16384)})]),Np=Je.strictObject({orderId:Je.uuid(),receiptId:Je.uuid(),transactionIds:Je.array(Je.string().min(1).max(255)).min(1).max(50),membership:Je.boolean()});var Nk=xt.strictObject({operation:xt.literal("native_receipt"),requestId:xt.uuid(),customerToken:xt.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:xt.uuid(),receiptId:xt.uuid(),nativeEvidence:jp.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),kk=xt.strictObject({scope:we,requestId:xt.uuid(),orderId:xt.uuid(),receiptId:xt.uuid(),orderStatus:xt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:xt.boolean(),nativeCompletion:Np.optional()});function VS(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function Fk(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function kp(e){return VS(e)?e.intervalCount??1:1}function Uk(e,t){return e.interval===t.interval&&kp(e)===kp(t)}function Mk(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},a={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},o=e==="week"?`/${a[r]??a.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?o:`/${n} ${o.slice(1)}${r==="en"?"s":""}`}import{z as Te}from"zod";var Dp=Te.string().regex(/^[a-f0-9]{64}$/),qS=Kc.omit({variations:!0,active:!0}).extend({changeId:Dp,variations:Te.array(Te.strictObject({urlRedirect:Te.string().max(2048)})).min(2).max(20)}),Gk=Te.strictObject({environmentId:Te.uuid(),trackExposures:Te.boolean(),generation:Dp,experiments:Te.array(qS).max(100),savedGroups:Wc}),$S=Te.strictObject({eventUuid:Te.uuid(),timestamp:Te.iso.datetime({offset:!0}).optional(),deviceId:Te.string().min(1).max(128),sessionId:Te.string().min(1).max(128).optional(),url:Te.url().max(2048),pageTitle:Te.string().max(512).optional(),experimentKey:Te.string().min(1).max(255),variationKey:Te.string().min(1).max(64)}),Kk=Te.strictObject({events:Te.array($S).min(1).max(20)}),Hk=Te.strictObject({inserted:Te.number().int().nonnegative(),duplicates:Te.number().int().nonnegative(),skipped:Te.number().int().nonnegative(),rejected:Te.array(Te.strictObject({index:Te.number().int().nonnegative(),reason:Te.string()}))});/*!
2
+ * decimal.js v10.6.0
3
+ * An arbitrary-precision Decimal type for JavaScript.
4
+ * https://github.com/MikeMcl/decimal.js
5
+ * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
6
+ * MIT Licence
7
+ */var hr=9e15,fn=1e9,Ks="0123456789abcdef",xa="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Aa="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Hs={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-hr,maxE:hr,crypto:!1},Bp,Wt,re=!0,Pa="[DecimalError] ",pn=Pa+"Invalid argument: ",Lp=Pa+"Precision limit exceeded",Vp=Pa+"crypto unavailable",qp="[object Decimal]",it=Math.floor,qe=Math.pow,GS=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,KS=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,HS=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,$p=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,wt=1e7,X=7,WS=9007199254740991,QS=xa.length-1,Ws=Aa.length-1,w={toStringTag:qp};w.absoluteValue=w.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),Q(e)};w.ceil=function(){return Q(new this.constructor(this),this.e+1,2)};w.clampedTo=w.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(pn+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};w.comparedTo=w.cmp=function(e){var t,n,r,i,a=this,o=a.d,s=(e=new a.constructor(e)).d,c=a.s,u=e.s;if(!o||!s)return!c||!u?NaN:c!==u?c:o===s?0:!o^c<0?1:-1;if(!o[0]||!s[0])return o[0]?c:s[0]?-u:0;if(c!==u)return c;if(a.e!==e.e)return a.e>e.e^c<0?1:-1;for(r=o.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==s[t])return o[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1};w.cosine=w.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+X,r.rounding=1,n=ZS(r,Qp(r,n)),r.precision=e,r.rounding=t,Q(Wt==2||Wt==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};w.cubeRoot=w.cbrt=function(){var e,t,n,r,i,a,o,s,c,u,l=this,d=l.constructor;if(!l.isFinite()||l.isZero())return new d(l);for(re=!1,a=l.s*qe(l.s*l,1/3),!a||Math.abs(a)==1/0?(n=Xe(l.d),e=l.e,(a=(e-n.length+1)%3)&&(n+=a==1||a==-2?"0":"00"),a=qe(n,1/3),e=it((e+1)/3)-(e%3==(e<0?-1:2)),a==1/0?n="5e"+e:(n=a.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new d(n),r.s=l.s):r=new d(a.toString()),o=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),u=c.plus(l),r=Re(u.plus(l).times(s),u.plus(c),o+2,1),Xe(s.d).slice(0,o)===(n=Xe(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(Q(s,e+1,0),s.times(s).times(s).eq(l))){r=s;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(Q(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return re=!0,Q(r,e,d.rounding,t)};w.decimalPlaces=w.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-it(this.e/X))*X,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};w.dividedBy=w.div=function(e){return Re(this,new this.constructor(e))};w.dividedToIntegerBy=w.divToInt=function(e){var t=this,n=t.constructor;return Q(Re(t,new n(e),0,1,1),n.precision,n.rounding)};w.equals=w.eq=function(e){return this.cmp(e)===0};w.floor=function(){return Q(new this.constructor(this),this.e+1,3)};w.greaterThan=w.gt=function(e){return this.cmp(e)>0};w.greaterThanOrEqualTo=w.gte=function(e){var t=this.cmp(e);return t==1||t===0};w.hyperbolicCosine=w.cosh=function(){var e,t,n,r,i,a=this,o=a.constructor,s=new o(1);if(!a.isFinite())return new o(a.s?1/0:NaN);if(a.isZero())return s;n=o.precision,r=o.rounding,o.precision=n+Math.max(a.e,a.sd())+4,o.rounding=1,i=a.d.length,i<32?(e=Math.ceil(i/3),t=(1/wa(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),a=gr(o,1,a.times(t),new o(1),!0);for(var c,u=e,l=new o(8);u--;)c=a.times(a),a=s.minus(c.times(l.minus(c.times(l))));return Q(a,o.precision=n,o.rounding=r,!0)};w.hyperbolicSine=w.sinh=function(){var e,t,n,r,i=this,a=i.constructor;if(!i.isFinite()||i.isZero())return new a(i);if(t=a.precision,n=a.rounding,a.precision=t+Math.max(i.e,i.sd())+4,a.rounding=1,r=i.d.length,r<3)i=gr(a,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/wa(5,e)),i=gr(a,2,i,i,!0);for(var o,s=new a(5),c=new a(16),u=new a(20);e--;)o=i.times(i),i=i.times(s.plus(o.times(c.times(o).plus(u))))}return a.precision=t,a.rounding=n,Q(i,t,n,!0)};w.hyperbolicTangent=w.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Re(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};w.inverseCosine=w.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?Bt(t,r,i):new t(0):new t(NaN):e.isZero()?Bt(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};w.inverseHyperbolicCosine=w.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,re=!1,n=n.times(n).minus(1).sqrt().plus(n),re=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};w.inverseHyperbolicSine=w.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,re=!1,n=n.times(n).plus(1).sqrt().plus(n),re=!0,r.precision=e,r.rounding=t,n.ln())};w.inverseHyperbolicTangent=w.atanh=function(){var e,t,n,r,i=this,a=i.constructor;return i.isFinite()?i.e>=0?new a(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=a.precision,t=a.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?Q(new a(i),e,t,!0):(a.precision=n=r-i.e,i=Re(i.plus(1),new a(1).minus(i),n+e,1),a.precision=e+4,a.rounding=1,i=i.ln(),a.precision=e,a.rounding=t,i.times(.5))):new a(NaN)};w.inverseSine=w.asin=function(){var e,t,n,r,i=this,a=i.constructor;return i.isZero()?new a(i):(t=i.abs().cmp(1),n=a.precision,r=a.rounding,t!==-1?t===0?(e=Bt(a,n+4,r).times(.5),e.s=i.s,e):new a(NaN):(a.precision=n+6,a.rounding=1,i=i.div(new a(1).minus(i.times(i)).sqrt().plus(1)).atan(),a.precision=n,a.rounding=r,i.times(2)))};w.inverseTangent=w.atan=function(){var e,t,n,r,i,a,o,s,c,u=this,l=u.constructor,d=l.precision,p=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&d+4<=Ws)return o=Bt(l,d+4,p).times(.25),o.s=u.s,o}else{if(!u.s)return new l(NaN);if(d+4<=Ws)return o=Bt(l,d+4,p).times(.5),o.s=u.s,o}for(l.precision=s=d+10,l.rounding=1,n=Math.min(28,s/X+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(re=!1,t=Math.ceil(s/X),r=1,c=u.times(u),o=new l(u),i=u;e!==-1;)if(i=i.times(c),a=o.minus(i.div(r+=2)),i=i.times(c),o=a.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===a.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),re=!0,Q(o,l.precision=d,l.rounding=p,!0)};w.isFinite=function(){return!!this.d};w.isInteger=w.isInt=function(){return!!this.d&&it(this.e/X)>this.d.length-2};w.isNaN=function(){return!this.s};w.isNegative=w.isNeg=function(){return this.s<0};w.isPositive=w.isPos=function(){return this.s>0};w.isZero=function(){return!!this.d&&this.d[0]===0};w.lessThan=w.lt=function(e){return this.cmp(e)<0};w.lessThanOrEqualTo=w.lte=function(e){return this.cmp(e)<1};w.logarithm=w.log=function(e){var t,n,r,i,a,o,s,c,u=this,l=u.constructor,d=l.precision,p=l.rounding,g=5;if(e==null)e=new l(10),t=!0;else{if(e=new l(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new l(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new l(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)a=!0;else{for(i=n[0];i%10===0;)i/=10;a=i!==1}if(re=!1,s=d+g,o=mn(u,s),r=t?Oa(l,s+10):mn(e,s),c=Re(o,r,s,1),li(c.d,i=d,p))do if(s+=10,o=mn(u,s),r=t?Oa(l,s+10):mn(e,s),c=Re(o,r,s,1),!a){+Xe(c.d).slice(i+1,i+15)+1==1e14&&(c=Q(c,d+1,0));break}while(li(c.d,i+=10,p));return re=!0,Q(c,d,p)};w.minus=w.sub=function(e){var t,n,r,i,a,o,s,c,u,l,d,p,g=this,m=g.constructor;if(e=new m(e),!g.d||!e.d)return!g.s||!e.s?e=new m(NaN):g.d?e.s=-e.s:e=new m(e.d||g.s!==e.s?g:NaN),e;if(g.s!=e.s)return e.s=-e.s,g.plus(e);if(u=g.d,p=e.d,s=m.precision,c=m.rounding,!u[0]||!p[0]){if(p[0])e.s=-e.s;else if(u[0])e=new m(g);else return new m(c===3?-0:0);return re?Q(e,s,c):e}if(n=it(e.e/X),l=it(g.e/X),u=u.slice(),a=l-n,a){for(d=a<0,d?(t=u,a=-a,o=p.length):(t=p,n=l,o=u.length),r=Math.max(Math.ceil(s/X),o)+2,a>r&&(a=r,t.length=1),t.reverse(),r=a;r--;)t.push(0);t.reverse()}else{for(r=u.length,o=p.length,d=r<o,d&&(o=r),r=0;r<o;r++)if(u[r]!=p[r]){d=u[r]<p[r];break}a=0}for(d&&(t=u,u=p,p=t,e.s=-e.s),o=u.length,r=p.length-o;r>0;--r)u[o++]=0;for(r=p.length;r>a;){if(u[--r]<p[r]){for(i=r;i&&u[--i]===0;)u[i]=wt-1;--u[i],u[r]+=wt}u[r]-=p[r]}for(;u[--o]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=Ca(u,n),re?Q(e,s,c):e):new m(c===3?-0:0)};w.modulo=w.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?Q(new r(n),r.precision,r.rounding):(re=!1,r.modulo==9?(t=Re(n,e.abs(),0,3,1),t.s*=e.s):t=Re(n,e,0,r.modulo,1),t=t.times(e),re=!0,n.minus(t))};w.naturalExponential=w.exp=function(){return Qs(this)};w.naturalLogarithm=w.ln=function(){return mn(this)};w.negated=w.neg=function(){var e=new this.constructor(this);return e.s=-e.s,Q(e)};w.plus=w.add=function(e){var t,n,r,i,a,o,s,c,u,l,d=this,p=d.constructor;if(e=new p(e),!d.d||!e.d)return!d.s||!e.s?e=new p(NaN):d.d||(e=new p(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(u=d.d,l=e.d,s=p.precision,c=p.rounding,!u[0]||!l[0])return l[0]||(e=new p(d)),re?Q(e,s,c):e;if(a=it(d.e/X),r=it(e.e/X),u=u.slice(),i=a-r,i){for(i<0?(n=u,i=-i,o=l.length):(n=l,r=a,o=u.length),a=Math.ceil(s/X),o=a>o?a+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=u.length,i=l.length,o-i<0&&(i=o,n=l,l=u,u=n),t=0;i;)t=(u[--i]=u[i]+l[i]+t)/wt|0,u[i]%=wt;for(t&&(u.unshift(t),++r),o=u.length;u[--o]==0;)u.pop();return e.d=u,e.e=Ca(u,r),re?Q(e,s,c):e};w.precision=w.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(pn+e);return n.d?(t=Gp(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};w.round=function(){var e=this,t=e.constructor;return Q(new t(e),e.e+1,t.rounding)};w.sine=w.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+X,r.rounding=1,n=JS(r,Qp(r,n)),r.precision=e,r.rounding=t,Q(Wt>2?n.neg():n,e,t,!0)):new r(NaN)};w.squareRoot=w.sqrt=function(){var e,t,n,r,i,a,o=this,s=o.d,c=o.e,u=o.s,l=o.constructor;if(u!==1||!s||!s[0])return new l(!u||u<0&&(!s||s[0])?NaN:s?o:1/0);for(re=!1,u=Math.sqrt(+o),u==0||u==1/0?(t=Xe(s),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=it((c+1)/2)-(c<0||c%2),u==1/0?t="5e"+c:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new l(t)):r=new l(u.toString()),n=(c=l.precision)+3;;)if(a=r,r=a.plus(Re(o,a,n+2,1)).times(.5),Xe(a.d).slice(0,n)===(t=Xe(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(Q(a,c+1,0),a.times(a).eq(o))){r=a;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(Q(r,c+1,1),e=!r.times(r).eq(o));break}return re=!0,Q(r,c,l.rounding,e)};w.tangent=w.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Re(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,Q(Wt==2||Wt==4?n.neg():n,e,t,!0)):new r(NaN)};w.times=w.mul=function(e){var t,n,r,i,a,o,s,c,u,l=this,d=l.constructor,p=l.d,g=(e=new d(e)).d;if(e.s*=l.s,!p||!p[0]||!g||!g[0])return new d(!e.s||p&&!p[0]&&!g||g&&!g[0]&&!p?NaN:!p||!g?e.s/0:e.s*0);for(n=it(l.e/X)+it(e.e/X),c=p.length,u=g.length,c<u&&(a=p,p=g,g=a,o=c,c=u,u=o),a=[],o=c+u,r=o;r--;)a.push(0);for(r=u;--r>=0;){for(t=0,i=c+r;i>r;)s=a[i]+g[r]*p[i-r-1]+t,a[i--]=s%wt|0,t=s/wt|0;a[i]=(a[i]+t)%wt|0}for(;!a[--o];)a.pop();return t?++n:a.shift(),e.d=a,e.e=Ca(a,n),re?Q(e,d.precision,d.rounding):e};w.toBinary=function(e,t){return Zs(this,2,e,t)};w.toDecimalPlaces=w.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(ut(e,0,fn),t===void 0?t=r.rounding:ut(t,0,8),Q(n,e+n.e+1,t))};w.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Lt(r,!0):(ut(e,0,fn),t===void 0?t=i.rounding:ut(t,0,8),r=Q(new i(r),e+1,t),n=Lt(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};w.toFixed=function(e,t){var n,r,i=this,a=i.constructor;return e===void 0?n=Lt(i):(ut(e,0,fn),t===void 0?t=a.rounding:ut(t,0,8),r=Q(new a(i),e+i.e+1,t),n=Lt(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};w.toFraction=function(e){var t,n,r,i,a,o,s,c,u,l,d,p,g=this,m=g.d,h=g.constructor;if(!m)return new h(g);if(u=n=new h(1),r=c=new h(0),t=new h(r),a=t.e=Gp(m)-g.e-1,o=a%X,t.d[0]=qe(10,o<0?X+o:o),e==null)e=a>0?t:u;else{if(s=new h(e),!s.isInt()||s.lt(u))throw Error(pn+s);e=s.gt(t)?a>0?t:u:s}for(re=!1,s=new h(Xe(m)),l=h.precision,h.precision=a=m.length*X*2;d=Re(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=c.plus(d.times(i)),c=i,i=t,t=s.minus(d.times(i)),s=i;return i=Re(e.minus(n),r,0,1,1),c=c.plus(i.times(u)),n=n.plus(i.times(r)),c.s=u.s=g.s,p=Re(u,r,a,1).minus(g).abs().cmp(Re(c,n,a,1).minus(g).abs())<1?[u,r]:[c,n],h.precision=l,re=!0,p};w.toHexadecimal=w.toHex=function(e,t){return Zs(this,16,e,t)};w.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:ut(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(re=!1,n=Re(n,e,0,t,1).times(e),re=!0,Q(n)):(e.s=n.s,n=e),n};w.toNumber=function(){return+this};w.toOctal=function(e,t){return Zs(this,8,e,t)};w.toPower=w.pow=function(e){var t,n,r,i,a,o,s=this,c=s.constructor,u=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(qe(+s,u));if(s=new c(s),s.eq(1))return s;if(r=c.precision,a=c.rounding,e.eq(1))return Q(s,r,a);if(t=it(e.e/X),t>=e.d.length-1&&(n=u<0?-u:u)<=WS)return i=Kp(c,s,n,r),e.s<0?new c(1).div(i):Q(i,r,a);if(o=s.s,o<0){if(t<e.d.length-1)return new c(NaN);if((e.d[t]&1)==0&&(o=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=o,s}return n=qe(+s,u),t=n==0||!isFinite(n)?it(u*(Math.log("0."+Xe(s.d))/Math.LN10+s.e+1)):new c(n+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?o/0:0):(re=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Qs(e.times(mn(s,r+n)),r),i.d&&(i=Q(i,r+5,1),li(i.d,r,a)&&(t=r+10,i=Q(Qs(e.times(mn(s,t+n)),t),t+5,1),+Xe(i.d).slice(r+1,r+15)+1==1e14&&(i=Q(i,r+1,0)))),i.s=o,re=!0,c.rounding=a,Q(i,r,a))};w.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=Lt(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(ut(e,1,fn),t===void 0?t=i.rounding:ut(t,0,8),r=Q(new i(r),e,t),n=Lt(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};w.toSignificantDigits=w.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(ut(e,1,fn),t===void 0?t=r.rounding:ut(t,0,8)),Q(new r(n),e,t)};w.toString=function(){var e=this,t=e.constructor,n=Lt(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};w.truncated=w.trunc=function(){return Q(new this.constructor(this),this.e+1,1)};w.valueOf=w.toJSON=function(){var e=this,t=e.constructor,n=Lt(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function Xe(e){var t,n,r,i=e.length-1,a="",o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+"",n=X-r.length,n&&(a+=dn(n)),a+=r;o=e[t],r=o+"",n=X-r.length,n&&(a+=dn(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return a+o}function ut(e,t,n){if(e!==~~e||e<t||e>n)throw Error(pn+e)}function li(e,t,n,r){var i,a,o,s;for(a=e[0];a>=10;a/=10)--t;return--t<0?(t+=X,i=0):(i=Math.ceil((t+1)/X),t%=X),a=qe(10,X-t),s=e[i]%a|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),o=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):o=(n<4&&s+1==a||n>3&&s+1==a/2)&&(e[i+1]/a/100|0)==qe(10,t-2)-1||(s==a/2||s==0)&&(e[i+1]/a/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),o=(r||n<4)&&s==9999||!r&&n>3&&s==4999):o=((r||n<4)&&s+1==a||!r&&n>3&&s+1==a/2)&&(e[i+1]/a/1e3|0)==qe(10,t-3)-1,o}function va(e,t,n){for(var r,i=[0],a,o=0,s=e.length;o<s;){for(a=i.length;a--;)i[a]*=t;for(i[0]+=Ks.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function ZS(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/wa(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=gr(e,1,t.times(i),new e(1));for(var a=n;a--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var Re=(function(){function e(r,i,a){var o,s=0,c=r.length;for(r=r.slice();c--;)o=r[c]*i+s,r[c]=o%a|0,s=o/a|0;return s&&r.unshift(s),r}function t(r,i,a,o){var s,c;if(a!=o)c=a>o?1:-1;else for(s=c=0;s<a;s++)if(r[s]!=i[s]){c=r[s]>i[s]?1:-1;break}return c}function n(r,i,a,o){for(var s=0;a--;)r[a]-=s,s=r[a]<i[a]?1:0,r[a]=s*o+r[a]-i[a];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,a,o,s,c){var u,l,d,p,g,m,h,y,x,v,E,A,S,q,L,ge,Ie,ne,B,Ce,H=r.constructor,He=r.s==i.s?1:-1,ue=r.d,te=i.d;if(!ue||!ue[0]||!te||!te[0])return new H(!r.s||!i.s||(ue?te&&ue[0]==te[0]:!te)?NaN:ue&&ue[0]==0||!te?He*0:He/0);for(c?(g=1,l=r.e-i.e):(c=wt,g=X,l=it(r.e/g)-it(i.e/g)),B=te.length,Ie=ue.length,x=new H(He),v=x.d=[],d=0;te[d]==(ue[d]||0);d++);if(te[d]>(ue[d]||0)&&l--,a==null?(q=a=H.precision,o=H.rounding):s?q=a+(r.e-i.e)+1:q=a,q<0)v.push(1),m=!0;else{if(q=q/g+2|0,d=0,B==1){for(p=0,te=te[0],q++;(d<Ie||p)&&q--;d++)L=p*c+(ue[d]||0),v[d]=L/te|0,p=L%te|0;m=p||d<Ie}else{for(p=c/(te[0]+1)|0,p>1&&(te=e(te,p,c),ue=e(ue,p,c),B=te.length,Ie=ue.length),ge=B,E=ue.slice(0,B),A=E.length;A<B;)E[A++]=0;Ce=te.slice(),Ce.unshift(0),ne=te[0],te[1]>=c/2&&++ne;do p=0,u=t(te,E,B,A),u<0?(S=E[0],B!=A&&(S=S*c+(E[1]||0)),p=S/ne|0,p>1?(p>=c&&(p=c-1),h=e(te,p,c),y=h.length,A=E.length,u=t(h,E,y,A),u==1&&(p--,n(h,B<y?Ce:te,y,c))):(p==0&&(u=p=1),h=te.slice()),y=h.length,y<A&&h.unshift(0),n(E,h,A,c),u==-1&&(A=E.length,u=t(te,E,B,A),u<1&&(p++,n(E,B<A?Ce:te,A,c))),A=E.length):u===0&&(p++,E=[0]),v[d++]=p,u&&E[0]?E[A++]=ue[ge]||0:(E=[ue[ge]],A=1);while((ge++<Ie||E[0]!==void 0)&&q--);m=E[0]!==void 0}v[0]||v.shift()}if(g==1)x.e=l,Bp=m;else{for(d=1,p=v[0];p>=10;p/=10)d++;x.e=d+l*g-1,Q(x,s?a+x.e+1:a,o,m)}return x}})();function Q(e,t,n,r){var i,a,o,s,c,u,l,d,p,g=e.constructor;e:if(t!=null){if(d=e.d,!d)return e;for(i=1,s=d[0];s>=10;s/=10)i++;if(a=t-i,a<0)a+=X,o=t,l=d[p=0],c=l/qe(10,i-o-1)%10|0;else if(p=Math.ceil((a+1)/X),s=d.length,p>=s)if(r){for(;s++<=p;)d.push(0);l=c=0,i=1,a%=X,o=a-X+1}else break e;else{for(l=s=d[p],i=1;s>=10;s/=10)i++;a%=X,o=a-X+i,c=o<0?0:l/qe(10,i-o-1)%10|0}if(r=r||t<0||d[p+1]!==void 0||(o<0?l:l%qe(10,i-o-1)),u=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(a>0?o>0?l/qe(10,i-o):0:d[p-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,u?(t-=e.e+1,d[0]=qe(10,(X-t%X)%X),e.e=-t||0):d[0]=e.e=0,e;if(a==0?(d.length=p,s=1,p--):(d.length=p+1,s=qe(10,X-a),d[p]=o>0?(l/qe(10,i-o)%qe(10,o)|0)*s:0),u)for(;;)if(p==0){for(a=1,o=d[0];o>=10;o/=10)a++;for(o=d[0]+=s,s=1;o>=10;o/=10)s++;a!=s&&(e.e++,d[0]==wt&&(d[0]=1));break}else{if(d[p]+=s,d[p]!=wt)break;d[p--]=0,s=1}for(a=d.length;d[--a]===0;)d.pop()}return re&&(e.e>g.maxE?(e.d=null,e.e=NaN):e.e<g.minE&&(e.e=0,e.d=[0])),e}function Lt(e,t,n){if(!e.isFinite())return Wp(e);var r,i=e.e,a=Xe(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+"."+a.slice(1)+dn(r):o>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(e.e<0?"e":"e+")+e.e):i<0?(a="0."+dn(-i-1)+a,n&&(r=n-o)>0&&(a+=dn(r))):i>=o?(a+=dn(i+1-o),n&&(r=n-i-1)>0&&(a=a+"."+dn(r))):((r=i+1)<o&&(a=a.slice(0,r)+"."+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+="."),a+=dn(r))),a}function Ca(e,t){var n=e[0];for(t*=X;n>=10;n/=10)t++;return t}function Oa(e,t,n){if(t>QS)throw re=!0,n&&(e.precision=n),Error(Lp);return Q(new e(xa),t,1,!0)}function Bt(e,t,n){if(t>Ws)throw Error(Lp);return Q(new e(Aa),t,n,!0)}function Gp(e){var t=e.length-1,n=t*X+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function dn(e){for(var t="";e--;)t+="0";return t}function Kp(e,t,n,r){var i,a=new e(1),o=Math.ceil(r/X+4);for(re=!1;;){if(n%2&&(a=a.times(t),Up(a.d,o)&&(i=!0)),n=it(n/2),n===0){n=a.d.length-1,i&&a.d[n]===0&&++a.d[n];break}t=t.times(t),Up(t.d,o)}return re=!0,a}function Fp(e){return e.d[e.d.length-1]&1}function Hp(e,t,n){for(var r,i,a=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){a=i;break}r=a.cmp(i),(r===n||r===0&&a.s===n)&&(a=i)}return a}function Qs(e,t){var n,r,i,a,o,s,c,u=0,l=0,d=0,p=e.constructor,g=p.rounding,m=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(re=!1,c=m):c=t,s=new p(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(qe(2,d))/Math.LN10*2+5|0,c+=r,n=a=o=new p(1),p.precision=c;;){if(a=Q(a.times(e),c,1),n=n.times(++l),s=o.plus(Re(a,n,c,1)),Xe(s.d).slice(0,c)===Xe(o.d).slice(0,c)){for(i=d;i--;)o=Q(o.times(o),c,1);if(t==null)if(u<3&&li(o.d,c-r,g,u))p.precision=c+=10,n=a=s=new p(1),l=0,u++;else return Q(o,p.precision=m,g,re=!0);else return p.precision=m,o}o=s}}function mn(e,t){var n,r,i,a,o,s,c,u,l,d,p,g=1,m=10,h=e,y=h.d,x=h.constructor,v=x.rounding,E=x.precision;if(h.s<0||!y||!y[0]||!h.e&&y[0]==1&&y.length==1)return new x(y&&!y[0]?-1/0:h.s!=1?NaN:y?0:h);if(t==null?(re=!1,l=E):l=t,x.precision=l+=m,n=Xe(y),r=n.charAt(0),Math.abs(a=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=Xe(h.d),r=n.charAt(0),g++;a=h.e,r>1?(h=new x("0."+n),a++):h=new x(r+"."+n.slice(1))}else return u=Oa(x,l+2,E).times(a+""),h=mn(new x(r+"."+n.slice(1)),l-m).plus(u),x.precision=E,t==null?Q(h,E,v,re=!0):h;for(d=h,c=o=h=Re(h.minus(1),h.plus(1),l,1),p=Q(h.times(h),l,1),i=3;;){if(o=Q(o.times(p),l,1),u=c.plus(Re(o,new x(i),l,1)),Xe(u.d).slice(0,l)===Xe(c.d).slice(0,l))if(c=c.times(2),a!==0&&(c=c.plus(Oa(x,l+2,E).times(a+""))),c=Re(c,new x(g),l,1),t==null)if(li(c.d,l-m,v,s))x.precision=l+=m,u=o=h=Re(d.minus(1),d.plus(1),l,1),p=Q(h.times(h),l,1),i=s=1;else return Q(c,x.precision=E,v,re=!0);else return x.precision=E,c;c=u,i+=2}}function Wp(e){return String(e.s*e.s/0)}function Ia(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%X,n<0&&(r+=X),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=X;r<i;)e.d.push(+t.slice(r,r+=X));t=t.slice(r),r=X-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),re&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function YS(e,t){var n,r,i,a,o,s,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),$p.test(t))return Ia(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(KS.test(t))n=16,t=t.toLowerCase();else if(GS.test(t))n=2;else if(HS.test(t))n=8;else throw Error(pn+t);for(a=t.search(/p/i),a>0?(c=+t.slice(a+1),t=t.substring(2,a)):t=t.slice(2),a=t.indexOf("."),o=a>=0,r=e.constructor,o&&(t=t.replace(".",""),s=t.length,a=s-a,i=Kp(r,new r(n),a,a*2)),u=va(t,n,wt),l=u.length-1,a=l;u[a]===0;--a)u.pop();return a<0?new r(e.s*0):(e.e=Ca(u,l),e.d=u,re=!1,o&&(e=Re(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?qe(2,c):Et.pow(2,c))),re=!0,e)}function JS(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:gr(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/wa(5,n)),t=gr(e,2,t,t);for(var i,a=new e(5),o=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(a.plus(i.times(o.times(i).minus(s))));return t}function gr(e,t,n,r,i){var a,o,s,c,u=1,l=e.precision,d=Math.ceil(l/X);for(re=!1,c=n.times(n),s=new e(r);;){if(o=Re(s.times(c),new e(t++*t++),l,1),s=i?r.plus(o):r.minus(o),r=Re(o.times(c),new e(t++*t++),l,1),o=s.plus(r),o.d[d]!==void 0){for(a=d;o.d[a]===s.d[a]&&a--;);if(a==-1)break}a=s,s=r,r=o,o=a,u++}return re=!0,o.d.length=d+1,o}function wa(e,t){for(var n=e;--t;)n*=e;return n}function Qp(e,t){var n,r=t.s<0,i=Bt(e,e.precision,1),a=i.times(.5);if(t=t.abs(),t.lte(a))return Wt=r?4:1,t;if(n=t.divToInt(i),n.isZero())Wt=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(a))return Wt=Fp(n)?r?2:3:r?4:1,t;Wt=Fp(n)?r?1:4:r?3:2}return t.minus(i).abs()}function Zs(e,t,n,r){var i,a,o,s,c,u,l,d,p,g=e.constructor,m=n!==void 0;if(m?(ut(n,1,fn),r===void 0?r=g.rounding:ut(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())l=Wp(e);else{for(l=Lt(e),o=l.indexOf("."),m?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(l=l.replace(".",""),p=new g(1),p.e=l.length-o,p.d=va(Lt(p),10,i),p.e=p.d.length),d=va(l,10,i),a=c=d.length;d[--c]==0;)d.pop();if(!d[0])l=m?"0p+0":"0";else{if(o<0?a--:(e=new g(e),e.d=d,e.e=a,e=Re(e,p,n,r,0,i),d=e.d,a=e.e,u=Bp),o=d[n],s=i/2,u=u||d[n+1]!==void 0,u=r<4?(o!==void 0||u)&&(r===0||r===(e.s<0?3:2)):o>s||o===s&&(r===4||u||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,u)for(;++d[--n]>i-1;)d[n]=0,n||(++a,d.unshift(1));for(c=d.length;!d[c-1];--c);for(o=0,l="";o<c;o++)l+=Ks.charAt(d[o]);if(m){if(c>1)if(t==16||t==8){for(o=t==16?4:3,--c;c%o;c++)l+="0";for(d=va(l,i,t),c=d.length;!d[c-1];--c);for(o=1,l="1.";o<c;o++)l+=Ks.charAt(d[o])}else l=l.charAt(0)+"."+l.slice(1);l=l+(a<0?"p":"p+")+a}else if(a<0){for(;++a;)l="0"+l;l="0."+l}else if(++a>c)for(a-=c;a--;)l+="0";else a<c&&(l=l.slice(0,a)+"."+l.slice(a))}l=(t==16?"0x":t==2?"0b":t==8?"0o":"")+l}return e.s<0?"-"+l:l}function Up(e,t){if(e.length>t)return e.length=t,!0}function XS(e){return new this(e).abs()}function zS(e){return new this(e).acos()}function ev(e){return new this(e).acosh()}function tv(e,t){return new this(e).plus(t)}function nv(e){return new this(e).asin()}function rv(e){return new this(e).asinh()}function iv(e){return new this(e).atan()}function av(e){return new this(e).atanh()}function ov(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,a=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=Bt(this,a,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?Bt(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=Bt(this,a,1).times(.5),n.s=e.s):t.s<0?(this.precision=a,this.rounding=1,n=this.atan(Re(e,t,a,1)),t=Bt(this,a,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Re(e,t,a,1)),n}function sv(e){return new this(e).cbrt()}function cv(e){return Q(e=new this(e),e.e+1,2)}function uv(e,t,n){return new this(e).clamp(t,n)}function lv(e){if(!e||typeof e!="object")throw Error(Pa+"Object expected");var t,n,r,i=e.defaults===!0,a=["precision",1,fn,"rounding",0,8,"toExpNeg",-hr,0,"toExpPos",0,hr,"maxE",0,hr,"minE",-hr,0,"modulo",0,9];for(t=0;t<a.length;t+=3)if(n=a[t],i&&(this[n]=Hs[n]),(r=e[n])!==void 0)if(it(r)===r&&r>=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(pn+n+": "+r);if(n="crypto",i&&(this[n]=Hs[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(Vp);else this[n]=!1;else throw Error(pn+n+": "+r);return this}function dv(e){return new this(e).cos()}function mv(e){return new this(e).cosh()}function Zp(e){var t,n,r;function i(a){var o,s,c,u=this;if(!(u instanceof i))return new i(a);if(u.constructor=i,Mp(a)){u.s=a.s,re?!a.d||a.e>i.maxE?(u.e=NaN,u.d=null):a.e<i.minE?(u.e=0,u.d=[0]):(u.e=a.e,u.d=a.d.slice()):(u.e=a.e,u.d=a.d?a.d.slice():a.d);return}if(c=typeof a,c==="number"){if(a===0){u.s=1/a<0?-1:1,u.e=0,u.d=[0];return}if(a<0?(a=-a,u.s=-1):u.s=1,a===~~a&&a<1e7){for(o=0,s=a;s>=10;s/=10)o++;re?o>i.maxE?(u.e=NaN,u.d=null):o<i.minE?(u.e=0,u.d=[0]):(u.e=o,u.d=[a]):(u.e=o,u.d=[a]);return}if(a*0!==0){a||(u.s=NaN),u.e=NaN,u.d=null;return}return Ia(u,a.toString())}if(c==="string")return(s=a.charCodeAt(0))===45?(a=a.slice(1),u.s=-1):(s===43&&(a=a.slice(1)),u.s=1),$p.test(a)?Ia(u,a):YS(u,a);if(c==="bigint")return a<0?(a=-a,u.s=-1):u.s=1,Ia(u,a.toString());throw Error(pn+a)}if(i.prototype=w,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=lv,i.clone=Zp,i.isDecimal=Mp,i.abs=XS,i.acos=zS,i.acosh=ev,i.add=tv,i.asin=nv,i.asinh=rv,i.atan=iv,i.atanh=av,i.atan2=ov,i.cbrt=sv,i.ceil=cv,i.clamp=uv,i.cos=dv,i.cosh=mv,i.div=pv,i.exp=fv,i.floor=hv,i.hypot=gv,i.ln=_v,i.log=bv,i.log10=Sv,i.log2=yv,i.max=vv,i.min=Iv,i.mod=xv,i.mul=Av,i.pow=Ov,i.random=Pv,i.round=Cv,i.sign=wv,i.sin=Ev,i.sinh=Tv,i.sqrt=Rv,i.sub=jv,i.sum=Nv,i.tan=kv,i.tanh=Dv,i.trunc=Fv,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function pv(e,t){return new this(e).div(t)}function fv(e){return new this(e).exp()}function hv(e){return Q(e=new this(e),e.e+1,3)}function gv(){var e,t,n=new this(0);for(re=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return re=!0,new this(1/0);n=t}return re=!0,n.sqrt()}function Mp(e){return e instanceof Et||e&&e.toStringTag===qp||!1}function _v(e){return new this(e).ln()}function bv(e,t){return new this(e).log(t)}function yv(e){return new this(e).log(2)}function Sv(e){return new this(e).log(10)}function vv(){return Hp(this,arguments,-1)}function Iv(){return Hp(this,arguments,1)}function xv(e,t){return new this(e).mod(t)}function Av(e,t){return new this(e).mul(t)}function Ov(e,t){return new this(e).pow(t)}function Pv(e){var t,n,r,i,a=0,o=new this(1),s=[];if(e===void 0?e=this.precision:ut(e,1,fn),r=Math.ceil(e/X),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));a<r;)i=t[a],i>=429e7?t[a]=crypto.getRandomValues(new Uint32Array(1))[0]:s[a++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);a<r;)i=t[a]+(t[a+1]<<8)+(t[a+2]<<16)+((t[a+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,a):(s.push(i%1e7),a+=4);a=r/4}else throw Error(Vp);else for(;a<r;)s[a++]=Math.random()*1e7|0;for(r=s[--a],e%=X,r&&e&&(i=qe(10,X-e),s[a]=(r/i|0)*i);s[a]===0;a--)s.pop();if(a<0)n=0,s=[0];else{for(n=-1;s[0]===0;n-=X)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<X&&(n-=X-r)}return o.e=n,o.d=s,o}function Cv(e){return Q(e=new this(e),e.e+1,this.rounding)}function wv(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function Ev(e){return new this(e).sin()}function Tv(e){return new this(e).sinh()}function Rv(e){return new this(e).sqrt()}function jv(e,t){return new this(e).sub(t)}function Nv(){var e=0,t=arguments,n=new this(t[e]);for(re=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return re=!0,Q(n,this.precision,this.rounding)}function kv(e){return new this(e).tan()}function Dv(e){return new this(e).tanh()}function Fv(e){return Q(e=new this(e),e.e+1,1)}w[Symbol.for("nodejs.util.inspect.custom")]=w.toString;w[Symbol.toStringTag]="Decimal";var Et=w.constructor=Zp(Hs);xa=new Et(xa);Aa=new Et(Aa);var{PAYLOAD_BYTES:Uv}={PAYLOAD_BYTES:20},{KSUID_EPOCH:Mv}={KSUID_EPOCH:14e8},{getRandomBytes:Bv}={getRandomBytes:({size:t})=>{let n=new Uint8Array(t);return globalThis.crypto.getRandomValues(n),n}},{ALPHABET:Lv}={ALPHABET:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},{ENCODED_LENGTH:Vv}={ENCODED_LENGTH:27},{base62Encode:qv}=(e=>({base62Encode:({bytes:n,padTo:r})=>{let i=[],a=new Uint8Array(n),o=!1;for(;!o;){o=!0;let s=0;for(let c=0;c<a.length;c++){let u=s*256+a[c];a[c]=Math.floor(u/62),s=u%62,a[c]!==0&&(o=!1)}i.push(s)}for(i.reverse();i.length<r;)i.unshift(0);return i.map(s=>e[s]).join("")}}))(Lv),{generateKsuid:Yp}=((e,t,n,r,i)=>({generateKsuid:({prefix:o=""}={})=>{let s=new Uint8Array(e),c=Math.floor(Date.now()/1e3)-t;s[0]=c>>>24&255,s[1]=c>>>16&255,s[2]=c>>>8&255,s[3]=c&255;let u=n({size:16});s.set(u,4);let l=r({bytes:s,padTo:i});return`${o}${l}`}}))(Uv,Mv,Bv,qv,Vv);var Jp={randomSync:()=>({string:Yp({})})};import{z as fe}from"zod/v4";var $v=202,Gv=502,Kv=400,Hv=409,Wv=100,Qv=201,Zv=417;var Yv=403,Jv=504,Xv=410,zv=505,e0=418,t0=419,n0=507,r0=500,i0=411,a0=423,o0=420,s0=405,c0=301,u0=302,l0=207,d0=300,m0=511,p0=204,f0=203,h0=406,g0=404,_0=501,b0=304,y0=200,S0=206,v0=402,I0=308,x0=412,A0=428,O0=102,P0=407,C0=431,w0=408,E0=413,T0=414,R0=416,j0=205,N0=303,k0=503,D0=101,F0=307,U0=429,M0=401,B0=422,L0=415,V0=305,Xp={ACCEPTED:$v,BAD_GATEWAY:Gv,BAD_REQUEST:Kv,CONFLICT:Hv,CONTINUE:Wv,CREATED:Qv,EXPECTATION_FAILED:Zv,FORBIDDEN:Yv,GATEWAY_TIMEOUT:Jv,GONE:Xv,HTTP_VERSION_NOT_SUPPORTED:zv,IM_A_TEAPOT:e0,INSUFFICIENT_SPACE_ON_RESOURCE:t0,INSUFFICIENT_STORAGE:n0,INTERNAL_SERVER_ERROR:r0,LENGTH_REQUIRED:i0,LOCKED:a0,METHOD_FAILURE:o0,METHOD_NOT_ALLOWED:s0,MOVED_PERMANENTLY:c0,MOVED_TEMPORARILY:u0,MULTI_STATUS:l0,MULTIPLE_CHOICES:d0,NETWORK_AUTHENTICATION_REQUIRED:m0,NO_CONTENT:p0,NON_AUTHORITATIVE_INFORMATION:f0,NOT_ACCEPTABLE:h0,NOT_FOUND:g0,NOT_IMPLEMENTED:_0,NOT_MODIFIED:b0,OK:y0,PARTIAL_CONTENT:S0,PAYMENT_REQUIRED:v0,PERMANENT_REDIRECT:I0,PRECONDITION_FAILED:x0,PRECONDITION_REQUIRED:A0,PROCESSING:O0,PROXY_AUTHENTICATION_REQUIRED:P0,REQUEST_HEADER_FIELDS_TOO_LARGE:C0,REQUEST_TIMEOUT:w0,REQUEST_TOO_LONG:E0,REQUEST_URI_TOO_LONG:T0,REQUESTED_RANGE_NOT_SATISFIABLE:R0,RESET_CONTENT:j0,SEE_OTHER:N0,SERVICE_UNAVAILABLE:k0,SWITCHING_PROTOCOLS:D0,TEMPORARY_REDIRECT:F0,TOO_MANY_REQUESTS:U0,UNAUTHORIZED:M0,UNPROCESSABLE_ENTITY:B0,UNSUPPORTED_MEDIA_TYPE:L0,USE_PROXY:V0};var zp={202:"Accepted",502:"Bad Gateway",400:"Bad Request",409:"Conflict",100:"Continue",201:"Created",417:"Expectation Failed",424:"Failed Dependency",403:"Forbidden",504:"Gateway Timeout",410:"Gone",505:"HTTP Version Not Supported",418:"I'm a teapot",419:"Insufficient Space on Resource",507:"Insufficient Storage",500:"Internal Server Error",411:"Length Required",423:"Locked",420:"Method Failure",405:"Method Not Allowed",301:"Moved Permanently",302:"Moved Temporarily",207:"Multi-Status",300:"Multiple Choices",511:"Network Authentication Required",204:"No Content",203:"Non Authoritative Information",406:"Not Acceptable",404:"Not Found",501:"Not Implemented",304:"Not Modified",200:"OK",206:"Partial Content",402:"Payment Required",308:"Permanent Redirect",412:"Precondition Failed",428:"Precondition Required",102:"Processing",103:"Early Hints",426:"Upgrade Required",407:"Proxy Authentication Required",431:"Request Header Fields Too Large",408:"Request Timeout",413:"Request Entity Too Large",414:"Request-URI Too Long",416:"Requested Range Not Satisfiable",205:"Reset Content",303:"See Other",503:"Service Unavailable",101:"Switching Protocols",307:"Temporary Redirect",429:"Too Many Requests",401:"Unauthorized",451:"Unavailable For Legal Reasons",422:"Unprocessable Entity",415:"Unsupported Media Type",305:"Use Proxy",421:"Misdirected Request"},ef={Accepted:202,"Bad Gateway":502,"Bad Request":400,Conflict:409,Continue:100,Created:201,"Expectation Failed":417,"Failed Dependency":424,Forbidden:403,"Gateway Timeout":504,Gone:410,"HTTP Version Not Supported":505,"I'm a teapot":418,"Insufficient Space on Resource":419,"Insufficient Storage":507,"Internal Server Error":500,"Length Required":411,Locked:423,"Method Failure":420,"Method Not Allowed":405,"Moved Permanently":301,"Moved Temporarily":302,"Multi-Status":207,"Multiple Choices":300,"Network Authentication Required":511,"No Content":204,"Non Authoritative Information":203,"Not Acceptable":406,"Not Found":404,"Not Implemented":501,"Not Modified":304,OK:200,"Partial Content":206,"Payment Required":402,"Permanent Redirect":308,"Precondition Failed":412,"Precondition Required":428,Processing:102,"Early Hints":103,"Upgrade Required":426,"Proxy Authentication Required":407,"Request Header Fields Too Large":431,"Request Timeout":408,"Request Entity Too Large":413,"Request-URI Too Long":414,"Requested Range Not Satisfiable":416,"Reset Content":205,"See Other":303,"Service Unavailable":503,"Switching Protocols":101,"Temporary Redirect":307,"Too Many Requests":429,Unauthorized:401,"Unavailable For Legal Reasons":451,"Unprocessable Entity":422,"Unsupported Media Type":415,"Use Proxy":305,"Misdirected Request":421};function q0(e){var t=zp[e.toString()];if(!t)throw new Error("Status code does not exist: "+e);return t}function tf(e){var t=ef[e];if(!t)throw new Error("Reason phrase does not exist: "+e);return t}var nf=q0;var hn;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(hn||(hn={}));var Ea=function(){return Ea=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},Ea.apply(this,arguments)},oD=Ea(Ea({},Xp),{getStatusCode:tf,getStatusText:nf});var{generateId:_r}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(Jp),{BILLING_CONTROL_KEYS:Ta}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:$0}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:rf}={entToPrice:({ent:t,prices:n})=>{let r=n.filter(i=>i.entitlement_id===t.id);return r.find(i=>i.internal_product_id===t.internal_product_id)??r[0]}},{nullish:At}={nullish:t=>t==null},{FeatureType:at}=(()=>{var e;return(function(t){t.Boolean="boolean",t.Metered="metered",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{FeatureType:e}})(),{AllowanceType:Ra}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:di}={Infinite:"inf"},{EntInterval:br}=(()=>{var e;return(function(t){t.Lifetime="lifetime",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{EntInterval:e}})(),{BillingInterval:Qt}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{BillingInterval:e}})(),{fixedCurrenciesToApi:G0}={fixedCurrenciesToApi:t=>{if(!t)return;let n=Object.entries(t);if(n.length!==0)return n.map(([r,i])=>({currency:r,amount:i.amount??0}))}},{usageCurrenciesToTiers:K0}={usageCurrenciesToTiers:(t,n)=>{if(!t||n<=0)return;let r=Object.entries(t);if(r.length===0)return;let i=Array.from({length:n},()=>[]);for(let[a,o]of r)(o.usage_tiers??[]).forEach((s,c)=>{c<n&&i[c].push({currency:a,amount:s.amount,...s.flat_amount!==void 0?{flat_amount:s.flat_amount}:{}})});return i}},{TierInfinite:Ys}={TierInfinite:"inf"},{FeatureUsageType:gn}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:yr}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Usage="usage"})(e||(e={})),{PriceType:e}})(),{BillingType:Sr}=(()=>{var e;return(function(t){t.OneOff="one_off",t.FixedCycle="fixed_cycle",t.UsageBelowThreshold="usage_below_threshold",t.UsageInAdvance="usage_in_advance",t.UsageInArrear="usage_in_arrear",t.InArrearProrated="in_arrear_prorated"})(e||(e={})),{BillingType:e}})(),{BillWhen:mi}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:_n}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:Zt}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:vr}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{InternalError:H0}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=500,data:a}){super(n),this.name="InternalError",this.code=r||"internal_error",this.statusCode=i,this.data=a}}return{InternalError:e}})(),{getItemFeatureType:af}=((e,t)=>({getItemFeatureType:({item:r,features:i})=>{let a=i.find(o=>o.id===r.feature_id);if(a)return a.type===e.Boolean?t.Static:a.type===e.CreditSystem?t.SingleUse:a.config?.usage_type}}))(at,Zt),{billingControlsFromColumns:of}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(Ta),{nullish:Ir}={nullish:t=>t==null},{RecaseError:lt}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=400,data:a}){super(n),this.name="RecaseError",this.code=r||"invalid_request",this.statusCode=i,this.data=a}}return{RecaseError:e}})(),{ErrCode:ht}={ErrCode:{PlanAlreadyAttached:"plan_already_attached",PendingPlanConflict:"pending_plan_conflict",IdempotencyKeyAlreadyExists:"idempotency_key_already_exists",IdempotencyKeyNotFound:"idempotency_key_not_found",DuplicateIdempotencyKey:"duplicate_idempotency_key",InvalidApiVersion:"invalid_api_version",NoSecretKey:"no_secret_key",InvalidSecretKey:"invalid_secret_key",NoAuthHeader:"no_auth_header",InvalidAuthHeader:"invalid_auth_header",FailedToVerifySecretKey:"failed_to_verify_secret_key",FailedToFetchKeyFromAutumn:"failed_to_fetch_key_from_autumn",InsufficientScopes:"insufficient_scopes",NoPublishableKey:"no_publishable_key",InvalidPublishableKey:"invalid_publishable_key",GetOrgFromPublishableKeyFailed:"get_org_from_publishable_key_failed",EndpointNotPublic:"endpoint_not_public",FailedToVerifyPublishableKey:"failed_to_verify_publishable_key",InvalidInputs:"invalid_inputs",InvalidRequest:"invalid_request",InvalidExpand:"invalid_expand",InvalidOptions:"invalid_options",InvalidCursor:"invalid_cursor",RequestTemporarilyDisabled:"request_temporarily_disabled",OrgNotFound:"org_not_found",OrgHasCustomers:"org_has_customers",MigrationNotFound:"migration_not_found",FeatureNotFound:"feature_not_found",InvalidFeature:"invalid_feature",DuplicateFeatureId:"duplicate_feature_id",InvalidEventName:"invalid_event_name",FeatureLimitReached:"feature_limit_reached",InternalError:"internal_error",DuplicateCustomerId:"duplicate_customer_id",StripeKeyNotFound:"stripe_key_not_found",DuplicateCustomerEmail:"duplicate_customer_email",StripeError:"stripe_error",StripeKeyInvalid:"stripe_key_invalid",StripeAccountMismatch:"stripe_account_mismatch",StripeConfigNotFound:"stripe_config_not_found",StripeDeleteCustomerFailed:"stripe_delete_customer_failed",StripeCreateCustomerFailed:"stripe_create_customer_failed",StripeCreateProductFailed:"stripe_create_product_failed",StripeCancelSubscriptionFailed:"stripe_cancel_subscription_failed",StripeGetPaymentMethodFailed:"stripe_get_payment_method_failed",StripeCardDeclined:"stripe_card_declined",StripeUpdateSubscriptionFailed:"stripe_update_subscription_failed",StripeCancelSubscriptionScheduleFailed:"stripe_cancel_subscription_schedule_failed",StripeCreateSubscriptionFailed:"stripe_create_subscription_failed",PriceNotFound:"price_not_found",CreatePriceFailed:"create_price_failed",InvalidPrice:"invalid_price",InvalidPriceId:"invalid_price_id",InvalidPriceOptions:"invalid_price_options",InvalidPriceConfig:"invalid_price_config",CusPriceNotFound:"cus_price_not_found",InvalidCustomer:"invalid_customer",CreateCustomerFailed:"create_customer_failed",CustomerNotFound:"customer_not_found",CustomersNotFound:"customers_not_found",CustomerAlreadyHasProduct:"customer_already_has_product",CustomerHasNoPaymentMethod:"customer_has_no_payment_method",CustomerHasNoBaseProduct:"customer_has_no_base_product",AttachProductToCustomerFailed:"attach_product_to_customer_failed",CustomerEntitlementNotFound:"customer_entitlement_not_found",MultipleCustomersFound:"multiple_customers_found",InvalidUpdateCustomerParams:"invalid_update_customer_params",CurrencyMismatch:"currency_mismatch",CreateStripeProductFailed:"create_stripe_product_failed",DeleteStripeProductFailed:"delete_stripe_product_failed",CreateStripeSubscriptionFailed:"create_stripe_subscription_failed",CusProductNotFound:"cus_product_not_found",DuplicateSubscriptionId:"duplicate_subscription_id",InvalidEntitlement:"invalid_entitlement",CreateEntitlementFailed:"create_entitlement_failed",DeleteEntitlementFailed:"delete_entitlement_failed",InsufficientBalance:"insufficient_balance",CreateInvoiceFailed:"create_invoice_failed",InvalidEvent:"invalid_event",CreateEventFailed:"create_event_failed",DuplicateEvent:"duplicate_event",NoActiveCusProducts:"no_active_cus_products",GetCusProductsFailed:"get_cus_products_failed",GetCusPriceFailed:"get_cus_price_failed",PayInvoiceFailed:"invoice_payment_failed",InvalidReward:"invalid_reward",ProductNotInStripe:"product_not_in_stripe",DuplicateRewardId:"duplicate_reward_id",DuplicatePromoCode:"duplicate_promo_code",PromoCodeAlreadyExistsInStripe:"promo_code_already_exists_in_stripe",PromoCodeFirstTimeOnly:"promo_code_first_time_only",EntityNotFound:"entity_not_found",EntityAlreadyDeleted:"entity_already_deleted",ReferralCodeMaxRedemptionsReached:"referral_code_max_redemptions_reached",ReferralNotFound:"referral_not_found",CustomerAlreadyRedeemedReferralCode:"customer_already_redeemed_referral_code",CustomerCannotRedeemOwnCode:"customer_cannot_redeem_own_code",InvalidProductItem:"invalid_product_item",EntityIdRequired:"entity_id_required",LockAlreadyExists:"lock_already_exists",InsertSubscriptionFailed:"insert_subscription_failed",UpdateSubscriptionFailed:"update_subscription_failed",RewardNotFound:"reward_not_found",RewardProgramNotFound:"reward_program_not_found",InsertRewardProgramFailed:"insert_reward_program_failed",InsertReferralCodeFailed:"insert_referral_code_failed",ReferralCodeNotFound:"referral_code_not_found",UpdateRewardRedemptionFailed:"update_reward_redemption_failed",RewardRedemptionNotFound:"reward_redemption_not_found",InsertRewardRedemptionFailed:"insert_reward_redemption_failed",InsertMigrationJobFailed:"insert_migration_job_failed",InsertMigrationErrorFailed:"insert_migration_error_failed",MigrationJobNotFound:"migration_job_not_found",MigrationAlreadyInProgress:"migration_already_in_progress",CustomerExportInProgress:"customer_export_in_progress",SupabaseNotFound:"supabase_not_found",EntityBalanceNotFound:"entity_balance_not_found",TinybirdDisabled:"tinybird_disabled",ClickHouseDisabled:"tinybird_disabled",PaymentMethodNotFound:"payment_method_not_found",VercelSubscriptionAlreadyExists:"vercel_subscription_already_exists",VercelSubscriptionNotFound:"vercel_subscription_not_found",VercelResourceNotFound:"vercel_resource_not_found",ProductNotFound:"product_not_found",NestedVariantNotAllowed:"nested_variant_not_allowed",CannotForkArchivedBase:"cannot_fork_archived_base",ProductIdAlreadyExists:"product_id_already_exists",DuplicateVersionSlug:"duplicate_version_slug",CannotPreviewOnVariant:"cannot_preview_on_variant",InvalidPropagationTarget:"invalid_propagation_target",ConflictingVariantAnchor:"conflicting_variant_anchor",VariantCrossPlanAnchor:"variant_cross_plan_anchor",TooManyVariants:"too_many_variants",ConflictingVersionFlags:"conflicting_version_flags",VariantCannotBeDefault:"variant_cannot_be_default",HistoricalPlanVersionCannotBeDefault:"historical_plan_version_cannot_be_default",UnderMaintenance:"under_maintenance"}},{validateFeatureId:W0}=((e,t)=>({validateFeatureId:r=>{if(!r.match(/^[a-zA-Z0-9_-]+$/))throw new e({message:"Feature ID can only contain alphanumeric characters, underscores, and hyphens",code:t.InvalidFeature,statusCode:400})}}))(lt,ht),{notNullish:xr}=(e=>({notNullish:n=>!e(n)}))(Ir),{keyToTitle:sf}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:Q0}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:Z0}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ApiFeatureType:Y0}=(()=>{var e;return(function(t){t.Static="static",t.Boolean="boolean",t.SingleUsage="single_use",t.ContinuousUse="continuous_use",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{ApiFeatureType:e}})(),{ProductItemInterval:Js}=(()=>{var e;return(function(t){t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{ProductItemInterval:e}})(),{COMMON:cf}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:J0}={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:X0}=(e=>({COMMON_SET:new Set(e)}))(cf),{hasNoDuplicateCurrencies:uf}={hasNoDuplicateCurrencies:t=>{let n=new Set;for(let{currency:r}of t){let i=r.toLowerCase();if(n.has(i))return!1;n.add(i)}return!0}},{DUPLICATE_CURRENCY_MESSAGE:lf}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{TierBehavior:ja}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:Ar}=(()=>{var e;return(function(t){t.BillImmediately="bill_immediately",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.BillNextCycle="bill_next_cycle"})(e||(e={})),{OnIncrease:e}})(),{OnDecrease:pi}=(()=>{var e;return(function(t){t.Prorate="prorate",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.None="none",t.NoProrations="no_prorations"})(e||(e={})),{OnDecrease:e}})(),{RolloverExpiryDurationType:Xs}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:z0}=(()=>{var e;return(function(t){t.Day="day",t.Week="week",t.Month="month",t.Year="year"})(e||(e={})),{EntitlementDuration:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:eI}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:tI}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:df}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(fe),{flatCreditRateShape:mf}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(fe),{CreditTierSchema:nI}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(fe),{CreditMultiplierSchema:rI}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(fe,df),{MarkupEntrySchema:pf}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(fe),{ModelMarkupsSchema:iI}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(fe,pf),{isFeaturePriceItem:zs}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(xr),{notNullish:Bn}={notNullish:t=>t!=null},{isAiCreditSystem:ec}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(at),{VIOLATION_MESSAGES:aI}={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."}},{sameSpecificity:oI}={sameSpecificity:(t,n)=>Object.keys(t.match).length===Object.keys(n.match).length&&(t.priority??null)===(n.priority??null)},{matchesCanCoexist:ff}={matchesCanCoexist:(t,n)=>Object.entries(t).every(([r,i])=>{let a=Object.entries(n).find(([o])=>o===r)?.[1];return a===void 0||a===i})},{formatCreditMatch:sI}={formatCreditMatch:t=>Object.entries(t).map(([n,r])=>`${n}=${r}`).join(", ")},{validateMultiplierShape:cI}={validateMultiplierShape:({name:t,multiplier:n,invalidCreditSystem:r})=>{let i=n.factor!==void 0,a=n.add!==void 0;!i&&!a&&r(`Multiplier "${t}" needs a factor or an add.`);let o=Number(n.factor);i&&!(Number.isFinite(o)&&o>0)&&r(`Multiplier "${t}" factor must be greater than zero.`);let s=Number(n.add);a&&!Number.isFinite(s)&&r(`Multiplier "${t}" add must be a number.`),i&&(n.factor=o),a&&(n.add=s)}},{minimumCreditRateAmount:uI}={minimumCreditRateAmount:t=>t.tier_behavior!=="graduated"?t.credit_amount??0:(t.tiers??[]).reduce((n,r)=>Math.min(n,r.credit_amount),Number.POSITIVE_INFINITY)},{worstCaseRate:lI}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((a,o)=>{let s=[];for(let u of r){let l=u.factor!==void 0&&u.factor<1||u.add!==void 0&&u.add<0,d=s.every(p=>e(p.match,u.match));(l||u===o)&&e(o.match,u.match)&&d&&s.push(u)}let c=s.reduce((u,l)=>u.mul(l.factor!==void 0&&l.factor<1?l.factor:1).add(l.add!==void 0&&l.add<0?l.add:0),new t(i));return t.min(a,c)},new t(i))}))(ff,Et),{validateCreditSystemSchemaReferences:dI}=((e,t,n,r)=>({validateCreditSystemSchemaReferences:({config:a,allFeatures:o,selfFeatureId:s})=>{let c=Array.isArray(a?.schema)?a.schema:[];if(c.length!==0)for(let u of c){let l=u.metered_feature_id;if(!l||l===s)continue;let d=o.find(p=>p.id===l);if(d){if(d.type===e.CreditSystem)throw new t({message:`Credit system schema cannot reference another credit system (${l}). Only metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Boolean)throw new t({message:`Credit system schema cannot reference boolean feature ${l}. Only consumable (single-use) metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Metered&&d.config?.usage_type===r.Continuous)throw new t({message:`Credit system schema cannot reference continuous feature ${l}. Only consumable (single-use) metered features are allowed.`,code:n.InvalidFeature,statusCode:400})}}}}))(at,lt,ht,gn),{isPriceItem:tc}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(xr,Ir),{isFeatureItem:Na}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(xr,Ir),{itemToBillingInterval:bn}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(At,Qt),{rolloverConfigToIssue:mI}={rolloverConfigToIssue:({rollover:t})=>t==null?null:t.max!=null&&t.max_percentage!=null?"Rollover max and max_percentage are mutually exclusive. Set one or the other, not both.":t.max_percentage!=null?t.max_percentage<=0||t.max_percentage>100?"Rollover max_percentage must be between 0 (exclusive) and 100 (inclusive)":null:t.max!=null&&t.max<=0?"Rollover maximum amount must be greater than 0":null},{itemToEntInterval:ka}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(At,br,Zt),{itemToEntIntervalCount:Da}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:Or}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:Fa}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(Bn,At),{toKey:hf}={toKey:t=>t.toLowerCase()},{priceOwnedStripePriceId:pI}=(e=>({priceOwnedStripePriceId:({price:n})=>{let r=n.config,i=r.stripe_prepaid_price_v2_id||r.stripe_price_id;return e(i)?null:i}}))(At),{UsageTierSchema:nc}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).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"]}).transform(r=>({...r,amount:r.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(fe,di),{IgnoredFixedPriceMetadataSchema:fI}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(fe),{hasCatalogCurrencies:hI}={hasCatalogCurrencies:t=>Object.keys(t??{}).length>0},{usageTiersToComparisonShape:gI}={usageTiersToComparisonShape:t=>t.map((n,r)=>({amount:n.amount,flat_amount:n.flat_amount??0,to:r===t.length-1?null:n.to}))},{normalizedAllocatedBillingBehavior:_I}=(e=>({normalizedAllocatedBillingBehavior:n=>n.allocated_billing_behavior??(n.should_prorate?e.Prorated:e.Arrear)}))(_n),{getResetUsage:gf}=((e,t,n,r)=>({getResetUsage:({item:a,feature:o})=>{if(a.feature_id)return e(a.reset_usage_when_enabled)&&(t(a)||n(a))&&o?o?.config?.usage_type===r.Single:a.reset_usage_when_enabled}}))(Ir,Na,zs,gn),{hasUnlimitedAllowanceType:bI}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(Ra),{normalizedEntitlementInterval:_f}=(e=>({normalizedEntitlementInterval:n=>n.interval??e.Lifetime}))(br),{normalizedEntitlementIntervalCount:yI}=((e,t)=>({normalizedEntitlementIntervalCount:r=>e(r)===t.Lifetime?1:r.interval_count??1}))(_f,br),{normalizeOptionalId:SI}={normalizeOptionalId:t=>t||null},{rolloversAreSame:vI}=(e=>({rolloversAreSame:({rollover1:n,rollover2:r})=>!n&&!r?!0:!n&&r||n&&!r?!1:n?.max==r?.max&&n?.max_percentage==r?.max_percentage&&(n?.duration??e.Month)===(r?.duration??e.Month)&&n?.length==r?.length}))(Xs),{deterministicStringify:rc}=(()=>{let e=t=>{if(t==null)return"null";if(typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(e).join(",")}]`;let n=t;return typeof n.toJSON=="function"?e(n.toJSON()):`{${Object.keys(n).filter(i=>n[i]!==void 0).sort().map(i=>`${JSON.stringify(i)}:${e(n[i])}`).join(",")}}`};return{deterministicStringify:e}})(),{MARKUP_FIELDS:II}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:xI}={expiriesAreSame:(t,n)=>(t.expiry_duration??null)===(n.expiry_duration??null)&&(t.expiry_length??null)==(n.expiry_length??null)},{itemToFeature:bf}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{isFeaturePriceItem:Pr}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(Bn),{ProductErrorCode:AI}={ProductErrorCode:{ProductNotFound:"product_not_found",ProductAlreadyExists:"product_already_exists",InvalidProductItem:"invalid_product_item"}},{buildUsagePriceCurrencies:OI}=(e=>({buildUsagePriceCurrencies:({baseTiers:n,itemTiers:r,flatCurrencies:i})=>{if(r?.length){let a=[...new Set(r.flatMap(s=>(s.additional_currencies??[]).map(c=>e(c.currency))))];if(a.length===0)return;let o={};for(let s of a)o[s]={usage_tiers:n.map((c,u)=>{let l=(r[u]?.additional_currencies??[]).find(d=>e(d.currency)===s);return{to:c.to,amount:l?.amount??0,...l?.flat_amount!==void 0?{flat_amount:l.flat_amount}:{}}})};return o}if(i?.length&&n.length>0){let a={};for(let{currency:o,amount:s}of i)a[e(o)]={usage_tiers:[{to:n[0].to,amount:s}]};return a}}}))(hf),{itemToFeature:PI}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{shouldProrate:CI}=((e,t)=>({shouldProrate:r=>r?r===e.ProrateNextCycle||r===e.ProrateImmediately||r===t.ProrateImmediately||r===t.ProrateNextCycle:!0}))(Ar,pi),{getBillingType:wI}=((e,t,n,r)=>({getBillingType:a=>{if(a.type===e.Fixed&&a.interval===t.OneOff)return n.OneOff;if(a.type===e.Fixed)return n.FixedCycle;let o=a;return o.bill_when===r.InAdvance||o.bill_when===r.StartOfPeriod?n.UsageInAdvance:o.bill_when===r.EndOfPeriod&&o.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(yr,Qt,Sr,mi),{stripeResourceFields:EI}={stripeResourceFields:["stripe_product_id","stripe_price_id","stripe_empty_price_id","stripe_placeholder_price_id","stripe_prepaid_price_v2_id","stripe_meter_id","stripe_event_name"]},{PREVIEW_STRIPE_PRICE_ID_PREFIX:TI}={PREVIEW_STRIPE_PRICE_ID_PREFIX:"price_PREVIEW_"},{PREVIEW_STRIPE_PRODUCT_ID_PREFIX:RI}={PREVIEW_STRIPE_PRODUCT_ID_PREFIX:"prod_PREVIEW_"},{normalizeOptionalId:jI}={normalizeOptionalId:t=>t||null},{stripeProductOnlyFields:NI}={stripeProductOnlyFields:["stripe_product_id","stripe_meter_id"]},{copyField:kI}=(e=>({copyField:({fromConfig:n,toConfig:r,field:i})=>!e(r[i])||e(n[i])?!1:(r[i]=n[i],!0)}))(At),{stripeResourceFields:DI}={stripeResourceFields:["stripe_product_id","stripe_price_id","stripe_empty_price_id","stripe_placeholder_price_id","stripe_prepaid_price_v2_id","stripe_meter_id","stripe_event_name"]},{handleCustomProductItems:FI}={handleCustomProductItems:({newPrices:t,newEnts:n,updatedPrices:r,updatedEnts:i,samePrices:a,sameEnts:o,features:s})=>({prices:[...t,...r,...a],entitlements:[...n,...i,...o].map(c=>({...c,feature:s.find(u=>u.id===c.feature_id)})),customPrices:[...t,...r],customEnts:[...n,...i],features:s})},{validateLicenseBillingMode:UI}=((e,t)=>({validateLicenseBillingMode:({prepaidOnly:r})=>{if(r===!1)throw new e({message:"License overflow billing (prepaid_only: false) is not yet available. Set prepaid_only to true.",code:t.InvalidRequest,statusCode:400})}}))(lt,ht),{PlanItemMatchPrecision:MI}=(()=>{var e;return(function(t){t.FeatureBillingMethodCadence="feature_billing_method_cadence",t.FeatureCadence="feature_cadence"})(e||(e={})),{PlanItemMatchPrecision:e}})(),{catalogPlanItemIdentity:BI}={catalogPlanItemIdentity:{responseField:"mapping_identity",components:[{paths:["feature_id"],default:""},{paths:["price.billing_method"],default:""},{paths:["price.interval","reset.interval"],default:""},{paths:["price.interval_count","reset.interval_count"],default:"",defaultWhen:{component:2,value:1}}]}},{applyPrice:LI}={applyPrice:(t,n)=>n===void 0?t:n===null?null:{...n}},{planItemMatchesFilter:VI}={planItemMatchesFilter:({item:t,filter:n})=>{if(n.feature_id!==void 0&&t.feature_id!==n.feature_id||n.billing_method!==void 0&&t.price?.billing_method!==n.billing_method)return!1;if(n.interval!==void 0){let r=t.price?.interval??t.reset?.interval;if(String(r)!==String(n.interval))return!1}return!(n.interval_count!==void 0&&(t.price?.interval_count??t.reset?.interval_count??1)!==n.interval_count||n.included!==void 0&&(t.unlimited===!0||(t.included??0)!==n.included))}},{isFreeNonResetEntitlement:qI}={isFreeNonResetEntitlement:t=>t.price==null&&t.reset==null},{toApiPlanItemPrice:$I}={toApiPlanItemPrice:t=>t?{...t,billing_units:t.billing_units??1,max_purchase:t.max_purchase??null}:null},{toApiPlanItemRollover:GI}={toApiPlanItemRollover:t=>{if(t)return{...t,max:t.max??null}}},{applyFreeTrial:KI}={applyFreeTrial:(t,n)=>{if(n===void 0)return t;if(n!==null)return{...n}}},{applyLicenseUpsert:HI}={applyLicenseUpsert:({existing:t,upsert:n})=>{let r=n.customize===null?void 0:n.customize??t?.customize;return{license_plan_id:n.license_plan_id,version:t?.version??1,included:n.included??t?.included??0,prepaid_only:n.prepaid_only??t?.prepaid_only??!1,...r!==void 0?{customize:r}:{},...t?.plan!==void 0?{plan:t.plan}:{}}}},{PlanItemFilterPrecision:yf}=(()=>{var e;return(function(t){t.Identity="identity",t.IdentityAndIncluded="identity_and_included"})(e||(e={})),{PlanItemFilterPrecision:e}})(),{additionalCurrenciesCompatible:ic}={additionalCurrenciesCompatible:(t,n)=>(t??[]).every(r=>{let i=(n??[]).find(a=>a.currency.toLowerCase()===r.currency.toLowerCase());return!i||(r.amount??null)===(i.amount??null)&&(r.flat_amount??null)===(i.flat_amount??null)})},{toBasePriceParams:WI}={toBasePriceParams:(t,{includeInternalIds:n=!1}={})=>({amount:t.amount,interval:t.interval,...t.interval_count!==void 0?{interval_count:t.interval_count}:{},...t.additional_currencies?.length?{additional_currencies:t.additional_currencies}:{},...n&&t.entitlement_id!==void 0?{entitlement_id:t.entitlement_id}:{},...n&&t.price_id!==void 0?{price_id:t.price_id}:{},...n&&"stripe_price_id"in t&&t.stripe_price_id!==void 0?{stripe_price_id:t.stripe_price_id}:{}})},{tiersEqual:QI}=(e=>({tiersEqual:(n,r)=>!n?.length&&!r?.length?!0:!n||!r||n.length!==r.length?!1:n.every((i,a)=>{let o=r[a];return i.to===o.to&&(i.amount??0)===(o.amount??0)&&(i.flat_amount??null)===(o.flat_amount??null)&&e(i.additional_currencies,o.additional_currencies)})}))(ic),{rolloversEqual:ZI}={rolloversEqual:(t,n)=>t==null&&n==null?!0:t==null||n==null?!1:t.expiry_duration_type===n.expiry_duration_type&&(t.expiry_duration_length??null)===(n.expiry_duration_length??null)&&(t.max??null)===(n.max??null)&&(t.max_percentage??null)===(n.max_percentage??null)},{prorationsEqual:YI}={prorationsEqual:(t,n)=>t==null&&n==null?!0:t==null||n==null?!1:(t.on_increase??null)===(n.on_increase??null)&&(t.on_decrease??null)===(n.on_decrease??null)},{creditSchemaFingerprint:JI}=(e=>({creditSchemaFingerprint:n=>e(Object.fromEntries((n??[]).map(r=>[r.metered_feature_id,{...r,billing_units:r.billing_units??1}])))}))(rc),{toCreatePlanItemParams:XI}={toCreatePlanItemParams:(t,{includeInternalIds:n=!1}={})=>{let r={feature_id:t.feature_id};return t.entity_feature_id!==void 0&&(r.entity_feature_id=t.entity_feature_id),t.pooled&&(r.pooled=t.pooled),n&&t.entitlement_id!==void 0&&(r.entitlement_id=t.entitlement_id),n&&t.price_id!==void 0&&(r.price_id=t.price_id),t.included!==void 0&&t.included!==null&&(r.included=t.included),t.unlimited!==void 0&&t.unlimited!==null&&(r.unlimited=t.unlimited),t.reset&&(r.reset=t.reset),t.price&&(r.price=t.price),t.rollover&&(r.rollover={expiry_duration_type:t.rollover.expiry_duration_type,...t.rollover.max!=null?{max:t.rollover.max}:{},...t.rollover.max_percentage!=null?{max_percentage:t.rollover.max_percentage}:{},...t.rollover.expiry_duration_length!==void 0?{expiry_duration_length:t.rollover.expiry_duration_length}:{}}),t.proration?.on_increase&&t.proration.on_decrease&&(r.proration={on_increase:t.proration.on_increase,on_decrease:t.proration.on_decrease}),t.feature_override&&(r.feature_override=t.feature_override),r}},{buildRemoveFilter:zI}=(e=>({buildRemoveFilter:({item:n,filterPrecision:r})=>{let i={feature_id:n.feature_id};n.price?.billing_method!==void 0&&(i.billing_method=n.price.billing_method);let a=n.price?.interval??n.reset?.interval;a!==void 0&&(i.interval=a);let o=n.price?.interval_count??n.reset?.interval_count;return a!==void 0&&(i.interval_count=o??1),r===e.IdentityAndIncluded&&typeof n.included=="number"&&n.unlimited!==!0&&(n.reset!=null||n.price!=null)&&(i.included=n.included),i}}))(yf),{FreeTrialDuration:ex}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{arraysEqual:tx}={arraysEqual:({left:t,right:n,equals:r})=>{if(!t?.length&&!n?.length)return!0;if(!t||!n||t.length!==n.length)return!1;let i=[...n];return t.every(a=>{let o=i.findIndex(s=>r(a,s));return o===-1?!1:(i.splice(o,1),!0)})}},{normalizeIntervalCount:nx}={normalizeIntervalCount:({interval:t,intervalCount:n})=>t?n??1:n??""},{hasLicenseCustomize:Sf}={hasLicenseCustomize:t=>t!=null&&(t.price!==void 0||t.add_items!==void 0||t.remove_items!==void 0)},{byLicensePlanId:rx}={byLicensePlanId:(t,n)=>t.license_plan_id.localeCompare(n.license_plan_id)},{variantSettingKeys:ix}={variantSettingKeys:["name","description","group","add_on","config","billing_controls","metadata"]},{valuesEqual:ax}={valuesEqual:(t,n)=>JSON.stringify(t)===JSON.stringify(n)},{omitVariantOwnedSettings:fD}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:ox}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(At),{isPriceItem:Ua}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(Bn,At),{isDefaultTrialV2:hD}=(e=>({isDefaultTrialV2:({freeTrial:n,items:r,isDefault:i})=>n?n.card_required===!1&&i&&!e({items:r}):!1}))(ox),{variantSettingsFields:sx}={variantSettingsFields:["description","group","is_add_on","is_default","config","billing_controls","metadata"]},{sortDeep:vf}=(()=>{let e=t=>Array.isArray(t)?t.map(e):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(n=>[n,e(t[n])])):t;return{sortDeep:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:cx}={IGNORE_PAST_DUE_DESCRIPTION:"If true, entitlements attached to this plan will still reset on schedule even when the customer's product is in a past_due state."},{propagatedSettingFields:ux}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:lx}={licenseParentTargetKey:({planId:t,version:n})=>`${t}@${n}`},{STRIPE_ZERO_DECIMAL_CURRENCIES:If}={STRIPE_ZERO_DECIMAL_CURRENCIES:new Set(["bif","clp","djf","gnf","jpy","kmf","krw","mga","pyg","rwf","ugx","vnd","vuv","xaf","xof","xpf"])},{STRIPE_THREE_DECIMAL_CURRENCIES:dx}={STRIPE_THREE_DECIMAL_CURRENCIES:new Set(["bhd","jod","kwd","omr","tnd"])},{currencyInputDecimals:xf}=(e=>({currencyInputDecimals:n=>e.has((n??"usd").toLowerCase())?0:2}))(If),{entIntervalToValue:mx}=((e,t)=>({entIntervalToValue:(r,i)=>{if(!r)return new e(1e7);let o={[t.Minute]:1,[t.Hour]:60,[t.Day]:1440,[t.Week]:1440*7,[t.Month]:1440*30,[t.Quarter]:1440*90,[t.SemiAnnual]:1440*180,[t.Year]:1440*365,[t.Lifetime]:1e9}[r];return new e(o).mul(i??1)}}))(Et,br),{intervalToValue:px}=(e=>({intervalToValue:(n,r)=>({[e.OneOff]:0,[e.Week]:.25,[e.Month]:1,[e.Quarter]:3,[e.SemiAnnual]:6,[e.Year]:12})[n]*(r??1)}))(Qt),{normalizeIncludedUsage:Af}={normalizeIncludedUsage:t=>t??0},{rolloversAreSame:Of}={rolloversAreSame:({rollover1:t,rollover2:n})=>t&&!n||!t&&n?!1:(t?.max??null)===(n?.max??null)&&(t?.max_percentage??null)===(n?.max_percentage??null)&&t?.duration===n?.duration&&t?.length===n?.length},{prorationConfigsAreSame:fx}=((e,t)=>({prorationConfigsAreSame:({config1:r,config2:i})=>(r?.on_increase??e.ProrateImmediately)===(i?.on_increase??e.ProrateImmediately)&&(r?.on_decrease??t.Prorate)===(i?.on_decrease??t.Prorate)}))(Ar,pi),{itemToExplicitAllocatedBillingBehavior:hx}=((e,t)=>({itemToExplicitAllocatedBillingBehavior:r=>e(r.config?.allocated_billing_behavior)?r.config.allocated_billing_behavior:(e(r.config?.on_increase)||e(r.config?.on_decrease),t.Prorated)}))(Bn,_n),{additionalCurrenciesAreSame:ac}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let a=(c,u)=>c.currency.localeCompare(u.currency),o=[...r].sort(a),s=[...i].sort(a);return o.every((c,u)=>c.currency===s[u].currency&&(c.amount??null)===(s[u].amount??null)&&(c.flat_amount??null)===(s[u].flat_amount??null))}},{itemPricingTiers:gx}={itemPricingTiers:t=>t.tiers?.length?t.tiers:t.price!=null?[{amount:t.price,to:"inf"}]:null},{priceItemsAreSame:_x}=((e,t,n)=>({priceItemsAreSame:({item1:i,item2:a,logDifferences:o=!1})=>{let s=i.price===a.price&&e({item:i})==e({item:a})&&t({item:i})==t({item:a})&&n(i.additional_currencies,a.additional_currencies);return!s&&o&&console.log(`Price items different: ${i.price}`),s}}))(bn,Or,ac),{calculateProrationAmount:bx}=(e=>({calculateProrationAmount:({periodEnd:n,periodStart:r,now:i,amount:a,allowNegative:o=!1})=>{let s=new e(n).minus(i),c=new e(n).minus(r),u=s.div(c).mul(a);return u.lte(0)&&!o?0:u.toNumber()}}))(Et),{getResetUsage:yx}=((e,t,n,r)=>({getResetUsage:({item:a,feature:o})=>{if(a.feature_id)return e(a.reset_usage_when_enabled)&&(t(a)||n(a))&&o?o?.config?.usage_type===r.Single:a.reset_usage_when_enabled}}))(At,Fa,Pr,gn),{compareDetails:Sx}={compareDetails:({newProductV2:t,curProductV2:n})=>{let r={is_add_on:{condition:t?.is_add_on===n?.is_add_on,message:`Is add-on different: ${t?.is_add_on} !== ${n?.is_add_on}`},is_default:{condition:t?.is_default===n?.is_default,message:`Is default different: ${t?.is_default} !== ${n?.is_default}`},archived:{condition:t?.archived===n?.archived,message:`Archived different: ${t?.archived} !== ${n?.archived}`},group:{condition:t?.group==n?.group,message:`Group different: ${t?.group} !== ${n?.group}`},name:{condition:t?.name==n?.name,message:`Name different: ${t?.name} !== ${n?.name}`},id:{condition:t?.id===n?.id,message:`ID different: ${t?.id} !== ${n?.id}`}};return Object.values(r).every(a=>a.condition)}},{compareConfig:vx}={compareConfig:({newConfig:t,curConfig:n})=>{let r={ignore_past_due:{condition:!!t?.ignore_past_due==!!n?.ignore_past_due,message:`Ignore past due different: ${t?.ignore_past_due} !== ${n?.ignore_past_due}`}};return Object.values(r).every(a=>a.condition)}},{normalizeBillingControlsForCompare:Ix}=(e=>({normalizeBillingControlsForCompare:n=>{if(!n)return;let r=n.spend_limits?.map(a=>{if(a.skip_overage_billing===!0)return a;let{skip_overage_billing:o,...s}=a;return s}),i=Object.fromEntries(e.flatMap(a=>{let o=a==="spend_limits"?r:n[a];return o==null||o.length===0?[]:[[a,o]]}));return Object.keys(i).length>0?i:void 0}}))(Ta),{sortControls:xx}={sortControls:t=>[...t].sort((n,r)=>{let i=(n.feature_id??"").localeCompare(r.feature_id??"");return i!==0?i:JSON.stringify(n).localeCompare(JSON.stringify(r))})},{compareMetadata:Ax}={compareMetadata:({newMetadata:t,curMetadata:n})=>{let r=i=>JSON.stringify(i??{},(a,o)=>o&&typeof o=="object"&&!Array.isArray(o)?Object.keys(o).sort().reduce((s,c)=>(s[c]=o[c],s),{}):o);return r(t)===r(n)}},{freeTrialsAreSame:Ox}={freeTrialsAreSame:({ft1:t,ft2:n})=>{if(!t&&!n)return!0;if(!t||!n)return!1;let r={length:{condition:t.length!==n.length,message:`Length different: ${t.length} !== ${n.length}`},unique_fingerprint:{condition:t.unique_fingerprint!==n.unique_fingerprint,message:`Unique fingerprint different: ${t.unique_fingerprint} !== ${n.unique_fingerprint}`},duration:{condition:t.duration!==n.duration,message:`Duration different: ${t.duration} !== ${n.duration}`},card_required:{condition:t.card_required!==n.card_required,message:`Card required different: ${t.card_required} !== ${n.card_required}`},on_end:{condition:(t.on_end??"bill")!==(n.on_end??"bill"),message:`On end different: ${t.on_end??"bill"} !== ${n.on_end??"bill"}`}};return!Object.values(r).some(a=>a.condition)}},{prodOptionsAreSame:Px}={prodOptionsAreSame:({curProduct:t,newProduct:n})=>t.is_default===n.is_default&&t.is_add_on===n.is_add_on},{PurchaseLimitIntervalEnum:Cx}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(fe,$0),{entToItemInterval:Pf}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))(br),{billingToItemInterval:Cf}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(Qt),{isContUseFeature:wf}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(gn),{getBillingType:oc}=((e,t,n,r)=>({getBillingType:a=>{if(a.type===e.Fixed&&a.interval===t.OneOff)return n.OneOff;if(a.type===e.Fixed)return n.FixedCycle;let o=a;return o.bill_when===r.InAdvance||o.bill_when===r.StartOfPeriod?n.UsageInAdvance:o.bill_when===r.EndOfPeriod&&o.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(yr,Qt,Sr,mi),{isAllocatedPrice:Ef}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(oc,Sr),{priceToEnt:sc}=(e=>{function t({price:n,entitlements:r,errorOnNotFound:i}){let a=r.filter(s=>s.id===n.entitlement_id),o=a.find(s=>s.internal_product_id===n.internal_product_id)??a[0];if(!o&&i)throw new e({message:`Entitlement not found for price ${n.id}`});return o}return{priceToEnt:t}})(H0),{isBooleanFeatureItem:Tf}=((e,t)=>({isBooleanFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)&&t(r.interval)&&t(r.included_usage)}))(xr,Ir),{constructBooleanFeature:wx}=((e,t,n)=>({constructBooleanFeature:({featureId:i,orgId:a,env:o,name:s})=>({internal_id:e("fe"),org_id:a,env:o,created_at:Date.now(),id:i,name:s||t(i),type:n.Boolean,config:null,archived:!1,event_names:[],model_markups:null})}))(_r,sf,at),{constructMeteredFeature:Ex}=((e,t,n,r)=>({constructMeteredFeature:({featureId:a,name:o,orgId:s,env:c,usageType:u,eventNames:l=[]})=>({internal_id:e("fe"),org_id:s,env:c,created_at:Date.now(),id:a,name:o||t(a),type:n.Metered,config:{filters:[{property:"event_name",operator:"eq",value:[]}],aggregate:{type:r.Sum,property:"value"},usage_type:u},archived:!1,event_names:l,model_markups:null})}))(_r,sf,at,Q0),{ApiFeatureV0Schema:Tx}=((e,t)=>({ApiFeatureV0Schema:e.object({id:e.string().meta({description:"The ID of the feature, used to refer to it in other API calls like /track or /check."}),name:e.string().nullish().meta({description:"The name of the feature."}),type:e.enum(t).meta({description:"The type of the feature"}),display:e.object({singular:e.string().meta({description:"The singular display name for the feature."}),plural:e.string().meta({description:"The plural display name for the feature."})}).nullish().meta({description:"Singular and plural display names for the feature."}),credit_schema:e.array(e.object({metered_feature_id:e.string().meta({description:"The ID of the metered feature (should be a single_use feature)."}),credit_cost:e.number().meta({description:"The credit cost of the metered feature."})})).nullish().meta({description:"Credit cost schema for credit system features."}),archived:e.boolean().nullish().meta({description:"Whether or not the feature is archived."})})}))(fe,Y0),{CURRENCY_CODES:Rx}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(cf,J0,X0),{RolloverConfigSchema:jx}=((e,t)=>({RolloverConfigSchema:e.object({max:e.number().nullable().optional(),max_percentage:e.number().nullable().optional(),duration:e.enum(t).default(t.Month),length:e.number()})}))(fe,Xs),{EntitlementExpirySchema:Nx}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(fe,z0),{CreditDimensionNameSchema:kx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(fe,eI,tI),{CreditDimensionBaseSchema:Dx}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(fe,df),{graduatedCreditRateShape:Rf}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(fe,nI),{ProviderMarkupsSchema:Fx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(fe,pf),{isAnyCreditSystem:Ux}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(at,ec),{findCreditTierViolations:Mx}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(aI),{findAmbiguousCreditDimensions:Bx}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),a=[];for(let[o,[s,c]]of i.entries())for(let[u,l]of i.slice(o+1))e(c,l)&&t(c.match,l.match)&&a.push({names:[s,u],example:{...c.match,...l.match}});return a}}))(oI,ff),{validateMultipliersKeepRatesNonNegative:Lx}=((e,t)=>({validateMultipliersKeepRatesNonNegative:({schemaItem:r,invalidCreditSystem:i})=>{let a=Object.values(r.multipliers??{}),o=[r,...Object.values(r.dimensions??{})],s=Math.min(...o.map(e));t({multipliers:a,cheapestRate:s}).lt(0)&&i(`Multipliers on ${r.metered_feature_id} can take a rate below zero.`)}}))(uI,lI),{buildFixedPriceCurrencies:Vx}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:a}of n)r[e(i)]={amount:a};return r}}))(hf),{PriceCurrencyConfigSchema:jf}=((e,t)=>({PriceCurrencyConfigSchema:e.object({amount:e.number().nullish(),usage_tiers:e.array(t).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish()})}))(fe,nc),{baseCurrenciesAreCompatible:qx}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:a})=>(n??null)===(r??null)||e(i)!==e(a)}))(hI),{tiersAreSame:Nf}=(e=>({tiersAreSame:(n,r)=>{if(n.length!==r.length)return!1;let i=e(n),a=e(r);return i.every((o,s)=>{let c=a[s];return o.amount===c?.amount&&o.flat_amount===c.flat_amount&&o.to===c.to})}}))(gI),{UsagePriceConfigSchema:$x}=((e,t,n,r,i,a)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(a).optional()})}))(fe,mi,nc,Qt,jf,_n),{toFeature:Gx}=((e,t,n,r,i,a,o)=>({toFeature:({item:c,orgId:u,internalFeatureId:l,internalProductId:d,isCustom:p,newVersion:g,feature:m,curEnt:h})=>{let y=m?.type===e.Boolean,x=t({item:c,feature:m}),v={id:c.entitlement_id||h?.id||n("ent"),org_id:u,created_at:c.created_at||Date.now(),is_custom:p,internal_product_id:d||null,internal_feature_id:l,feature_id:c.feature_id,allowance:c.included_usage===r?null:c.included_usage,allowance_type:y?null:c.included_usage===r?i.Unlimited:i.Fixed,interval:y?null:a({item:c}),interval_count:o({item:c}),carry_from_previous:!x,entity_feature_id:c.entity_feature_id,pooled:c.pooled??!1,usage_limit:null,rollover:c.config?.rollover,expiry_duration:c.config?.expiry?.duration,expiry_length:c.config?.expiry?.length,feature_override:c.config?.feature_override};return(p||g)&&(v={...v,id:n("ent"),created_at:Date.now()}),{price:null,ent:v}}}))(at,gf,_r,di,Ra,ka,Da),{creditDimensionRulesEqual:Kx}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(rc),{markupRecordsAreSame:Hx}=(e=>({markupRecordsAreSame:(n,r)=>[...new Set([...Object.keys(n??{}),...Object.keys(r??{})])].every(i=>e.every(a=>(n?.[i]?.[a]??null)===(r?.[i]?.[a]??null)))}))(II),{itemToUsageType:Wx}=((e,t,n)=>({itemToUsageType:({item:i,features:a})=>{let o=e({item:i,features:a});return!o||!o.config?null:o.type===t.Boolean?n.Static:o.type===t.CreditSystem?n.SingleUse:o.config.usage_type}}))(bf,at,Zt),{itemToUsageType:Qx}=((e,t,n)=>({itemToUsageType:({item:i,features:a})=>{let o=e({item:i,features:a});return o?o.type==t.Boolean?n.Static:o.type==t.CreditSystem?n.SingleUse:o.config.usage_type:null}}))(PI,at,Zt),{isPreviewStripeId:Zx}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(TI,RI),{findPairedEntitlement:Yx}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(sc),{isConsumablePrice:Jx}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(oc,Sr),{validateLicenseLink:gD}=((e,t,n)=>({validateLicenseLink:({parentProduct:i,licenseProduct:a,prepaidOnly:o,licensePlanId:s})=>{if(o!==void 0&&e({prepaidOnly:o}),s&&a.archived)throw new t({message:`License plan ${s} is archived and cannot be linked.`,code:n.InvalidRequest,statusCode:400});if(a.base_internal_product_id)throw new t({message:`A variant cannot be used as a plan license (${s??a.id}).`,code:n.InvalidRequest});if(i&&a.id===i.id)throw new t({message:`A plan cannot be linked as a license to itself (${s??a.id}).`,code:n.InvalidRequest,statusCode:400})}}))(UI,lt,ht),{evaluateCatalogItemIdentity:Xx}=(e=>({evaluateCatalogItemIdentity:({item:n,recipe:r=e})=>{let i=[];for(let a of r.components){let o;for(let c of a.paths){o=n;for(let u of c.split("."))o=o!==null&&typeof o=="object"?o[u]:void 0;if(o!=null)break}let s=a.defaultWhen&&i[a.defaultWhen.component]?a.defaultWhen.value:a.default;if(o!=null&&typeof o!="string"&&typeof o!="number")throw new Error("Catalog identity components must be strings or numbers");i.push(o??s)}return i}}))(BI),{removeItems:zx}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(a=>e({item:i,filter:a})))}))(VI),{toApiPlanItem:eA}=((e,t)=>({toApiPlanItem:r=>({...r,included:r.included??0,unlimited:r.unlimited??!1,reset:r.reset??null,price:e(r.price),rollover:t(r.rollover)})}))($I,GI),{applyLicenses:tA}=(e=>({applyLicenses:({base:n,diff:r})=>{if(r.upsert_licenses===void 0&&r.remove_licenses===void 0)return;let i=new Set((r.remove_licenses??[]).map(s=>s.license_plan_id)),a=new Map((r.upsert_licenses??[]).map(s=>[s.license_plan_id,s])),o=[];for(let s of n.licenses??[]){if(i.has(s.license_plan_id))continue;let c=a.get(s.license_plan_id);if(c){o.push(e({existing:s,upsert:c})),a.delete(s.license_plan_id);continue}o.push(s)}for(let s of r.upsert_licenses??[])a.has(s.license_plan_id)&&o.push(e({upsert:s}));return o}}))(HI),{pricesEqual:kf}=(e=>({pricesEqual:(n,r)=>n===void 0&&r===void 0||n===null&&r===null?!0:n==null||r==null?!1:n.amount===r.amount&&n.interval===r.interval&&(n.interval_count??1)===(r.interval_count??1)&&e(n.additional_currencies,r.additional_currencies)}))(ic),{itemPricesEqual:nA}=((e,t,n)=>({itemPricesEqual:(i,a)=>{if(i==null&&a==null)return!0;if(i==null||a==null)return!1;let o=i.tiers?.length?i.tier_behavior??e.Graduated:null,s=a.tiers?.length?a.tier_behavior??e.Graduated:null;return(i.amount??null)===(a.amount??null)&&t(i.additional_currencies,a.additional_currencies)&&n(i.tiers,a.tiers)&&o===s&&i.interval===a.interval&&(i.interval_count??1)===(a.interval_count??1)&&(i.billing_units??1)===(a.billing_units??1)&&i.billing_method===a.billing_method&&(i.max_purchase??null)===(a.max_purchase??null)}}))(ja,ic,QI),{featureOverridesEqual:rA}=((e,t)=>({featureOverridesEqual:(r,i)=>r==null&&i==null?!0:r==null||i==null?!1:e(r.credit_schema)===e(i.credit_schema)&&t(r.markups??{})===t(i.markups??{})}))(JI,rc),{freeTrialsEqual:iA}=(e=>({freeTrialsEqual:(n,r)=>n===void 0&&r===void 0||n===null&&r===null?!0:n==null||r==null?!1:n.duration_length===r.duration_length&&(n.duration_type??e.Month)===(r.duration_type??e.Month)&&(n.card_required??!0)===(r.card_required??!0)&&(n.on_end??"bill")===(r.on_end??"bill")}))(ex),{planItemFiltersEqual:aA}=(e=>({planItemFiltersEqual:(n,r)=>n.feature_id===r.feature_id&&(n.billing_method??null)===(r.billing_method??null)&&(n.interval??null)===(r.interval??null)&&e({interval:n.interval,intervalCount:n.interval_count})===e({interval:r.interval,intervalCount:r.interval_count})&&(n.included??null)===(r.included??null)}))(nx),{toUpsertLicense:oA}=(e=>({toUpsertLicense:({license:n,clearCustomize:r=!1})=>({license_plan_id:n.license_plan_id,...n.version_slug!==void 0?{version_slug:n.version_slug}:{},included:n.included,prepaid_only:n.prepaid_only,...r?{customize:null}:e(n.customize)?{customize:n.customize}:{}})}))(Sf),{getVariantSettingsPatch:_D}=((e,t)=>({getVariantSettingsPatch:({from:r,to:i})=>{let a={};for(let o of e)t(r[o],i[o])||(a[o]=i[o]);return a}}))(ix,ax),{isOneOffProductV2:bD}=((e,t,n,r)=>({isOneOffProductV2:({items:a})=>{let o=a.filter(s=>e(s)||t(s));return o.length>0&&o.every(s=>n({item:s})===r.OneOff)}}))(Ua,Pr,bn,Qt),{canonicalizeBillingControls:sA}=(e=>({canonicalizeBillingControls:n=>{let r=n??{},i={};for(let a of Object.keys(r)){let o=r[a];Array.isArray(o)&&o.length===0||(i[a]=Array.isArray(o)?[...o].sort((s,c)=>String(s?.feature_id??"").localeCompare(String(c?.feature_id??""))):o)}return JSON.stringify(e(i))}}))(vf),{ProductConfigSchema:cA}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(fe,cx),{shouldApplyVariantUpdates:yD}=(e=>({shouldApplyVariantUpdates:({oldBase:n,latestBase:r,propagateToVariants:i,variantUpdates:a,updates:o})=>i.length>0||a.length>0||n.internal_id!==r.internal_id?!0:e.some(s=>o[s]!==void 0)}))(ux),{resolveLicenseParentTargets:SD}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:a,childPlanId:o})=>{let s=new Map(i.map(l=>[e({planId:l.parent.id,version:l.parent.version}),l])),c=new Set,u=[];for(let l of a){let d=e({planId:l.plan_id,version:l.version});if(c.has(d))throw new t({message:`Parent plan target ${d} was selected more than once.`,code:n.InvalidPropagationTarget,statusCode:400});let p=s.get(d);if(!p)throw new t({message:`Plan ${l.plan_id} v${l.version} does not offer ${o} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),u.push(p)}return u}}))(lx,lt,ht),{stripeMinorUnitFactor:Ma}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(If,dx),{entIntervalsSame:uA}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),a=e(r.interval,r.intervalCount);return i.eq(a)}}))(mx),{intervalsDifferent:lA}=((e,t)=>({intervalsDifferent:({intervalA:r,intervalB:i})=>{if(e(r)&&e(i))return!1;if(e(r)||e(i))return!0;let a=t(r.interval,r.intervalCount),o=t(i.interval,i.intervalCount);return a!==o}}))(At,px),{allocatedBillingBehaviorAreSame:dA}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),a=e(r);return i===a}}))(hx),{tiersAreSame:mA}=(e=>({tiersAreSame:(n,r)=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every((i,a)=>i.amount===r[a].amount&&i.to===r[a].to&&(i.flat_amount??null)===(r[a].flat_amount??null)&&e(i.additional_currencies,r[a].additional_currencies))}))(ac),{itemToPriceOrTiers:pA}=(e=>({itemToPriceOrTiers:({item:n,proration:r,now:i})=>{if(i=i||Date.now(),n.price)return{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.price}):n.price,tiers:void 0};if(n.tiers)return n.tiers.length>1?{price:void 0,tiers:n.tiers.map(a=>({...a,amount:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:a.amount}):a.amount}))}:{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.tiers[0].amount}):n.tiers[0].amount,tiers:void 0}}}))(bx),{normalizeBillingControls:fA}=((e,t,n)=>({normalizeBillingControls:i=>{let a=e(i);return JSON.stringify(t.flatMap(o=>{let s=a?.[o];return s?.length?[[o,n(s)]]:[]}))}}))(Ix,Ta,xx),{AutoTopupPurchaseLimitSchema:hA}=((e,t)=>({AutoTopupPurchaseLimitSchema:e.object({interval:t.meta({description:"The time interval for the purchase limit window."}),interval_count:e.number().min(1).default(1).meta({description:"Number of intervals in the purchase limit window."}),limit:e.number().min(1).meta({description:"Maximum number of auto top-ups allowed within the interval."})})}))(fe,Cx),{toFeatureItem:gA}=((e,t,n,r)=>({toFeatureItem:({ent:a})=>{if(a.feature.type===e.Boolean)return{feature_id:a.feature.id,entity_feature_id:a.entity_feature_id,entitlement_id:a.id};let o=a.rollover||a.feature_override?{rollover:a.rollover??void 0,feature_override:a.feature_override??void 0}:void 0;return{feature_id:a.feature.id,included_usage:a.allowance_type===t.Unlimited?n:a.allowance,interval:r({entInterval:a.interval}),interval_count:a.interval_count??1,entity_feature_id:a.entity_feature_id,pooled:a.pooled??!1,reset_usage_when_enabled:!a.carry_from_previous,config:o,entitlement_id:a.id,created_at:a.created_at}}}))(at,Ra,di,Pf),{toPriceItem:_A}=((e,t)=>({toPriceItem:({price:r})=>{let i=r.config;return{feature_id:null,interval:e({billingInterval:i.interval}),interval_count:i.interval_count??1,price:i.amount,additional_currencies:t(i.currencies)??void 0,base_currency:i.base_currency??void 0,price_id:r.id,created_at:r.created_at,price_config:r.config}}}))(Cf,G0),{isPayPerUsePrice:Df}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(oc,Sr),{createFeaturesFromItems:bA}=((e,t,n,r,i,a,o,s,c,u)=>({createFeaturesFromItems:({items:d,curFeatures:p,orgId:g,env:m})=>{let h=[];for(let y of d){if(!y.feature_id)continue;let x=p.find(v=>v.id===y.feature_id);if(x){if(e(y.feature_type))continue;if(y.feature_type===t.Static){if(y.feature_type===t.Static&&x.type!==n.Boolean)throw new r({message:`Feature ${y.feature_id} already exists but is not a static feature`,code:i.InvalidRequest,statusCode:400})}else if(y.feature_type!==x.config?.usage_type)throw new r({message:`Feature ${y.feature_id} already exists but is not a ${y.feature_type} feature`,code:i.InvalidRequest,statusCode:400});continue}if(a(y.feature_id),o(y)){let v=s({featureId:y.feature_id,orgId:g,env:m});h.push(v)}else{if(!y.feature_type)throw new r({message:`Feature type is required for ${y.feature_id}. Either 'continuous_use' or 'single_use'`,code:i.InvalidRequest,statusCode:400});let v=c({featureId:y.feature_id,orgId:g,env:m,usageType:y.feature_type===t.ContinuousUse?u.Continuous:u.Single});h.push(v)}}return{allFeatures:[...p,...h],newFeatures:h}}}))(Ir,Zt,at,lt,ht,W0,Tf,wx,Ex,gn),{SUPPORTED_SET:yA}=(e=>({SUPPORTED_SET:new Set(e)}))(Rx),{CreditDimensionSchema:SA}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(fe,Dx,mf,Rf),{FeatureMarkupsOverrideSchema:vA}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(fe,Fx,iI),{validateCreditRate:Ff}=(e=>({validateCreditRate:({rate:n,invalidCreditSystem:r})=>{if(n.tier_behavior==="graduated"){(!Array.isArray(n.tiers)||n.tiers.length===0)&&r("Graduated credit schemas require at least one tier.");let a=n.tiers??[];for(let s of a){let c=Number(s.credit_amount);(!Number.isFinite(c)||c<0)&&r("Tier credit costs must be zero or greater."),s.credit_amount=c,s.to!=="inf"&&(s.to=Number(s.to))}let[o]=e(a.map(s=>s.to));o&&r(o.message);return}let i=Number(n.credit_amount);(!Number.isFinite(i)||i<0)&&r("Credit cost must be zero or greater."),n.credit_amount=i}}))(Mx),{validateDimensionsAreSeparable:IA}=((e,t)=>({validateDimensionsAreSeparable:({dimensions:r,invalidCreditSystem:i})=>{let[a]=e(r);if(!a)return;let[o,s]=a.names;i(`Dimensions "${o}" and "${s}" can both match the same event (${t(a.example)}). Give one more match keys or a priority.`)}}))(Bx,sI),{validateCreditMultipliers:xA}=((e,t)=>({validateCreditMultipliers:({schemaItem:r,invalidCreditSystem:i})=>{for(let[a,o]of Object.entries(r.multipliers??{}))e({name:a,multiplier:o,invalidCreditSystem:i});t({schemaItem:r,invalidCreditSystem:i})}}))(cI,Lx),{FixedPriceConfigSchema:AA}=((e,t,n,r,i)=>({FixedPriceConfigSchema:e.object({type:e.string(),amount:e.number().min(0),interval:e.enum(t),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),n).nullish(),billing_units:e.number().nullish(),usage_tiers:e.array(r).nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),feature_id:i,internal_feature_id:i})}))(fe,Qt,jf,nc,fI),{currenciesAreCompatible:OA}=(e=>({currenciesAreCompatible:(n,r)=>{let i=n??{},a=r??{};for(let o of Object.keys(i)){let s=a[o];if(!s)continue;let c=i[o];if((c?.amount??null)!==(s.amount??null)||!e(c?.usage_tiers??[],s.usage_tiers??[]))return!1}return!0}}))(Nf),{creditSchemaItemsAreSame:PA}=(e=>({creditSchemaItemsAreSame:({left:n,right:r})=>(n.feature_amount??1)==(r.feature_amount??1)&&e({left:n,right:r})&&n.credit_amount==r.credit_amount&&(n.tier_behavior??null)===(r.tier_behavior??null)&&(n.tiers??[]).length===(r.tiers??[]).length&&(n.tiers??[]).every((i,a)=>i.to===r.tiers?.[a]?.to&&i.credit_amount==r.tiers?.[a]?.credit_amount)}))(Kx),{markupOverridesAreSame:CA}=(e=>({markupOverridesAreSame:({markups1:n,markups2:r})=>n&&r?(n.default_markup??null)===(r.default_markup??null)&&e(n.provider_markups,r.provider_markups)&&e(n.model_markups,r.model_markups):!(n||r)}))(Hx),{resolveAllocatedBillingBehavior:wA}=((e,t,n,r)=>({resolveAllocatedBillingBehavior:({item:a,curPrice:o})=>{if(e(a.config?.allocated_billing_behavior))return a.config.allocated_billing_behavior;if(e(a.config?.on_increase)||e(a.config?.on_decrease))return t.Prorated;if(o&&n({price:o})){let c=o.config;return e(c.allocated_billing_behavior)?c.allocated_billing_behavior:r(o)?t.Prorated:t.Arrear}return t.Arrear}}))(Bn,_n,Df,Ef),{itemCanBeProrated:EA}=((e,t,n)=>({itemCanBeProrated:({item:i,features:a})=>{let o=e({item:i,features:a});return o===t.SingleUse&&i.usage_model===n.Prepaid?!0:o===t.ContinuousUse}}))(Qx,Zt,vr),{priceHasPreviewStripeId:TA}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(a=>t({stripeId:i[a]}))}}))(EI,Zx),{buildPlanItemKey:RA}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let a=t({item:r});return i===e.FeatureCadence&&a.splice(1,1),a.join("|")}}))(MI,Xx),{itemsEqual:Uf}=((e,t,n,r)=>({itemsEqual:(a,o)=>a.feature_id===o.feature_id&&(a.entity_feature_id??null)===(o.entity_feature_id??null)&&(a.pooled??!1)===(o.pooled??!1)&&(a.included??0)===(o.included??0)&&(a.unlimited??!1)===(o.unlimited??!1)&&(a.reset?.interval??null)===(o.reset?.interval??null)&&(a.reset?.interval_count??1)===(o.reset?.interval_count??1)&&e(a.price,o.price)&&t(a.rollover,o.rollover)&&n(a.proration,o.proration)&&r(a.feature_override,o.feature_override)}))(nA,ZI,YI,rA),{licenseCustomizesAreSame:jA}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:a,right:o})=>{let s=a??{},c=o??{},u={price:!e(s.price,c.price),addItems:!t({left:s.add_items,right:c.add_items,equals:n}),removeItems:!t({left:s.remove_items,right:c.remove_items,equals:r})};return!Object.values(u).some(Boolean)}}))(kf,tx,Uf,aA),{normalizeVariantSettingValue:NA}=((e,t,n)=>({normalizeVariantSettingValue:({field:i,value:a})=>{if(i==="group")return a||"";if(i==="description")return a||null;if(i==="billing_controls")return e(a);if(i==="config"){let o=t.safeParse(a??{});return JSON.stringify(n(o.success?o.data:a??{}))}return i==="metadata"?JSON.stringify(n(a??{})):a}}))(sA,cA,vf),{intervalsSame:kA}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(lA),{sanitizeItems:DA}=((e,t,n,r)=>({sanitizeItems:({items:a,features:o})=>a.map(s=>{let c=s.tiers?.length===1&&s.tiers[0].additional_currencies?.length?{price:void 0,tiers:s.tiers}:e({item:s}),u={...s,reset_usage_when_enabled:t({item:s,feature:o.find(l=>l.id===s.feature_id)}),...c};return u.config||(u.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),u})}))(pA,yx,Ar,pi),{compareBillingControls:FA}=(e=>({compareBillingControls:({newBillingControls:n,curBillingControls:r})=>e(n)===e(r)}))(fA),{AutoTopupSchema:UA}=((e,t)=>({AutoTopupSchema:e.object({feature_id:e.string().meta({description:"The ID of the feature (credit balance) to auto top-up."}),enabled:e.boolean().default(!1).meta({description:"Whether auto top-up is enabled."}),threshold:e.number().meta({description:"When the balance drops below this threshold, an auto top-up will be purchased."}),quantity:e.number().min(1).meta({description:"Amount of credits to add per auto top-up."}),purchase_limit:t.optional().meta({description:"Optional rate limit to cap how often auto top-ups occur."}),invoice_mode:e.boolean().optional().meta({description:"When true, auto top-up creates a send_invoice invoice instead of auto-charging."})})}))(fe,hA),{toFeaturePriceItem:MA}=((e,t,n,r,i,a,o,s,c,u,l)=>({toFeaturePriceItem:({ent:p,price:g})=>{let m=g.config,h=e(m.currencies,m.usage_tiers.length),y=m.usage_tiers.map((E,A)=>({amount:E.amount,to:E.to===-1?t:E.to,flat_amount:E.flat_amount,...h?.[A]?.length?{additional_currencies:h[A]}:{}})),x={};return g.proration_config&&(x={...g.proration_config}),n({feature:p.feature})&&r({price:g})&&(x.allocated_billing_behavior=m.allocated_billing_behavior??(i(g)?a.Prorated:a.Arrear)),p.rollover&&(x.rollover=p.rollover),p.expiry_duration&&p.expiry_length!=null&&(x.expiry={duration:p.expiry_duration,length:p.expiry_length}),p.feature_override&&(x.feature_override=p.feature_override),m.threshold_billing&&(x.threshold_billing=m.threshold_billing),{feature_id:p.feature.id,feature_type:p.feature.config?.usage_type||o.SingleUse,included_usage:p.allowance,interval:s({entInterval:p.interval}),interval_count:p.interval_count??1,price_interval:c({billingInterval:m.interval}),price_interval_count:m.interval_count??1,price:null,tiers:y,base_currency:m.base_currency??void 0,billing_units:m.billing_units,tier_behavior:g.tier_behavior??null,entity_feature_id:p.entity_feature_id,pooled:p.pooled??!1,reset_usage_when_enabled:!p.carry_from_previous,usage_model:m.bill_when===u.StartOfPeriod||m.bill_when===u.InAdvance?l.Prepaid:l.PayPerUse,created_at:p.created_at,entitlement_id:p.id,price_id:g.id,price_config:g.config,config:Object.keys(x).length>0?x:void 0,usage_limit:p.usage_limit}}}))(K0,Ys,wf,Df,Ef,_n,Zt,Pf,Cf,mi,vr),{isValidCurrencyCode:cc}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(yA),{CreditSchemaItemBaseSchema:Mf}=((e,t,n,r)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,n).optional(),multipliers:e.record(t,r).optional()})}))(fe,kx,SA,rI),{GraduatedCreditSchemaItemSchema:BA}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(Mf,Rf),{validateCreditDimensionRules:LA}=((e,t,n)=>({validateCreditDimensionRules:({schemaItem:i,invalidCreditSystem:a})=>{let o=i.dimensions??{};for(let[s,c]of Object.entries(o))c.priority!==void 0&&!Number.isInteger(c.priority)&&a(`Dimension "${s}" priority must be an integer.`),e({rate:c,invalidCreditSystem:a});t({dimensions:o,invalidCreditSystem:a}),n({schemaItem:i,invalidCreditSystem:a})}}))(Ff,IA,xA),{pricesAreSame:Ba}=((e,t,n,r,i,a,o,s)=>({pricesAreSame:(u,l,d=!1)=>{let p=u.config,g=l.config;if(p.type!==g.type)return!1;if(p.type===e.Fixed){let A=t.parse(p),S=t.parse(g),q={amount:A.amount!==S.amount,interval:A.interval!==S.interval,intervalCount:(A.interval_count??1)!==(S.interval_count??1),baseCurrency:!n({base1:A.base_currency,base2:S.base_currency,currencies1:A.currencies,currencies2:S.currencies}),currencies:!r(A.currencies,S.currencies)};return!Object.values(q).some(Boolean)}let m=i.parse(p),h=i.parse(g),y={shouldProrate:(m.should_prorate??!1)!==(h.should_prorate??!1),allocatedBillingBehavior:a(m)!==a(h),billWhen:m.bill_when!==h.bill_when,billingUnits:(m.billing_units??1)!==(h.billing_units??1),thresholdBilling:m.threshold_billing?.threshold!==h.threshold_billing?.threshold,interval:m.interval!==h.interval,intervalCount:(m.interval_count??1)!==(h.interval_count??1),internalFeatureId:m.internal_feature_id!==h.internal_feature_id,featureId:m.feature_id!==h.feature_id,usageTiers:!o(m.usage_tiers,h.usage_tiers),baseCurrency:!n({base1:m.base_currency,base2:h.base_currency,currencies1:m.currencies,currencies2:h.currencies}),currencies:!r(m.currencies,h.currencies)},x=m.usage_tiers.length<=1&&h.usage_tiers.length<=1,v={onIncrease:u.proration_config?.on_increase!=l.proration_config?.on_increase,onDecrease:u.proration_config?.on_decrease!=l.proration_config?.on_decrease,tierBehavior:!x&&(u.tier_behavior??s.Graduated)!==(l.tier_behavior??s.Graduated)},E=Object.values(y).some(Boolean)||Object.values(v).some(Boolean);return E&&d&&console.log("Prices are different",{configDiffs:y,prorationDiffs:v}),!E}}))(yr,AA,qx,OA,$x,_I,Nf,ja),{creditSchemasAreSame:VA}=(e=>({creditSchemasAreSame:({schema1:n,schema2:r})=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every(i=>{let a=r.find(o=>o.metered_feature_id===i.metered_feature_id);return a?e({left:i,right:a}):!1})}))(PA),{itemToAllocatedBillingBehavior:qA}=((e,t,n,r,i,a,o,s,c)=>({itemToAllocatedBillingBehavior:({item:l,features:d,curPrice:p})=>{if(!(e({item:l,features:d})===t.ContinuousUse&&n(l)&&l.usage_model!==r.Prepaid))return null;let h=i({item:l,curPrice:p});if(h===a.Arrear){if(o(l.config?.on_increase)||o(l.config?.on_decrease))throw new s({message:`on_increase / on_decrease are not supported for allocated arrear billing (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400});if(o(l.config?.rollover))throw new s({message:`rollover is not supported for allocated arrear billing because the balance never resets (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400})}return h}}))(Wx,Zt,Pr,vr,wA,_n,Bn,lt,AI),{composeMatchKey:fi}=(e=>({composeMatchKey:n=>e({item:n})}))(RA),{applyItems:$A}=((e,t,n,r)=>({applyItems:(a,o)=>{let s=[...a];if(o.remove_items&&(s=e(s,o.remove_items)),o.add_items){let c=new Set;for(let u of s)t(u)&&c.add(n(u));for(let u of o.add_items){let l=n(u);t(u)&&c.has(l)||(s.push(r(u)),t(u)&&c.add(l))}}return s}}))(zx,qI,fi,eA),{dedupeItemsByMatchKey:GA}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(fi),{planLicensesAreSame:KA}=(e=>({planLicensesAreSame:({left:n,right:r})=>{let i={licensePlanId:n.license_plan_id!==r.license_plan_id,versionSlug:n.version_slug!==r.version_slug,included:n.included!==r.included,prepaidOnly:n.prepaid_only!==r.prepaid_only,customize:!e({left:n.customize,right:r.customize})};return!Object.values(i).some(Boolean)}}))(jA),{dedupeItemsByMatchKey:HA}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(fi),{validateVariantSettingsUpdate:vD}=((e,t,n,r)=>({validateVariantSettingsUpdate:({allowVariantSettingsUpdate:a,fullProduct:o,currentProduct:s,updates:c})=>{if(a||o.base_internal_product_id==null)return;let u=e.find(l=>c[l]===void 0?!1:t({field:l,value:c[l]})!==t({field:l,value:s[l]}));if(u)throw new n({message:`Cannot update ${u} directly on a variant plan.`,code:r.InvalidPropagationTarget,statusCode:400})}}))(sx,NA,lt,ht),{findSimilarItem:uc}=((e,t,n,r,i,a,o,s,c)=>({findSimilarItem:({item:l,items:d})=>e(l)?d.find(p=>e(p)&&p.feature_id===l.feature_id&&p.entity_feature_id==l.entity_feature_id&&t({intervalA:{interval:n({item:p}),intervalCount:r({item:p})},intervalB:{interval:n({item:l}),intervalCount:r({item:l})}})):i(l)?d.find(p=>i(p)&&p.feature_id===l.feature_id&&p.entity_feature_id==l.entity_feature_id&&a({intervalA:{interval:o({item:p}),intervalCount:s({item:p})},intervalB:{interval:o({item:l}),intervalCount:s({item:l})}})&&l.usage_model==p.usage_model):c(l)?d.find(p=>c(p)&&p.price==l.price&&o({item:p})==o({item:l})&&s({item:p})==s({item:l})):null}))(Fa,uA,ka,Da,Pr,kA,bn,Or,Ua),{stripAutoTopupCountsForStorage:WA}=(e=>({stripAutoTopupCountsForStorage:n=>n==null?n:n.map(r=>e.parse({...r,purchase_limit:r.purchase_limit?{interval:r.purchase_limit.interval,interval_count:r.purchase_limit.interval_count??1,limit:r.purchase_limit.limit}:void 0}))}))(UA),{toProductItem:Bf}=((e,t,n,r)=>({toProductItem:({ent:a,price:o})=>e(o)?t({ent:a}):e(a)?n({price:o}):r({ent:a,price:o})}))(At,gA,_A,MA),{CurrencyCodeSchema:Lf}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(fe,cc),{AdditionalCurrencyPriceSchema:QA}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(fe,Lf),{FlatCreditSchemaItemSchema:ZA}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(Mf,mf),{validateCreditSystem:YA}=((e,t,n,r,i,a,o,s)=>({validateCreditSystem:(u,l=e.CreditSystem)=>{let d=Array.isArray(u?.schema)?u.schema:[],p=v=>{throw new t({message:v,code:n.InvalidFeature,statusCode:r.BAD_REQUEST})};!i(l)&&d.length===0&&p("At least one metered feature is required for credit system"),i(l)&&d.length>0&&p("AI credit systems are leaf features and cannot define a schema. Model rates live in model_markups.");let g=d.map(v=>v.metered_feature_id),m=Array.from(new Set(g));g.length!==m.length&&p("Credit system contains multiple of the same metered_feature_id");let h={...u,schema:d,usage_type:a.Single},y=h.default_markup;if(y!=null){let v=Number(y);if(Number.isNaN(v)||v<-100)throw new t({message:"Default markup must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});h.default_markup=v}let x=h.provider_markups;if(x!=null)for(let[v,E]of Object.entries(x)){let A=Number(E?.markup);if(!v||Number.isNaN(A)||A<-100)throw new t({message:"Provider markups must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});E.markup=A}for(let v of h.schema){if(v.feature_amount!==void 0){let E=Number(v.feature_amount);(!Number.isFinite(E)||E<=0)&&p("Billing units must be greater than zero."),v.feature_amount=E}o({rate:v,invalidCreditSystem:p}),s({schemaItem:v,invalidCreditSystem:p})}return h}}))(at,lt,ht,hn,ec,gn,Ff,LA),{stripePriceIdForInitializedPrice:Vf}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:a,newPrice:o})=>{if(!e(i)&&(!a||i!==t({price:a})||n(a,o)))return i}}))(At,pI,Ba),{featureOverridesAreSame:lc}=((e,t)=>({featureOverridesAreSame:({override1:r,override2:i})=>e({schema1:r?.schema,schema2:i?.schema})&&t({markups1:r?.markups,markups2:i?.markups})}))(VA,CA),{applyDiff:qf}=((e,t,n,r)=>({applyDiff:({base:a,diff:o})=>{let s={price:e(a.price,o.price),items:t(a.items,o),free_trial:n(a.free_trial,o.free_trial)},c=r({base:a,diff:o});return c===void 0?s:{...s,licenses:c}}}))(LI,$A,KI,tA),{diffPlanLicenses:JA}=((e,t,n,r)=>({diffPlanLicenses:({from:a,to:o,includeAdds:s=!1,includeRemoves:c=!1})=>{let u=new Map((a??[]).map(g=>[g.license_plan_id,g])),l=new Map((o??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of l.values()){let m=u.get(g.license_plan_id);!m&&!s||m&&e({left:m,right:g})||d.push(t({license:g,clearCustomize:m!=null&&n(m.customize)&&!n(g.customize)}))}let p=c?[...u.keys()].filter(g=>!l.has(g)).map(g=>({license_plan_id:g})):[];return{...d.length>0?{upsert_licenses:d.sort(r)}:{},...p.length>0?{remove_licenses:p.sort(r)}:{}}}}))(KA,oA,Sf,rx),{applyDiffToVariantPlan:ID}=((e,t)=>({applyDiffToVariantPlan:({plan:r,diff:i,settingsPatch:a={}})=>{let o=e({base:r,diff:i});return{...r,...o,...a,items:t(o.items)}}}))(qf,HA),{mapToProductItems:$f}=((e,t,n,r)=>({mapToProductItems:({prices:a,entitlements:o,features:s})=>{let c=[];a??=[],o??=[];for(let u of o){let l=e({ent:u,prices:a}),d=t({ent:u,price:l});c.push(d)}for(let u of a)n({price:u,entitlements:o})||c.push(t({price:u}));for(let u of c)s.find(d=>d.id===u.feature_id)&&(u.feature_type=r({item:u,features:s}));return c}}))(rf,Bf,sc,af),{featureItemsAreSame:XA}=((e,t,n)=>({featureItemsAreSame:({item1:i,item2:a,logDifferences:o=!1})=>{let s={feature_id:{condition:i.feature_id===a.feature_id,message:`Feature ID different: ${i.feature_id} != ${a.feature_id}`},included_usage:{condition:e(i.included_usage)==e(a.included_usage),message:`Included usage different: ${i.included_usage} != ${a.included_usage}`},interval:{condition:i.interval==a.interval,message:`Interval different: ${i.interval} != ${a.interval}`},interval_count:{condition:(i.interval_count||1)==(a.interval_count||1),message:`Interval count different: ${i.interval_count} != ${a.interval_count}`},entity_feature_id:{condition:i.entity_feature_id==a.entity_feature_id,message:`Entity feature ID different: ${i.entity_feature_id} != ${a.entity_feature_id}`},pooled:{condition:(i.pooled??!1)===(a.pooled??!1),message:`Pooled different: ${i.pooled} != ${a.pooled}`},reset_usage_when_enabled:{condition:(i.reset_usage_when_enabled??!1)===(a.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${i.reset_usage_when_enabled} !== ${a.reset_usage_when_enabled}`},rollover_config:{condition:t({rollover1:i.config?.rollover||void 0,rollover2:a.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(i.config?.rollover)} !== ${JSON.stringify(a.config?.rollover)}`},feature_override:{condition:n({override1:i.config?.feature_override,override2:a.config?.feature_override}),message:`Feature override different: ${JSON.stringify(i.config?.feature_override)} !== ${JSON.stringify(a.config?.feature_override)}`},threshold_billing:{condition:(i.config?.threshold_billing?.threshold??null)===(a.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(i.config?.threshold_billing)} !== ${JSON.stringify(a.config?.threshold_billing)}`}},c=Object.values(s).every(u=>u.condition);return!c&&o&&console.log("Feature items different:",Object.values(s).filter(u=>!u.condition).map(u=>u.message)),c}}))(Af,Of,lc),{featurePriceItemsAreSame:zA}=((e,t,n,r,i,a,o,s,c,u)=>({featurePriceItemsAreSame:({item1:d,item2:p,logDifferences:g=!1})=>{let m={included_usage:{condition:e(d.included_usage)==e(p.included_usage),message:`Included usage different: ${d.included_usage} != ${p.included_usage}`},usage_limit:{condition:d.usage_limit==p.usage_limit,message:`Usage limit different: ${d.usage_limit} !== ${p.usage_limit}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`},proration_config:{condition:t({config1:d.config||void 0,config2:p.config||void 0}),message:`Proration config different: ${JSON.stringify(d.config)} !== ${JSON.stringify(p.config)}`},allocated_billing_behavior:{condition:n({item1:d,item2:p}),message:`Allocated billing behavior different: ${d.config?.allocated_billing_behavior} !== ${p.config?.allocated_billing_behavior}`},rollover_config:{condition:r({rollover1:d.config?.rollover||void 0,rollover2:p.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(d.config?.rollover)} !== ${JSON.stringify(p.config?.rollover)}`},feature_override:{condition:i({override1:d.config?.feature_override,override2:p.config?.feature_override}),message:`Feature override different: ${JSON.stringify(d.config?.feature_override)} !== ${JSON.stringify(p.config?.feature_override)}`},threshold_billing:{condition:(d.config?.threshold_billing?.threshold??null)===(p.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(d.config?.threshold_billing)} !== ${JSON.stringify(p.config?.threshold_billing)}`},entity_feature_id:{condition:d.entity_feature_id==p.entity_feature_id,message:`Entity feature ID different: ${d.entity_feature_id} != ${p.entity_feature_id}`},pooled:{condition:(d.pooled??!1)===(p.pooled??!1),message:`Pooled different: ${d.pooled} != ${p.pooled}`}},h={feature_id:{condition:d.feature_id===p.feature_id,message:`Feature ID different: ${d.feature_id} != ${p.feature_id}`},interval:{condition:a({item:d})==a({item:p}),message:`Billing interval different: ${a({item:d})} != ${a({item:p})}`},interval_count:{condition:o({item:d})==o({item:p}),message:`Billing interval count different: ${o({item:d})} != ${o({item:p})}`},usage_model:{condition:d.usage_model===p.usage_model,message:`Usage model different: ${d.usage_model} != ${p.usage_model}`},pricing:{condition:s(c(d),c(p)),message:`Pricing different: ${JSON.stringify(c(d))} != ${JSON.stringify(c(p))}`},additional_currencies:{condition:u(d.additional_currencies,p.additional_currencies),message:"Additional currencies different"},tier_behavior:{condition:(c(d)?.length??0)<=1&&(c(p)?.length??0)<=1?!0:d.tier_behavior==p.tier_behavior,message:`Tiers type different: ${d.tier_behavior} != ${p.tier_behavior}`},billing_units:{condition:d.billing_units==p.billing_units,message:`Billing units different: ${d.billing_units} !== ${p.billing_units}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`}},y=Object.values(h).every(v=>v.condition)&&Object.values(m).every(v=>v.condition),x=Object.values(h).some(v=>!v.condition);return!y&&g&&console.log("Feature price items different:",Object.values(m).filter(v=>!v.condition).map(v=>v.message),Object.values(h).filter(v=>!v.condition).map(v=>v.message)),{same:y,pricesChanged:x}}}))(Af,fx,dA,Of,lc,bn,Or,mA,gx,ac),{pickBillingControlColumns:eO}=((e,t)=>({pickBillingControlColumns:r=>{if(!r)return{};let i=Object.fromEntries(e.flatMap(a=>r[a]===void 0?[]:[[a,r[a]]]));return i.auto_topups!==void 0&&(i.auto_topups=t(i.auto_topups)),i}}))(Ta,WA),{mapToProductV2:xD}=((e,t,n,r,i)=>({mapToProductV2:({product:o,features:s})=>{let c=[];for(let l of o.entitlements){let d=e({ent:l,prices:o.prices});c.push(t({ent:l,price:d}))}for(let l of o.prices)n({price:l,entitlements:o.entitlements})||c.push(t({price:l}));s||(s=o.entitlements.map(l=>l.feature));for(let l of c)l.feature_type=r({item:l,features:s});return{internal_id:o.internal_id,id:o.id,name:o.name,description:o.description??null,is_add_on:o.is_add_on,is_default:o.is_default,version:o.version,version_slug:o.version_slug??null,active:o.active??!1,group:o.group||null,free_trial:o.free_trial,created_at:o.created_at,env:o.env,items:c,stripe_id:o.processor?.id||null,archived:o.archived||!1,config:o.config??void 0,billing_controls:i(o),metadata:o.metadata??{}}}}))(rf,Bf,sc,af,of),{AdditionalCurrencyTierSchema:tO}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,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"]})}))(fe,Lf),{AdditionalCurrencyPriceArraySchema:nO}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(fe,QA,uf,lf),{CreditSchemaItemSchema:rO}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(fe,ZA,BA),{validateItemFeatureOverride:iO}=((e,t,n,r,i,a,o,s,c)=>({validateItemFeatureOverride:({item:l,feature:d,features:p})=>{let g=l.config?.feature_override;if(!g)return;let m=y=>{throw new e({message:`${y} (feature: ${l.feature_id})`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})};if(!(d&&r(d.type))){m("feature_override is only supported on credit system items");return}if(g.schema&&d.type!==i.CreditSystem&&m("feature_override.credit_schema is not supported on AI credit system items"),g.markups&&!a(d.type)&&m("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let h={schema:g.schema,usage_type:o.Single};s(h,d.type),c({config:h,allFeatures:p});for(let y of g.schema)if(!p.find(v=>v.id===y.metered_feature_id))throw new e({message:`feature_override on ${d.id} references unknown feature ${y.metered_feature_id}`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})}}))(lt,ht,hn,Ux,at,ec,gn,YA,dI),{toPrice:aO}=((e,t,n,r,i,a,o)=>({toPrice:({item:c,orgId:u,internalProductId:l,isCustom:d,newVersion:p,curPrice:g})=>{let m={type:e.Fixed,amount:t(c.price)?c.price:c.tiers[0].amount,interval:n({item:c}),interval_count:r({item:c}),stripe_product_id:null,stripe_price_id:void 0,feature_id:null,internal_feature_id:null},h=i(c.additional_currencies);h&&(m.currencies=h);let y=c.base_currency??(h?g?.config?.base_currency:void 0);y&&(m.base_currency=y);let x={id:c.price_id||g?.id||a("pr"),created_at:c.created_at||Date.now(),org_id:u,internal_product_id:l,is_custom:d,config:m,proration_config:null};return(d||p)&&(x={...x,id:a("pr"),created_at:Date.now()}),m.stripe_price_id=o({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:x}),{price:x,ent:null}}}))(yr,xr,bn,Or,Vx,_r,Vf),{entsAreSame:dc}=((e,t,n,r,i,a,o)=>({entsAreSame:(c,u)=>{if(c.internal_feature_id!==u.internal_feature_id||e(c)!==e(u))return!1;let l=e(c),d={interval:t(c)!==t(u),intervalCount:n(c)!==n(u),allowance:!l&&c.allowance!=u.allowance,carryFromPrevious:(c.carry_from_previous??!1)!==(u.carry_from_previous??!1),entityFeatureId:r(c.entity_feature_id)!==r(u.entity_feature_id),pooled:(c.pooled??!1)!==(u.pooled??!1),usageLimit:c.usage_limit!=u.usage_limit,rollover:!i({rollover1:c.rollover,rollover2:u.rollover}),featureOverride:!a({override1:c.feature_override,override2:u.feature_override}),expiry:!o(c,u)};return!Object.values(d).some(Boolean)}}))(bI,_f,yI,SI,vI,lc,xI),{toFeatureAndPrice:oO}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m,h,y,x,v,E,A,S,q,L,ge,Ie,ne,B)=>({toFeatureAndPrice:({item:H,orgId:He,internalFeatureId:ue,internalProductId:te,isCustom:gt,curPrice:Fe,curEnt:_t,newVersion:Yt,features:Ot})=>{let Wf=e({item:H,feature:Ot.find(st=>st.id===H.feature_id)}),Va=t({item:H,features:Ot,curPrice:Fe}),bc=Va===n.Arrear,Ln={id:H.entitlement_id||_t?.id||r("ent"),org_id:He,created_at:H.created_at||Date.now(),is_custom:gt,internal_product_id:te,internal_feature_id:ue,feature_id:H.feature_id,allowance:H.included_usage||0,allowance_type:i.Fixed,interval:a({item:H}),interval_count:o({item:H}),carry_from_previous:!Wf,entity_feature_id:H.entity_feature_id,pooled:H.pooled??!1,usage_limit:H.usage_limit||null,rollover:H.config?.rollover,expiry_duration:H.config?.expiry?.duration,expiry_length:H.config?.expiry?.length,feature_override:H.config?.feature_override};(!_t||gt&&!s(_t,Ln)||Yt)&&(Ln={...Ln,id:r("ent"),created_at:Date.now()});let Qf=a({item:H}),Cr={type:c.Usage,bill_when:H.usage_model===u.Prepaid?l.StartOfPeriod:l.EndOfPeriod,billing_units:H.billing_units||1,...H.config?.threshold_billing?{threshold_billing:H.config.threshold_billing}:{},should_prorate:Qf===d.Lifetime&&!bc,...Va?{allocated_billing_behavior:Va}:{},internal_feature_id:ue,feature_id:H.feature_id,usage_tiers:p(H.price)?[{amount:H.price,to:g}]:H.tiers?.map(st=>({to:st.to,amount:st.amount??0,...st.flat_amount!=null?{flat_amount:st.flat_amount}:{}})),interval:m({item:H}),interval_count:h({item:H}),stripe_price_id:void 0},yc=y({baseTiers:Cr.usage_tiers,itemTiers:H.tiers,flatCurrencies:H.additional_currencies});yc&&(Cr.currencies=yc,Cr.base_currency=H.base_currency??Fe?.config?.base_currency??void 0);let Zf=x({item:H,features:Ot})&&!bc,Sc=null;if(Zf){let st=H.config?.on_increase||v.ProrateImmediately,yn=H.config?.on_decrease||E.Prorate;(A(yn)||yn===E.Prorate)&&(yn=st===v.ProrateImmediately||st===v.BillImmediately?E.ProrateImmediately:E.ProrateNextCycle),Sc={on_increase:st,on_decrease:yn}}let Vt={id:H.price_id||Fe?.id||r("pr"),created_at:H.created_at||Date.now(),org_id:He,internal_product_id:te,is_custom:gt,config:Cr,entitlement_id:Ln.id,proration_config:Sc,tier_behavior:H.tier_behavior??null},vc=S(Vt.config);if((vc===q.UsageInArrear||vc===q.InArrearProrated)&&Vt.config.interval===L.OneOff)throw new ge({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${H.feature_id})`,code:Ie.InvalidPrice,statusCode:400});let Yf=Fe&&!ne(Fe,Vt,!0)||_t&&!s(_t,Ln);if(Fe&&(Yf||Yt)){let st=Vt.config,yn=Fe.config;st.stripe_meter_id=yn.stripe_meter_id,st.stripe_product_id=yn.stripe_product_id,Vt.config=st}return(gt||Yt)&&(Vt={...Vt,id:r("pr"),created_at:Date.now()}),Cr.stripe_price_id=B({requestedStripePriceId:H.stripe_price_id,currentPrice:Fe,newPrice:Vt}),{price:Vt,ent:Ln}}}))(gf,qA,_n,_r,Ra,ka,Da,dc,yr,vr,mi,br,xr,Ys,bn,Or,OI,EA,Ar,pi,CI,wI,Sr,Qt,lt,ht,Ba,Vf),{getPriceStripeReuseLevel:sO}=((e,t,n,r,i,a)=>({getPriceStripeReuseLevel:({newPrice:s,candidatePrice:c,newEntitlements:u,candidateEntitlements:l})=>{if(e({price:c})||s.config?.type!==c.config?.type)return"none";if(t(c,s,!1)){if(s.config?.type!==n.Usage)return"full";let h=r({price:s,entitlements:u}),y=r({price:c,entitlements:l});if(!h&&!y)return"full";if(!h||!y)return"none";if(i(y,h))return"full"}if(s.config?.type!==n.Usage)return"none";let d=s.config,p=c.config;if(d.feature_id!==p.feature_id)return"none";let g=r({price:s,entitlements:u}),m=r({price:c,entitlements:l});return!g&&!m?"stripeProductOnly":!g||!m||a(g.entity_feature_id)!==a(m.entity_feature_id)?"none":"stripeProductOnly"}}))(TA,Ba,yr,Yx,dc,jI),{applyLicenseCustomizeToBasePlan:AD}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:a})=>{let o=new Set((a.add_items??[]).map(u=>e(u))),s={...i,items:i.items.filter(u=>!o.has(e(u)))},c=t({base:s,diff:a});return{...s,...c,items:n(c.items)}}}))(fi,qf,GA),{diffPlanV1:cO}=((e,t,n,r,i,a,o,s,c)=>({diffPlanV1:({from:l,to:d,includeAdds:p=!1,includeRemoves:g=!1,filterPrecision:m=e.Identity})=>{let h={};t(l.price,d.price)||(h.price=d.price===null?null:n(d.price));let y=new Map(l.items.map(A=>[r(A),A])),x=new Map(d.items.map(A=>[r(A),A])),v=[];for(let A of d.items){let S=y.get(r(A));(!S||!i(S,A))&&v.push(a(A))}v.length>0&&(h.add_items=v);let E=[];for(let A of l.items){let S=x.get(r(A));(!S||!i(A,S))&&E.push(o({item:A,filterPrecision:m}))}if(E.length>0&&(h.remove_items=E),!s(l.free_trial,d.free_trial))if(d.free_trial==null)h.free_trial=null;else{let{on_end:A,...S}=d.free_trial;h.free_trial=A==null?S:{...S,on_end:A}}return Object.assign(h,c({from:l.licenses,to:d.licenses,includeAdds:p,includeRemoves:g})),h}}))(yf,kf,WI,fi,Uf,XI,zI,iA,JA),{currentItemsOf:Gf}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))($f),{itemsAreSame:Kf}=((e,t,n,r,i,a,o,s)=>({itemsAreSame:({item1:u,item2:l,features:d,logDifferences:p=!1})=>{let g=!1,m=!1;if(e(u)){if(!e(l))return{same:!1,pricesChanged:!0};g=t({item1:u,item2:l,logDifferences:p}),m=!1}if(n(u)){if(!n(l))return{same:!1,pricesChanged:!0};let{same:h,pricesChanged:y}=r({item1:u,item2:l,logDifferences:p});g=h,i({item:u,features:d||[]})?.config?.usage_type===a.Continuous?m=!0:m=y}return o(u)&&(g=s({item1:u,item2:l,logDifferences:p}),g||(m=!0)),{same:g,pricesChanged:!g&&m}}}))(Fa,XA,Pr,zA,bf,gn,Ua,_x),{productsAreSame:OD}=((e,t,n,r,i,a,o,s,c,u,l,d,p)=>({productsAreSame:({newProductV1:m,newProductV2:h,curProductV1:y,curProductV2:x,features:v})=>{if(!m&&!h)throw new Error("productsAreSame error: product1 not provided");if(!y&&!x)throw new Error("productsAreSame error: product2 not provided");let E=h?.items||e({prices:m?.prices||[],entitlements:m?.entitlements||[],features:v}),A=x?.items||e({prices:y?.prices||[],entitlements:y?.entitlements||[],features:v});E=t({items:E,features:v}),A=t({items:A,features:v});let S=!0,q=!1,L=!0,ge=!0,Ie=!0,ne=[],B=[];L=n({newProductV2:h,curProductV2:x}),ge=r({newConfig:h?.config,curConfig:x?.config}),Ie=i({newBillingControls:h?.billing_controls??(m?a(m):void 0),curBillingControls:x?.billing_controls??(y?a(y):void 0)});let Ce=o({newMetadata:h?.metadata,curMetadata:x?.metadata});E.length!==A.length&&(S=!1),E.length!==A.length&&(S=!1);for(let Fe of E){let _t=s({item:Fe,items:A});if(!_t){(c(Fe)||u(Fe))&&(q=!0),S=!1,ne.push(Fe);continue}let{same:Yt,pricesChanged:Ot}=l({item1:Fe,item2:_t,features:v,logDifferences:!1});Yt||(S=!1,ne.push(Fe)),Ot&&(q=!0)}for(let Fe of A)s({item:Fe,items:E})||(S=!1,(c(Fe)||u(Fe))&&(q=!0),B.push(Fe));let H=y?.free_trial||x?.free_trial,He=m?.free_trial||h?.free_trial,ue=d({ft1:H,ft2:He}),te=p({curProduct:x||y,newProduct:h||m});return{itemsSame:S,freeTrialsSame:ue,onlyEntsChanged:!q,newItems:ne,removedItems:B,detailsSame:L,optionsSame:te,configSame:ge,billingControlsSame:Ie,metadataSame:Ce,same:S&&L&&ue&&ge&&Ce&&Ie}}}))($f,DA,Sx,vx,FA,of,Ax,uc,Pr,Ua,Kf,Ox,Px),{constructProduct:PD}=((e,t)=>({constructProduct:({productData:r,version:i=1,orgId:a,env:o,processor:s,baseInternalProductId:c})=>({id:r.id,name:r.name,description:r.description??null,is_add_on:r.is_add_on,is_default:r.is_default,version:i,version_slug:`v${i}`,active:!0,group:r.group||"",env:o,internal_id:e("prod"),org_id:a,created_at:Date.now(),processor:s,base_variant_id:null,base_internal_product_id:c??r.base_internal_product_id??null,archived:r.archived??!1,deleted_at:null,previous_version_slug:null,config:{...r.config,ignore_past_due:r.config?.ignore_past_due??!1},...t(r.billing_controls),metadata:r.metadata??{}})}))(_r,eO),{AdditionalCurrencyTierArraySchema:uO}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(fe,tO,uf,lf),{FeatureConfigOverrideSchema:lO}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(fe,rO,vA),{itemToPriceAndEnt:dO}=((e,t,n,r,i,a,o,s,c,u)=>({itemToPriceAndEnt:({item:d,orgId:p,internalProductId:g,feature:m,curPrice:h,curEnt:y,isCustom:x,newVersion:v,features:E})=>{let A=null,S=null,q=null,L=null,ge=null,Ie=null;if(e(d)){let{price:ne}=t({item:d,orgId:p,internalProductId:g,isCustom:x,newVersion:v,curPrice:h});!h||v?A=ne:n(h,ne,!0)?ge=h:q=ne}else if(r(d)){if(!m)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let ne=m?.type===o.Boolean,{ent:B}=s({item:d,orgId:p,internalFeatureId:m.internal_id,internalProductId:g,isCustom:x,newVersion:v,feature:m,curEnt:y});!y||v?S=B:c(y,B)?Ie=y:L=B}else{if(!m)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let{price:ne,ent:B}=u({item:d,orgId:p,internalFeatureId:m.internal_id,internalProductId:g,isCustom:x,curPrice:h,curEnt:y,newVersion:v,features:E}),Ce=y&&c(y,B);!h||v?A=ne:!Ce||!n(h,ne,!1)?q=ne:ge=h,!y||v?S=B:Ce?Ie=y:L=B}return{newPrice:A,newEnt:S,updatedPrice:q,updatedEnt:L,samePrice:ge,sameEnt:Ie}}}))(tc,aO,Ba,Na,lt,ht,at,Gx,dc,oO),{copyStripeResourcesToMatchingPrice:mO}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:o,candidatePrices:s,targetEntitlements:c,candidateEntitlements:u})=>{let l=s.map(x=>({candidatePrice:x,level:e({newPrice:o,candidatePrice:x,newEntitlements:c,candidateEntitlements:u})})),d=l.find(x=>x.level==="full"),g=(d??l.find(x=>x.level==="stripeProductOnly"))?.candidatePrice,m=d?.candidatePrice,h=o.config,y=[];if(g){let x=g.config;for(let v of t)v==="stripe_meter_id"&&(!n(o)||!n(g))||r({fromConfig:x,toConfig:h,field:v})&&y.push(v)}if(m){let x=m.config;for(let v of i)t.includes(v)||r({fromConfig:x,toConfig:h,field:v})&&y.push(v)}return{copiedFields:y}}}))(sO,NI,Jx,kI,DI),{getApiPlanDiff:CD}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(cO),{backfillExistingItemIds:pO}=((e,t)=>({backfillExistingItemIds:({items:r,currentFullProduct:i,features:a})=>{let o=e({currentFullProduct:i,features:a});return r.map(s=>{if(s.entitlement_id||s.price_id)return s;let c=t({item:s,items:o});return c?{...s,...c.entitlement_id?{entitlement_id:c.entitlement_id}:{},...c.price_id?{price_id:c.price_id}:{}}:s})}}))(Gf,uc),{PriceTierSchema:fO}=((e,t,n)=>({PriceTierSchema:e.object({to:e.number().or(e.literal(t)).meta({description:"The maximum amount of usage for this tier.",example:100}),amount:e.number().optional().meta({description:"The price of the product item for this tier.",example:10}),flat_amount:e.number().optional().meta({description:"A flat fee charged for this tier, in addition to the per-unit amount."}),additional_currencies:n.nullish().meta({description:"Per-currency amounts for this tier. Boundaries ('to') are shared across currencies."})}).refine(i=>i.amount!=null||i.flat_amount!=null,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0}))}))(fe,Ys,uO),{ProductItemConfigSchema:hO}=((e,t,n,r,i,a,o)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:a.nullish(),feature_override:o.nullish()})}))(fe,_n,Ar,pi,jx,Nx,lO),{carryForwardStripeResources:gO}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:a})=>{for(let o of n)e({targetPrice:o,candidatePrices:i,targetEntitlements:r,candidateEntitlements:a})}}))(mO),{resolveInPlaceEdit:wD}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:a,items:o,currentFullProduct:s,features:c})=>{let u=e({items:o,currentFullProduct:s,features:c}),l=t({currentFullProduct:s,features:c}),d=[],p=[];for(let h of l){let y=n({item:h,items:u}),x=!y,v=y&&!r({item1:y,item2:h,features:c}).same;(x||v)&&(h.entitlement_id&&d.push(h.entitlement_id),h.price_id&&p.push(h.price_id))}let g=new Set([...d,...p]),m=u.map(h=>{let y=h.entitlement_id&&g.has(h.entitlement_id),x=h.price_id&&g.has(h.price_id);return y||x?{...h,entitlement_id:void 0,price_id:void 0}:h});return{retiredEntitlementIds:d,retiredPriceIds:p,items:m,curPrices:s.prices.filter(h=>!g.has(h.id)),curEnts:s.entitlements.filter(h=>!g.has(h.id))}}}))(pO,Gf,uc,Kf),{ProductItemSchema:_O}=((e,t,n,r,i,a,o,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(fe,Z0,Zt,Tx,di,Js,vr,fO,nO,ja,hO),{validateProductItem:bO}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m,h,y,x,v,E)=>({validateProductItem:({item:S,features:q,multiCurrencyEnabled:L,validateRollover:ge})=>{S=e.parse(S);let Ie=q.find(ue=>ue.id===S.feature_id);if(t(S.feature_id)&&t(S.price)&&t(S.tiers))throw new n({message:"Either 'feature_id', 'price', or both should be set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let ne=S.pooled&&Ie?.type===a.Boolean,B=o(S)||s(S.included_usage)&&S.included_usage!==0||s(S.interval)||s(S.config?.rollover);if(ne&&B)throw new n({message:"Pooled boolean items cannot include balance or pricing fields",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(c({item:S,feature:Ie,features:q}),o(S)&&S.included_usage===u)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(S.pooled&&o(S)&&S.usage_model===l.PayPerUse)throw new n({message:"Pooled items cannot use usage-based pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(S.price)&&s(S.tiers))throw new n({message:"Either 'price' or 'tiers' should be set, not both",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let Ce=(S.additional_currencies?.length??0)>0||(S.tiers?.some(ue=>(ue.additional_currencies?.length??0)>0)??!1);if(Ce&&!L)throw new n({message:"Multi-currency is not enabled for this organization",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(Ce&&t(S.base_currency))throw new n({message:"'base_currency' is required when 'additional_currencies' are set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if((S.additional_currencies?.length??0)>0){if(s(S.tiers))throw new n({message:"Tiered items carry 'additional_currencies' on each tier, not at the item level",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(S.price)&&S.price<=0)throw new n({message:"'additional_currencies' require a non-zero 'price' \u2014 a plan that is free in the base currency is free in every currency",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST})}if(d(S)&&S.price&&S.price.toString().split(".")[1]?.length>2)throw new n({message:"One off prices can have at most 2 decimal places",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(S)||p(S)){if(typeof S.included_usage!="number"&&S.included_usage!==u&&s(S.included_usage))throw new n({message:`Included usage for feature ${S.feature_id} must be a number or '${u}'`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(t(S.included_usage)&&(S.included_usage=0),typeof S.included_usage=="number"&&S.included_usage<0)throw new n({message:"Included usage must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(S)||d(S)){let ue=g({item:S});if(String(ue)===m.Day||String(ue)===m.Minute||String(ue)===m.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(S)&&t(S.usage_model))throw new n({message:`Usage model is required for priced features. Please select one for the feature ${S.feature_id}`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(S)&&S.tiers){if(S.included_usage===u)throw new n({message:`Included usage can't be '${u}' for tiered prices`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(S.billing_units&&S.billing_units<=0)throw new n({message:"Billing units must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(S.tier_behavior===h.VolumeBased&&S.tiers.length>1&&S.usage_model!==l.Prepaid)throw new n({message:"Volume-based pricing is only supported for prepaid items",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(S.tiers.some(te=>te.flat_amount!=null&&te.flat_amount>0)){if(S.tier_behavior!==h.VolumeBased)throw new n({message:"flat_amount on tiers is only supported for volume-based pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(S.tiers.length<=1)throw new n({message:"flat_amount is not supported on single-tier pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(S.tiers.some(te=>te.flat_amount!=null&&te.flat_amount<0))throw new n({message:"flat_amount must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(S.usage_model===l.Prepaid&&S.config?.on_increase===y.BillImmediately)throw new n({message:"Bill immediately is not supported for prepaid just yet, contact us at hey@useautumn.com if you're interested!",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(S.config?.expiry&&Ie&&(Ie.type===a.Boolean||x({feature:Ie})))throw new n({message:`expiry is only supported on consumable features (feature: ${S.feature_id})`,code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(!S.config?.rollover)return;let H=S.config.rollover;if(H.duration===v.Forever&&(H.length=0),!ge)return;if(S.included_usage===u)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let He=E({rollover:H});if(He)throw new n({message:He,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(H.duration===v.Month&&(typeof H.length!="number"||H.length<0))throw new n({message:"Rollover length must be a positive number for monthly durations",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(s(S.usage_limit)&&S.usage_limit<=0)throw new n({message:"Usage limit must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}}))(_O,At,lt,ht,hn,at,zs,Bn,iO,di,vr,tc,Na,bn,Js,ja,Ar,wf,Xs,mI),{validateProductItems:yO}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m)=>({validateProductItems:({newItems:y,features:x,orgId:v,env:E,multiCurrencyEnabled:A,validateRollover:S=!0})=>{let{allFeatures:q,newFeatures:L}=e({items:y,curFeatures:x,orgId:v,env:E});x=q;for(let ne=0;ne<y.length;ne++){t({item:y[ne],features:x,multiCurrencyEnabled:A,validateRollover:S});let B=x.find(Ce=>Ce.id===y[ne].feature_id);B&&B.type===n.Metered&&(y[ne].feature_type=B.config?.usage_type)}for(let ne=0;ne<y.length;ne++){let B=y[ne],Ce=r({item:B}),H=i({item:B});if(a(B)&&y.find((te,gt)=>te.feature_id===B.feature_id&&gt!==ne&&B.entity_feature_id===te.entity_feature_id))throw new o({message:`Feature ${B.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let He=y.find((ue,te)=>ue.feature_id===B.feature_id&&te!==ne&&r({item:ue})===Ce&&i({item:ue})===H&&ue.entity_feature_id===B.entity_feature_id);if(He){if(u(He)&&u(B))throw new o({message:`You're trying to create two items for the same feature (${B.feature_id}) with the same interval. Please make them into one item.`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(B.usage_model&&B.usage_model===He?.usage_model)throw new o({message:`You're trying to add the same feature (${B.feature_id}), with the same reset interval. You should either change the reset interval of one of the items, or make one of them a prepaid quantity`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(l(B)&&y.find((te,gt)=>d({item:te})===d({item:B})&&p({item:te})===p({item:B})&&gt!==ne))throw new o({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let ge=y.some(ne=>(l(ne)||g(ne))&&String(d({item:ne}))===m.Week),Ie=y.some(ne=>(l(ne)||g(ne))&&String(d({item:ne}))===m.Month);if(ge&&Ie)throw new o({message:"Can't have both weekly and monthly price items in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(y.filter(l).length>1)throw new o({message:"Can't have more than one price item in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});return{allFeatures:q,newFeatures:L}}}))(bA,bO,at,ka,Da,Tf,lt,ht,hn,Na,tc,bn,Or,zs,Js),{handleNewProductItems:ED}=((e,t,n,r,i)=>({handleNewProductItems:async({db:o,curPrices:s,curEnts:c,newItems:u,features:l,product:d,logger:p,isCustom:g,newVersion:m,saveToDb:h=!0,multiCurrencyEnabled:y})=>{if(!u)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:l};let{allFeatures:x,newFeatures:v}=e({newItems:u,features:l,orgId:d.org_id,env:d.env,multiCurrencyEnabled:y,validateRollover:!g});l=x;let E=[],A=[],S=[],q=[],L=s.filter(B=>{let Ce=u.find(H=>H.price_id===B.id);return Ce?t(Ce):!0}),ge=c.filter(B=>!u.some(Ce=>Ce.entitlement_id===B.id)),Ie=[],ne=[];for(let B of u){let Ce=l.find(Ot=>Ot.id===B.feature_id),H=c.find(Ot=>Ot.id===B.entitlement_id),He=s.find(Ot=>Ot.id===B.price_id),{newPrice:ue,newEnt:te,updatedPrice:gt,updatedEnt:Fe,samePrice:_t,sameEnt:Yt}=n({item:B,orgId:d.org_id,internalProductId:d.internal_id,feature:Ce,curPrice:He,curEnt:H,isCustom:g,newVersion:m,features:l});ue&&E.push(ue),te&&A.push(te),gt&&S.push(gt),Fe&&q.push(Fe),_t&&Ie.push(_t),Yt&&ne.push(Yt)}return r({targetPrices:[...E,...S],targetEntitlements:[...A,...q,...ne],candidatePrices:s,candidateEntitlements:c}),(g||m)&&h?{...i({newPrices:E,newEnts:A,updatedPrices:S,updatedEnts:q,samePrices:Ie,sameEnts:ne,features:l}),samePrices:Ie,sameEnts:ne,newFeatures:v,retiredPriceIds:L.map(B=>B.id),retiredEntitlementIds:ge.map(B=>B.id)}:{prices:[...E,...S],entitlements:[...A,...q].map(B=>({...B,feature:l.find(Ce=>Ce.id===B.feature_id)})),customPrices:[],customEnts:[],features:l,samePrices:Ie,sameEnts:ne,newFeatures:v,retiredPriceIds:L.map(B=>B.id),retiredEntitlementIds:ge.map(B=>B.id)}}}))(yO,Fa,dO,gO,FI);var SO=Et.clone({precision:40});function mc(e){if(!cc(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function pc(e){let t=new SO(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function ND(e,t){let n=mc(t),i=pc(e).toDecimalPlaces(xf(n),Et.ROUND_HALF_CEIL).mul(Ma(n));if(!i.isInteger()||i.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Minor amount exceeds the exact integer boundary");return i.toNumber()}function kD(e,t){let n=mc(t),r=pc(e);if(!r.isInteger()||r.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Minor amount must be an exact safe integer");return r.div(Ma(n)).toString()}function DD(e,t){let n=pc(e).mul(Ma(mc(t)));if(n.isNegative())throw new Error("Usage unit price must be nonnegative");if(n.decimalPlaces()>12||n.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Usage unit amount cannot be represented exactly by the provider");return n.toFixed()}function LD(e){let t=e.screens.map(n=>n.type==="owned"?{...n,document:na(n.document)}:n);for(let n of e.inputs){let r=t.find(i=>i.id===n.screenId);if(r?.type==="owned"&&!kr(r.document,n.componentId))throw new Error(`Local Funnel input ${n.variable} targets hidden component ${n.componentId} on screen ${n.screenId}`)}return Ut.parse({...e,screens:t})}import{z as je}from"zod";var hc=32,vO=522240;function gc(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var IO=je.strictObject({nodeId:je.string().min(1).max(64),visit:je.number().int().nonnegative(),revision:je.number().int().nonnegative()}),fc=je.record(je.string(),he),xO=je.strictObject({id:je.uuid(),nodeId:je.string().min(1).max(64),visit:je.number().int().nonnegative(),input:je.strictObject({schemaVersion:ur.shape.schemaVersion,kind:ur.shape.kind,selector:ur.shape.selector,contract:ur.shape.contract}),context:fc,removed:je.array(je.string()).max(100),attributes:fc,removedAttributes:je.array(je.string()).max(100),result:xm,offeringVersionId:je.uuid().nullable(),events:je.strictObject({entered:je.string().regex(/^[1-9][0-9]{0,18}$/),decision:je.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),AO=je.strictObject({schemaVersion:je.literal(1),mode:je.enum(["local","remote"]),versionId:je.uuid(),generation:je.number().int().positive(),base:IO,context:fc,steps:je.array(xO).min(1).max(hc)}).refine(e=>ct(e)<=vO,"Segment exceeds its byte budget"),WD=(e,t,n)=>vp(e,t,`step:${n}`);function QD(e,t){let n={};for(let[s,c]of Object.entries(t))JSON.stringify(e[s])!==JSON.stringify(c)&&(n[s]=c);let r=e.attributes,i=t.attributes,a={},o=[];if(r&&typeof r=="object"&&!Array.isArray(r)&&i&&typeof i=="object"&&!Array.isArray(i)){for(let[s,c]of Object.entries(i))JSON.stringify(r[s])!==JSON.stringify(c)&&(a[s]=c);o=Object.keys(r).filter(s=>!Object.hasOwn(i,s)),delete n.attributes}return{context:n,removed:Object.keys(e).filter(s=>!Object.hasOwn(t,s)),attributes:a,removedAttributes:o}}function ZD(e){let t=AO.parse(e),n=structuredClone(t.context);return t.steps.map(r=>{for(let i of r.removed)delete n[i];if(n={...n,...r.context},Object.keys(r.attributes).length||r.removedAttributes.length){let i=je.record(je.string(),he).parse(n.attributes);for(let a of r.removedAttributes)delete i[a];n.attributes={...i,...r.attributes}}return{...r,input:ur.parse({...r.input,context:structuredClone(n)})}})}var _c=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},La=(e,t)=>new _c(e,t),OO=e=>({experiments:e.experiments,features:e.features});function PO(e,t=La){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=xc(e.growth.savedGroups),i=OO(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return wr(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let p=e.conditions[c.id];if(!p)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=Bs({id:c.id,name:c.id,type:"condition",cases:p.map(g=>({condition:g.condition,target:c.outputs[g.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");l=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let g=Bs({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=g.value,u=g.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let d=c.outputs[u]??(u==="value"?c.id:void 0);if(!d)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:d,...l===void 0?{}:{value:l}}}}}function CO(e,t,n,r=La){let i=fr.parse(e);if(i.evaluationMode!=="local")throw r("EVALUATION_MODE","Remote nodes are evaluated by Grow");if(i.expiresAt&&Date.parse(i.expiresAt)<=Date.now())throw r("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition");let a=PO(i,r),o=Tt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:s,onFeatureUsage:c,onExperimentViewed:u}=n,l={attributes:o,...s?{saveStickyBucketAssignmentDoc:d=>s(structuredClone(d))}:{},...c?{onFeatureUsage:(d,p)=>c(d,structuredClone(p))}:{},...u?{onExperimentViewed:(d,p)=>u(structuredClone(d),structuredClone(p))}:{},features:a.features,savedGroups:a.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return a.evaluate(t,l)}function Hf(e,t,n,r=La){let i=[],a=[],o=[],s=CO(e,t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(c){let u=i.findIndex(p=>p.next.attributeName===c.attributeName&&p.next.attributeValue===c.attributeValue),l=c.attributeName+"||"+c.attributeValue,d={expected:n.sticky[l]??null,next:c};u<0?i.push(d):i[u]=d},onExperimentViewed(c,u){u.inExperiment&&u.hashUsed&&!u.passthrough&&a.push(he.parse({key:c.key,variationId:u.variationId,keyUsed:u.key,hashAttribute:u.hashAttribute,hashValue:u.hashValue}))},onFeatureUsage(c,u){o.push(he.parse({feature:c,value:u.value,source:u.source,...u.ruleId?{ruleId:u.ruleId}:{}}))}},r);return{port:s.port,...s.value===void 0?{}:{value:s.value},sticky:i,exposures:a,features:o}}function oF(e,t,n,r=La){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,d=!1;for(let g=0;g<hc;g++){let m=a.get(u);if(!m||!gc(m))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||m.type!=="end"&&m.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let h=()=>({attributes:ia({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}),y,x;if(["condition","feature","split"].includes(m.type)||m.type==="offering"&&m.configuration.source==="feature")y=Hf(e,m.id,h(),r),m.type==="offering"&&(y.value={type:"offering_version",id:String(y.value)}),m.type==="condition"?x=y.port==="default"?m.default:m.cases[Number(y.port.slice(5))]?.target:m.type==="split"?x=y.port==="notParticipating"?m.notParticipating:m.routes[y.port]:(m.type==="feature"||m.type==="offering")&&(x=m.next);else if(y={port:"next",sticky:[],exposures:[],features:[]},(m.type==="entry"||m.type==="coupon"||m.type==="coupons")&&(x=m.next),m.type==="offering"&&m.configuration.source==="fixed"&&(y.value={type:"offering_version",id:m.configuration.versionId},x=m.next),m.type==="end"||m.type==="output"){let E=m.type==="end"?m.output:m.value;if(y=E?.type==="feature"?Hf(e,m.id,h(),r):{...y,port:"value",value:E?.type==="literal"?E.value:E?.type==="variable"?En({source:"variable",key:E.key,...E.path?{path:E.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},E&&(y.value===void 0||!mt(t.outputSchema,y.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let v=[...c,{nodeId:u,result:y}];if(ct({steps:v})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:y}),m.type==="feature"||m.type==="offering"||m.type==="coupon"||m.type==="coupons"){let E=m.type==="coupons"?m.couponIds.map(S=>({type:"reward",id:S})):m.type==="coupon"?{type:"reward",id:m.couponId}:y.value;if(E===void 0)throw r("INVALID_RESPONSE","Node output is missing");let A=Cn(m,{value:E});Vo(t.variables,m,A),Object.assign(o,A)}for(let E of y.sticky)s[`${E.next.attributeName}||${E.next.attributeValue}`]=structuredClone(E.next);if(m.type==="end"||m.type==="output"){d=!0;break}if(!x)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=x,l++}let p=a.get(u);return{steps:c,...!d&&p&&!gc(p)?{boundary:{nodeId:u,visit:l}}:{}}}import{z as wO}from"zod";var dF=wO.strictObject({document:Ut,configuration:fr.options[0]});export{Yc as a,Jf as b,TO as c,Zc as d,Xf as e,Xc as f,Wa as g,eh as h,RO as i,In as j,jO as k,NO as l,UO as m,zc as n,th as o,nh as p,MO as q,Qa as r,Za as s,Ya as t,Ja as u,ih as v,ah as w,tu as x,oh as y,ZO as z,kt as A,rP as B,nu as C,iP as D,ru as E,sh as F,iu as G,aP as H,oP as I,ch as J,au as K,Xa as L,sP as M,cP as N,o_ as O,rl as P,So as Q,ol as R,Fi as S,u_ as T,vo as U,l_ as V,sl as W,Io as X,wP as Y,d_ as Z,cl as _,EP as $,ul as aa,TP as ba,Lr as ca,Ao as da,Ui as ea,FP as fa,p_ as ga,f_ as ha,pl as ia,qP as ja,en as ka,dt as la,Mi as ma,h_ as na,$P as oa,GP as pa,KP as qa,HP as ra,WP as sa,QP as ta,ZP as ua,Vr as va,fl as wa,yl as xa,Co as ya,Qn as za,__ as Aa,b_ as Ba,y_ as Ca,S_ as Da,tn as Ea,Sl as Fa,vl as Ga,Il as Ha,xl as Ia,Bi as Ja,Al as Ka,Ol as La,Pl as Ma,Cl as Na,I_ as Oa,wl as Pa,x_ as Qa,A_ as Ra,O_ as Sa,El as Ta,wo as Ua,P_ as Va,$r as Wa,Tl as Xa,Rl as Ya,jl as Za,C_ as _a,Nl as $a,kl as ab,Kr as bb,Hr as cb,An as db,Li as eb,To as fb,w_ as gb,Fl as hb,Ul as ib,jo as jb,Ml as kb,Bl as lb,fC as mb,hC as nb,gC as ob,_C as pb,E_ as qb,bC as rb,yC as sb,No as tb,Ll as ub,T_ as vb,$l as wb,ko as xb,Gl as yb,Kl as zb,Hl as Ab,R_ as Bb,Wl as Cb,Do as Db,Ql as Eb,Yl as Fb,Jl as Gb,Mo as Hb,Zn as Ib,Yn as Jb,N_ as Kb,Vi as Lb,mt as Mb,Pn as Nb,Cn as Ob,Vo as Pb,bt as Qb,Ft as Rb,Jn as Sb,En as Tb,Xl as Ub,qi as Vb,qo as Wb,Qr as Xb,WC as Yb,QC as Zb,ct as _b,rn as $b,k_ as ac,zl as bc,D_ as cc,$i as dc,U_ as ec,M_ as fc,ed as gc,t1 as hc,n1 as ic,Zr as jc,r1 as kc,i1 as lc,B_ as mc,L_ as nc,an as oc,nd as pc,V_ as qc,q_ as rc,$o as sc,Go as tc,on as uc,cb as vc,Ko as wc,zn as xc,vd as yc,Rn as zc,Ub as Ac,Mb as Bc,xd as Cc,Yr as Dc,er as Ec,Ki as Fc,Ad as Gc,Od as Hc,Ho as Ic,Bb as Jc,Lb as Kc,Vb as Lc,Pd as Mc,Wo as Nc,Cd as Oc,wd as Pc,Ed as Qc,Hi as Rc,C1 as Sc,w1 as Tc,Td as Uc,Wi as Vc,qb as Wc,Xr as Xc,Qi as Yc,Rd as Zc,Gb as _c,Zo as $c,k1 as ad,Nd as bd,kd as cd,Kb as dd,Yo as ed,Fd as fd,Ud as gd,Yi as hd,Ji as id,Hb as jd,Wb as kd,Qb as ld,Md as md,Bd as nd,Ld as od,Vd as pd,qd,$d as rd,Gd as sd,Kd as td,zo as ud,Zb as vd,Yb as wd,zr as xd,Jb as yd,zb as zd,ey as Ad,es as Bd,Q1 as Cd,tr as Dd,ty as Ed,Wd as Fd,Qd as Gd,ny as Hd,Z1 as Id,Y1 as Jd,Zd as Kd,ry as Ld,J1 as Md,iy as Nd,Yd as Od,zi as Pd,iw as Qd,ea as Rd,Ht as Sd,ts as Td,rr as Ud,hw as Vd,cy as Wd,uy as Xd,Jd as Yd,gw as Zd,_w as _d,bw as $d,yw as ae,sn as be,Xd as ce,ns as de,Pw as ee,Cw as fe,rs as ge,dy as he,zd as ie,my as je,em as ke,tm as le,nm as me,is as ne,py as oe,na as pe,Bw as qe,ei as re,ra as se,im as te,as as ue,am as ve,om as we,os as xe,ia as ye,cs as ze,ti as Ae,oa as Be,ls as Ce,gy as De,cm as Ee,um as Fe,Xw as Ge,zw as He,eE as Ie,tE as Je,nE as Ke,rE as Le,_y as Me,iE as Ne,yt as Oe,lm as Pe,ds as Qe,ir as Re,ua as Se,mm as Te,ar as Ue,or as Ve,jn as We,Nn as Xe,sr as Ye,pm as Ze,by as _e,yy as $e,ms as af,fm as bf,hm as cf,gm as df,ni as ef,Sy as ff,ps as gf,_E as hf,bE as if,yE as jf,_m as kf,vy as lf,OE as mf,PE as nf,CE as of,Iy as pf,xy as qf,fs as rf,RE as sf,Ay as tf,Oy as uf,Sm as vf,UE as wf,hs as xf,gs as yf,wy as zf,_s as Af,bs as Bf,da as Cf,Ey as Df,Ty as Ef,JE as Ff,ma as Gf,eT as Hf,vm as If,tT as Jf,nT as Kf,Im as Lf,uT as Mf,Ss as Nf,ri as Of,ur as Pf,xm as Qf,lT as Rf,dT as Sf,Ry as Tf,ga as Uf,jy as Vf,Ny as Wf,ky as Xf,Ut as Yf,Pm as Zf,TT as _f,Dy as $f,Fy as ag,RT as bg,Uy as cg,Cm as dg,BT as eg,My as fg,Ly as gg,Vy as hg,qy as ig,$y as jg,Gy as kg,Ky as lg,Em as mg,Tm as ng,Hy as og,Wy as pg,Rm as qg,Ps as rg,Qy as sg,sR as tg,Os as ug,Zy as vg,cR as wg,uR as xg,lR as yg,jm as zg,ai as Ag,dr as Bg,Nm as Cg,vR as Dg,Dm as Eg,Cs as Fg,Fm as Gg,Um as Hg,Mm as Ig,Lm as Jg,Bm as Kg,ws as Lg,Yy as Mg,TR as Ng,Jy as Og,Vm as Pg,Xy as Qg,Mn as Rg,qm as Sg,Gm as Tg,Km as Ug,Hm as Vg,Wm as Wg,Qm as Xg,zy as Yg,Zm as Zg,eS as _g,tS as $g,nS as ah,rS as bh,Xm as ch,Rs as dh,ep as eh,iS as fh,aS as gh,GR as hh,KR as ih,HR as jh,np as kh,rp as lh,ip as mh,ap as nh,op as oh,sp as ph,WR as qh,QR as rh,sS as sh,cS as th,ZR as uh,YR as vh,Mt as wh,js as xh,uS as yh,si as zh,lS as Ah,zR as Bh,up as Ch,lp as Dh,ej as Eh,dp as Fh,mp as Gh,Ns as Hh,ks as Ih,pS as Jh,fS as Kh,hS as Lh,tj as Mh,Ds as Nh,pp as Oh,Fs as Ph,gS as Qh,fp as Rh,sj as Sh,hp as Th,Us as Uh,gp as Vh,ci as Wh,_p as Xh,cj as Yh,_S as Zh,Yj as _h,k as $h,bS as ai,yS as bi,SS as ci,Jj as di,N as ei,Xj as fi,vS as gi,iN as hi,aN as ii,oN as ji,ui as ki,Bs as li,vp as mi,bN as ni,yN as oi,Vs as pi,IS as qi,xS as ri,Ls as si,qs as ti,$s as ui,kN as vi,DN as wi,BN as xi,xp as yi,Ap as zi,WN as Ai,PS as Bi,QN as Ci,Pp as Di,fr as Ei,CS as Fi,wS as Gi,ES as Hi,ik as Ii,TS as Ji,RS as Ki,wp as Li,lk as Mi,jS as Ni,NS as Oi,dk as Pi,fk as Qi,kS as Ri,DS as Si,FS as Ti,US as Ui,MS as Vi,BS as Wi,bk as Xi,LS as Yi,yk as Zi,Sk as _i,Rp as $i,Ok as aj,Pk as bj,jp as cj,Np as dj,Nk as ej,kk as fj,VS as gj,Fk as hj,kp as ij,Uk as jj,Mk as kj,qS as lj,Gk as mj,$S as nj,Kk as oj,Hk as pj,ND as qj,kD as rj,DD as sj,LD as tj,hc as uj,vO as vj,gc as wj,IO as xj,xO as yj,AO as zj,WD as Aj,QD as Bj,ZD as Cj,_c as Dj,PO as Ej,CO as Fj,Hf as Gj,oF as Hj,dF as Ij};