@tinkerlandai/indiana-sdk 0.6.4 → 0.7.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 (53) hide show
  1. package/CHANGELOG.md +9 -4
  2. package/README.md +4 -4
  3. package/README.zh-CN.md +3 -3
  4. package/dist/{ai-usage-B4W5m4Ie.d.ts → ai-usage-BsrSG955.d.ts} +334 -518
  5. package/dist/chunk-3SONNXFG.js +1 -0
  6. package/dist/chunk-467Z5ISI.js +11 -0
  7. package/dist/{chunk-2EJSV6BA.js → chunk-4AWSZWZD.js} +1 -1
  8. package/dist/{chunk-5TEZEOHX.js → chunk-6MO6Y24B.js} +1 -1
  9. package/dist/chunk-HD74AAFS.js +1 -0
  10. package/dist/chunk-J4RHVU3W.js +1 -0
  11. package/dist/chunk-KQCTDXVD.js +17 -0
  12. package/dist/chunk-NOFNOHUI.js +1 -0
  13. package/dist/chunk-QO4YQLZ4.js +1 -0
  14. package/dist/chunk-RRII2DMC.js +1 -0
  15. package/dist/chunk-WCFVNF5D.js +1 -0
  16. package/dist/chunk-YAFMBXIE.js +4 -0
  17. package/dist/{client-OYRHOMUQ.js → client-F6UPJMHR.js} +1 -1
  18. package/dist/{configuration-sync-C2mytNwU.d.ts → configuration-sync-Bvd956GL.d.ts} +333 -25
  19. package/dist/controls-XG46TKUU.js +2 -0
  20. package/dist/funnel-runtime-host-26QI2W3S.js +1 -0
  21. package/dist/{funnel-runtime-start-sZ8ZCNlq.d.ts → funnel-runtime-start-ChVYbLzV.d.ts} +6655 -2785
  22. package/dist/iam.js +1 -1
  23. package/dist/index.d.ts +3634 -1485
  24. package/dist/index.js +1 -1
  25. package/dist/native-shell.js +1 -1
  26. package/dist/openrouter.d.ts +2 -3
  27. package/dist/openrouter.js +1 -1
  28. package/dist/page.d.ts +13 -13
  29. package/dist/page.js +1 -1
  30. package/dist/paywall-WKOHBYW7.js +1 -0
  31. package/dist/popup.d.ts +9 -16
  32. package/dist/popup.js +12 -12
  33. package/dist/react-native.d.ts +14 -14
  34. package/dist/react-native.js +1 -1
  35. package/dist/server.d.ts +4 -4
  36. package/dist/server.js +1 -1
  37. package/dist/src-UHLPVD6E.js +1 -0
  38. package/dist/visual.js +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-63BWE27V.js +0 -1
  41. package/dist/chunk-CB63JLGT.js +0 -1
  42. package/dist/chunk-D7YHFS6B.js +0 -4
  43. package/dist/chunk-HTRQPMJO.js +0 -11
  44. package/dist/chunk-ISUXYPYL.js +0 -1
  45. package/dist/chunk-QG3WUJG5.js +0 -1
  46. package/dist/chunk-RMJJOSVZ.js +0 -1
  47. package/dist/chunk-S2MSIA57.js +0 -17
  48. package/dist/chunk-VVSQKVE7.js +0 -1
  49. package/dist/funnel-runtime-host-NWS3URFA.js +0 -1
  50. package/dist/paywall-4XZ6NDMY.js +0 -1
  51. package/dist/src-WV6GZYWA.js +0 -1
  52. package/dist/{customer-page-B4FGCVpt.d.ts → customer-page-B4LkIr5q.d.ts} +4 -4
  53. package/dist/{screen-16d-xADb.d.ts → screen-iFngkxaL.d.ts} +185 -185
@@ -1,11 +0,0 @@
1
- import{a as _u,b as je,c as Vu,d as $u,g as Gu,h as nn,i as Ku}from"./chunk-ISUXYPYL.js";import{$ as Tu,Ca as Bu,Db as Fa,Ea as Lu,Gb as oi,L as ti,M as Iu,N as Au,Pb as to,Q as wu,Qb as Kn,R as ni,Rb as Vt,S as Cu,T as Pu,Tb as Ua,U as Da,V as jt,W as Ou,Z as Eu,a as Gn,b as oe,ba as Ru,c as Hi,ea as zi,f as bu,fa as pr,g as At,ga as ju,h as be,i as ja,ia as ku,j as Wi,ja as ri,k as Yt,la as Du,ma as Nu,oa as Fu,pb as qu,q as hn,r as Xi,s as xu,sa as Uu,ta as mr,tb as Ct,ua as Mu,vb as mt,wb as ii,xb as Na,zb as eo}from"./chunk-RMJJOSVZ.js";import{B as Ji,d as Qi,e as Zi,f as yu,g as Yi,i as Su,j as zr,l as he,m as wt,n as An,o as ka,p as dr,t as vu,v as ei}from"./chunk-S2MSIA57.js";import{z as Xt}from"zod";import{z as w}from"zod/v4";import{z as _g}from"zod/v4";var Hu=_g.registry();var{AppEnv:no}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:Wu}={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:yg}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:Sg}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(w),{ResetInterval:ai}=(()=>{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:vg}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:xg}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:Ig}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:Ag}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:wg}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(w),{BALANCE_BASES:Cg}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:Qu}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:Ma}=(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."})})}))(w),{ProductMetadataSchema:fr}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(w),{findDuplicate:Pg}={findDuplicate:t=>{let n=new Set;for(let r of t){if(n.has(r))return r;n.add(r)}}},{BillingInterval:wn}=(()=>{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:Ba}=(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')."})})}))(w),{withSpecDefault:si}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Hu),{COMMON:Zu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Og}={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:Eg}=(e=>({COMMON_SET:new Set(e)}))(Zu),{hasNoDuplicateCurrencies:Yu}={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:Ju}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:La}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(w),{Infinite:ro}={Infinite:"inf"},{TierBehavior:ci}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:io}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Xu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:Tg}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:oo}=(()=>{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:ao}=(()=>{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:qa}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:zu}=(()=>{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:Rg}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:jg}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Va}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(w),{ApiCreditTierSchema:el}=(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."})})}))(w),{VIOLATION_MESSAGES:kg}={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:tl}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(w),{ModelMarkupsSchema:$a}=((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()}))(w,tl),{additionalCurrencyPlanItemIssues:nl}={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=a=>(a.additional_currencies??[]).map(s=>s.currency.toLowerCase()),o=new Set(r.flatMap(i));o.size>0&&(r.every(s=>{let c=new Set(i(s));return c.size===o.size&&[...o].every(u=>c.has(u))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:Ga}=((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(a=>a.feature_id!==void 0||a.billing_method!==void 0||a.interval!==void 0||a.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)."})}))(w,io,wn,ai,La),{UpdatePlanItemParamsV1Schema:Dg}=((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})}))(w,Ga,ai),{FreeTrialDuration:ui}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:Ng}=((e,t)=>({laneParam:({schema:r,description:i})=>e({schema:t.array(r).optional(),defaultValue:[],description:i})}))(si,w),{findDuplicateInControls:Fg}={findDuplicateInControls:({controlKey:t,controls:n,rule:r})=>{let i=new Set;for(let[o,a]of n.entries()){let s=r.identityOf(a);if(s!==void 0){if(i.has(s))return{code:"custom",message:r.message,input:a[r.field],path:[t,o,r.field]};i.add(s)}}}},{featureIdIdentity:Ug}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:rl}={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:Mg}=((e,t)=>({usageAlertIdentity:r=>[r.feature_id??"",r.basis??e,t(r.filter),r.threshold_type,r.threshold].join("|")}))(Qu,rl),{RemovePlanLicenseSchema:Bg}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(w),{ApiStripePriceProcessorSchema:Lg}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(w),{ApiFeatureType:qg}=(()=>{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:Vg}=(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."})})}))(w),{ApiRevenueCatProductSchema:$g}=(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."})})}))(w),{TrialOnEnd:so}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:Gg}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:Kg}=(()=>{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:Hg}=(()=>{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:Wg}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(w),{UsageWindowScopeSchema:Qg}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(w),{EntInterval:il}=(()=>{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:Zg}=(()=>{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:Yg}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(w),{FreeTrialSchema:Jg}=((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()})}))(w,ui,so),{BillingType:Xg}=(()=>{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:Ka}=((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()}))}))(w,ro),{IgnoredFixedPriceMetadataSchema:zg}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(w),{BillWhen:eb}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:ol}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:tb}=((e,t,n)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(n).default(n.ProrateImmediately)})}))(w,oo,ao),{AllowanceType:nb}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:al}=((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()})}))(w,qa),{CreditDimensionBaseSchema:rb}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(w,Va),{flatCreditRateShape:sl}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(w),{CreditTierSchema:ib}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(w),{CreditMultiplierSchema:ob}=((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"})}))(w,Va),{idRegex:co}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:cl}={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:ab}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:sb}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:cb}=(()=>{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:ub}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:lb}={TierInfinite:"inf"},{CreateFreeTrialSchema:ul}=((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()})}))(w,ui,so),{ProductConfigParamsSchema:Ha}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(w,si,Wu),{CREATE_PRODUCT_EXAMPLE:db}={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:pb}=((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."})})}))(w,ui,so),{CreateProductSchema:jC}=(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("")})}))(w),{isUsageLimitBasisAlert:mb}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:ll}=(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()})}))(w),{RewardType:dl}=(()=>{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:pl}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:ml}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(w,pl),{RewardTriggerEvent:fb}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:hb}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:uo}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(w,Wu),{PurchaseLimitIntervalEnum:gb}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(w,yg),{DbSpendLimitSchema:Wa}=((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"]})}))(w,Sg),{USAGE_LIMIT_INTERVALS:bb}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(ai),{UsageLimitAnchorSchema:fl}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(w,vg),{UsageLimitFilterValueSchema:_b}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(w,Ig),{USAGE_ALERT_BASES:yb}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(Cg),{licensePatchIssues:Sb}=(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"]}]}}))(Pg),{BasePriceSchema:vb}=((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."})})}))(w,wn,Ba),{CURRENCY_CODES:xb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Zu,Og,Eg),{AllocatedBillingFieldSchema:hl}=((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'."})}))(w,Xu),{EntitlementExpirySchema:lo}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(w,zu),{CreditDimensionNameSchema:gl}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(w,Rg,jg),{ApiCreditMatchSchema:bl}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Va),{findCreditTierViolations:Ib}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(kg),{ApiCreditMultiplierSchema:Ab}=((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."})}))(w,bl),{ProviderMarkupsSchema:_l}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(w,tl),{planItemParamsIssues:wb}=((e,t,n,r,i)=>({planItemParamsIssues:a=>{let s=[],c=a.reset?.interval,u=a.price?.interval,l=a.reset?.interval_count??1,d=a.price?.interval_count??1;if(c&&u&&(String(c)!==String(u)||l!==d)&&a.price?.billing_method!==e.Prepaid&&s.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:a}),a.threshold_billing&&(!a.price||a.unlimited)&&s.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing}),a.expiry&&(a.price?.billing_method===e.Prepaid&&String(a.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:a.expiry}),a.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:a.expiry}),a.pooled&&s.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:a.expiry}),a.expiry.length<=0&&s.push({message:"expiry.length must be greater than 0",input:a.expiry})),a.price){a.threshold_billing&&a.price.billing_method!==e.UsageBased&&s.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing});let{amount:g,tiers:p}=a.price;a.threshold_billing&&p?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:a.threshold_billing});let h=a.price.billing_method===e.UsageBased&&a.price.allocated_billing===n.ProratedLegacy;a.proration&&a.price.billing_method!==e.Prepaid&&!h&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:a.proration});let y=typeof g=="number",A=Array.isArray(p)&&p.length>0;y||A?y&&A&&s.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:a.price}):s.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:a.price})}if(a.price?.tiers){let g=a.price.tiers.some(p=>p.flat_amount&&p.flat_amount>0);g&&a.price.tier_behavior!==r.VolumeBased&&s.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:a.price}),g&&a.price.tiers.length<=1&&s.push({message:"flat_amount is not supported on single-tier pricing.",input:a.price}),a.price.tiers.some(p=>p.flat_amount!=null&&p.flat_amount<0)&&s.push({message:"flat_amount must be 0 or greater.",input:a.price}),a.price?.tier_behavior===r.VolumeBased&&a.price?.billing_method!==e.Prepaid&&s.push({message:"volume-based pricing is only supported for prepaid features.",input:a.price}),a.price?.tiers.length===0?s.push({message:"tiers cannot be empty.",input:a.price}):a.included&&typeof a.price?.tiers[0].to=="number"&&a.price?.tiers[0].to<=a.included&&s.push({message:"tiers[0].to must be greater than included.",input:a.price})}for(let g of i(a.price))s.push({message:g,input:a.price});return s}}))(io,wn,Xu,ci,nl),{FreeTrialParamsV1Schema:Qa}=((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."})}))(w,ui,si),{duplicateCheck:Cb}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(Fg),{usageLimitIdentity:Za}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(rl),{ApiPriceProcessorsSchema:yl}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(w,Lg),{ApiFeatureV0Schema:Sl}=((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."})})}))(w,qg),{ApiRevenueCatPlanProcessorSchema:Pb}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(w,$g),{ApiFreeTrialV2Schema:Ob}=((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."})})}))(w,ui,so),{CustomerEligibilitySchema:Eb}=((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})})}))(w,Gg,Kg,Hg),{UsageWindowLimitSchema:kC}=((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()})}))(w,Wg,Qg,il,fl),{FeatureSchema:Tb}=((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()})}))(w,no,Zg,$a,Yg),{PriceCurrencyConfigSchema:vl}=((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()})}))(w,Ka),{UsagePriceConfigSchema:Rb}=((e,t,n,r,i,o)=>({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(o).optional()})}))(w,eb,Ka,wn,vl,ol),{graduatedCreditRateShape:xl}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(w,ib),{FeatureMarkupsOverrideSchema:jb}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(w,_l,$a),{usageAlertTargetLimitIdentity:kb}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(Za),{DiscountConfigSchema:Il}=((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()})}))(w,pl),{RewardEntitlementSchema:Al}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(w,lo),{UpdateRewardSchema:DC}=((e,t,n,r,i,o)=>({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(o).nullish()})}))(w,ll,dl,Il,ml,Al),{CreateRewardProgram:NC}=((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)})}))(w,fb,hb),{AutoTopupPurchaseLimitSchema:wl}=((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."})})}))(w,gb),{UsageLimitFilterSchema:Cl}=((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(o=>{let a=Object.keys(o.value).length;(a<1||a>r)&&o.issues.push({code:"custom",message:`filter.properties must have between 1 and ${r} keys`,input:o.value})})})}))(w,xg,_b,Ag),{UsageAlertBasisSchema:Db}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(w,yb),{refineCustomizePlanV1Schema:Pl}=(e=>({refineCustomizePlanV1Schema:(n,{includeItems:r=!0,includeFreeTrial:i=!0,includeUpdateItems:o=!0,includeLicenses:a=!0}={})=>{let s=["price",r&&"items","add_items","remove_items",o&&"update_items",i&&"free_trial","billing_controls",a&&"upsert_licenses",a&&"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(a)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||o&&u.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",o?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(Sb),{SUPPORTED_SET:Nb}=(e=>({SUPPORTED_SET:new Set(e)}))(xb),{ApiCreditDimensionBaseSchema:Fb}=((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."})})}))(w,bl),{refineGraduatedTiers:Ol}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(o=>o.to));for(let{index:o,message:a}of i)r.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(Ib),{ApiFeatureMarkupsOverrideSchema:Ub}=((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."})})}))(w,_l,$a),{AutoTopupPurchaseLimitParamsSchema:Mb}=((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."})})}))(wl,w),{DUPLICATE_CHECKS:Bb}=((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"})]}))(Cb,Ug,Za,Mg),{ApiPlanProcessorsSchema:Lb}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(w,Vg,Pb),{FixedPriceConfigSchema:qb}=((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})}))(w,wn,vl,Ka,zg),{CreditDimensionSchema:Vb}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(w,rb,sl,xl),{filterUnresolvableUsageLimitAlerts:$b}=((e,t,n)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:o})=>{let a=new Set(o.flatMap(s=>(s??[]).map(e)));return i.flatMap((s,c)=>t(s)&&!a.has(n(s))?[{index:c,usageAlert:s}]:[])}}))(Za,mb,kb),{CreateRewardSchema:FC}=((e,t,n,r,i,o)=>({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(o).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"})}))(w,ll,dl,Il,ml,Al),{AutoTopupSchema:Ya}=((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."})})}))(w,wl),{DbUsageLimitSchema:Ja}=((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."})})}))(w,bb,fl,Cl),{DbUsageAlertSchema:Xa}=((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(a=>{let{feature_id:s,threshold_type:c,threshold:u,basis:l,filter:d}=a.value;c==="remaining_percentage"&&u>100&&a.issues.push({code:"custom",input:u,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),l==="usage_limit"&&!s&&a.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&l!=="usage_limit"&&a.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(w,wg,Db,Qu,Cl),{isValidCurrencyCode:Gb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Nb),{ApiCreditDimensionSchema:Kb}=((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()])}))(w,Fb,el,Ol),{AutoTopupParamsSchema:Hb}=((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."})})}))(Ya,Mb),{findDuplicateBillingControlIssue:Wb}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(Bb),{CustomerBillingControlsSchema:za}=((e,t,n,r,i,o)=>({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(o).optional().meta({description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})})}))(w,Ya,Wa,Ja,Xa,Ma),{PriceSchema:Qb}=((e,t,n,r,i,o)=>({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:o.nullable()})}))(w,Xg,ci,qb,Rb,tb),{CreditSchemaItemBaseSchema:El}=((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()})}))(w,gl,Vb,ob),{GraduatedCreditSchemaItemSchema:Zb}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(El,xl),{UpdateProductSchema:UC}=((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()})}))(w,uo,za),{DbBillingControlsSchema:Yb}=((e,t,n,r,i,o)=>({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(o).nullish()})}))(w,Ya,Wa,Ja,Xa,Ma),{CurrencyCodeSchema:Tl}=((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')."})}))(w,Gb),{AdditionalCurrencyTierSchema:Jb}=((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"]})}))(w,Tl),{ApiCreditSchemaItemBaseSchema:Rl}=((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."})})}))(w,gl,Kb,Ab),{ApiFlatCreditSchemaItemSchema:Xb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Rl,w),{rejectDuplicateBillingControls:zb}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(Wb),{FlatCreditSchemaItemSchema:e_}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(El,sl),{ProductSchema:t_}=((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(()=>({}))})}))(w,no,uo,Yb,fr),{AdditionalCurrencyPriceSchema:n_}=((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."})})}))(w,Tl),{AdditionalCurrencyTierArraySchema:jl}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(w,Jb,Yu,Ju),{ApiGraduatedCreditSchemaItemSchema:r_}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Rl,w,el,Ol),{CustomerBillingControlsParamsSchema:po}=((e,t,n,r,i,o,a,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:o,description:"List of usage alert configurations per feature."}),overage_allowed:t({schema:a,description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})}).check(s)}))(w,Ng,Hb,Wa,Ja,Xa,Ma,zb),{CreditSchemaItemSchema:i_}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(w,e_,Zb),{PriceTierSchema:o_}=((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}))}))(w,lb,jl),{PlanBillingControlsParamsSchema:a_}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(r=>{let i=t({usageAlerts:r.value.usage_alerts??[],usageLimitLists:[r.value.usage_limits??[]]});for(let{index:o,usageAlert:a}of i)r.issues.push({code:"custom",message:`No usage limit on this plan matches the usage_limit alert for feature ${a.feature_id}`,input:a,path:["usage_alerts",o,"basis"]})})}))(po,$b),{AdditionalCurrencyPriceArraySchema:li}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(w,n_,Yu,Ju),{ApiUsageTierWithCurrenciesSchema:kl}=((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()}))}))(w,ro,jl),{ApiCreditSchemaItemSchema:s_}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(w,r_,Xb),{FeatureConfigOverrideSchema:Dl}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(w,i_,jb),{ProductItemConfigSchema:c_}=((e,t,n,r,i,o,a)=>({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:o.nullish(),feature_override:a.nullish()})}))(w,ol,oo,ao,al,lo,Dl),{BasePriceParamsSchema:mo}=((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."})}))(vb,si,w,li),{PlanItemPriceParamsSchema:u_}=((e,t,n,r,i,o,a)=>({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(o).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(w,li,kl,ci,wn,io,hl),{ApiFeatureOverrideSchema:Nl}=((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."})})}))(w,s_,Ub),{ApiPlanItemV1Schema:l_}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p,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(o).optional(),interval:e.enum(a).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(m).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:p.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(S=>{let j=S.value.reset?.interval,I=S.value.price?.interval,v=S.value.reset?.interval_count??1,$=S.value.price?.interval_count??1;if(j&&I&&(String(j)!==String(I)||v!==$)&&S.value.price?.billing_method!==s.Prepaid&&S.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:S.value}),S.value!==void 0&&S.value.price!==void 0&&S.value.price!==null){S.value.price.amount&&S.value.price.tiers&&S.value.price.tiers.length>0&&S.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:S.value});for(let we of y(S.value.price))S.issues.push({code:"custom",message:we,input:S.value.price})}})}))(w,Sl,ai,li,kl,ci,wn,io,hl,yl,Ba,qa,oo,ao,lo,Nl,nl),{EntitlementSchema:d_}=((e,t,n,r,i,o)=>({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:o.nullish()})}))(w,nb,il,zu,al,Dl),{ProductItemSchema:Fl}=((e,t,n,r,i,o,a,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(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(o).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(a).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(o).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})})}))(w,ab,sb,Sl,ro,cb,ub,o_,li,ci,c_),{ProductV2Schema:Ul}=((e,t,n,r,i,o,a)=>({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:o.optional(),metadata:a.optional()})}))(w,no,pb,Fl,uo,za,fr),{PlanItemParamsObjectSchema:p_}=((e,t,n,r,i,o,a,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:o}),proration:e.object({on_increase:e.enum(a).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})})}))(w,La,ai,si,u_,Tg,oo,ao,qa,lo,Nl),{FullProductWithoutLicensesSchema:MC}=((e,t,n,r,i,o)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(n),entitlements:t.array(r.extend({feature:i})),free_trial:o.nullish(),free_trials:t.array(o).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(t_,w,Qb,d_,Tb,Jg),{CreateProductItemParamsSchema:Ml}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))(Fl,La,w,ro),{CreatePlanItemParamsV1Schema:es}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(r=>{for(let{message:i,input:o}of t(r.value))r.issues.push({code:"custom",message:i,input:o})}).meta({title:"PlanItem",description:"Configuration for a feature item in a plan, including usage limits, pricing, and rollover settings."})}))(p_,wb),{LicenseCustomizeSchema:Bl}=((e,t,n,r)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(n).optional(),remove_items:e.array(r).optional()})}))(w,mo,es,Ga),{PlanLicenseParamsSchema:ts}=((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()})}))(w,Bl),{UpdateProductV2ParamsSchema:BC}=((e,t,n,r,i,o,a,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:o.nullish().meta({description:n.free_trial}),config:a.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})})}))(w,co,cl,Ml,ts,ul,Ha,po,fr),{CreatePlanParamsV1Schema:m_}=((e,t,n,r,i,o,a,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:o.optional().meta({description:"Free trial configuration. Customers can try this plan before being charged."}),config:a.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})})}))(w,co,mo,es,ts,Qa,Ha,a_,fr),{UpdatePlanParamsV1Schema:LC}=((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."})})}))(m_,w,mo,Qa,co),{CustomizePlanLicenseSchema:ns}=((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()})}))(w,Bl),{CreateProductV2ParamsSchema:qC}=((e,t,n,r,i,o,a,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:o.nullish().default(null).meta({description:n.free_trial}),config:a.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]})}))(w,co,cl,Ml,ts,ul,Ha,po,fr,db),{CustomizePlanV1BaseSchema:Ll}=((e,t,n,r,i,o,a,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:o.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:a.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."})})}))(w,mo,es,Ga,Dg,Qa,po,ns,Bg),{VariantCustomizeSchema:f_}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(Pl,Ll),{DiffedCustomizePlanV1Schema:VC}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(Pl,Ll),{ApiPlanV1Schema:$C}=((e,t,n,r,i,o,a,s,c,u,l,d,m,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(o).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:a.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:m.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."})})}))(w,li,wn,Ba,yl,l_,Lb,Ob,no,uo,za,fr,Eb,f_);import{z as C}from"zod";var h_=C.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),$l=C.enum(["single_use","continuous_use"]),rs=C.record(C.string(),C.union([C.string(),C.number(),C.boolean()]).transform(String).pipe(C.string())),ql=C.string().min(1).max(64).refine(e=>!e.includes("::")),Gl={credit_amount:C.number(),tier_behavior:C.never().optional(),tiers:C.never().optional()},Kl={credit_amount:C.never().optional(),tier_behavior:C.literal("graduated"),tiers:C.array(C.strictObject({to:C.union([C.number(),C.literal("inf")]),credit_amount:C.number()}))},g_=C.union([C.strictObject({match:rs,priority:C.number().int().optional(),...Gl}),C.strictObject({match:rs,priority:C.number().int().optional(),...Kl})]),b_=C.strictObject({match:rs,factor:C.number().positive().optional(),add:C.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Vl={metered_feature_id:C.string(),feature_amount:C.number().optional(),dimensions:C.record(ql,g_).optional(),multipliers:C.record(ql,b_).optional()},is=C.union([C.strictObject({...Vl,...Gl}),C.strictObject({...Vl,...Kl})]),ho=C.number().min(-100),Hl=C.record(C.string(),C.strictObject({markup:ho})).nullish(),go=C.record(C.string().regex(/.+\/.+/),C.strictObject({markup:ho.optional(),input_cost:C.number().min(0).optional(),output_cost:C.number().min(0).optional()})).nullish(),__=C.strictObject({default_markup:ho.optional(),provider_markups:Hl,model_markups:go}),os=C.strictObject({schema:C.array(is).optional(),markups:__.optional()}),y_=C.strictObject({filters:C.array(C.strictObject({property:C.string(),operator:C.string(),value:C.array(C.string())})),aggregate:C.strictObject({type:C.string(),property:C.string().nullable()}),usage_type:$l}),Wl=C.strictObject({schema:C.array(is).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:C.boolean().optional(),usage_type:$l.default("single_use").overwrite(()=>"single_use"),default_markup:ho.optional(),provider_markups:Hl}),as=Wl.safeExtend({schema:C.array(is).length(0)}),fo={id:h_,name:C.string().min(1),display:C.strictObject({singular:C.string().optional(),plural:C.string().optional()}).nullish(),event_names:C.array(C.string()).default([]),model_markups:go,stripe_meter:C.strictObject({id:C.string(),event_name:C.string()}).nullish(),stripe_product_id:C.string().nullish()},ss=e=>C.discriminatedUnion("type",[C.strictObject({...fo,...e,type:C.literal("boolean"),config:C.null()}),C.strictObject({...fo,...e,type:C.literal("metered"),config:y_}),C.strictObject({...fo,...e,type:C.literal("credit_system"),config:Wl}),C.strictObject({...fo,...e,type:C.literal("ai_credit_system"),config:as})]),HC=ss({}),S_=C.strictObject({id:C.boolean(),type:C.boolean(),usage_type:C.boolean()}),v_={internal_id:C.uuid(),org_id:C.uuid(),created_at:C.number(),env:C.enum(["sandbox","live"]),archived:C.boolean(),project_id:C.uuid(),environment_id:C.uuid(),revision:C.number().int().nonnegative(),update_rules:S_},Ql=ss(v_),WC=C.strictObject({rows:C.array(Ql).max(200),nextCursor:C.uuid().nullable()}),Zl=C.strictObject({features:C.array(Ql).max(500),limited:C.boolean()}),QC=C.union([ss({action:C.literal("save"),internal_id:C.uuid().nullable(),revision:C.number().int().nonnegative()}),C.strictObject({action:C.enum(["archive","restore","delete"]),internal_id:C.uuid(),revision:C.number().int().nonnegative()})]);import{z as hr}from"zod";var Yl=hr.number().int().min(0).max(1e8),di=hr.strictObject({kind:hr.enum(["graduated","volume"]),tiers:hr.array(hr.strictObject({upTo:hr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Yl,flatAmountMinor:Yl.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 cs(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?di.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let o of n.tiers){let a=o.upTo??1e4;if(n.kind==="volume"){if(t<=a){r=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function bo(e){return cs({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as R}from"zod";import{z as K}from"zod";import{z as rn}from"zod";import{z as gn}from"zod";var eP={plans:Gn,creditPacks:Gn,paidSeats:Gn,postpaid:Gn},Jl=gn.partialRecord(gn.enum(Gn),gn.number().int().min(1).max(1e8)),x_=gn.strictObject({currency:gn.enum(Gn),automaticTax:gn.boolean()}),I_=gn.strictObject({projectId:gn.uuid(),environmentId:gn.uuid()}),tP=I_.extend({settings:x_});var A_=rn.string().regex(/^[a-z][a-z0-9_]{0,63}$/),Xl=rn.number().int().min(0).max(1e4),us=rn.object({key:A_,featureId:rn.uuid(),planVersionId:rn.uuid(),includedQuantity:Xl,maximumQuantity:Xl,unitAmountCents:rn.number().int().min(0).max(1e8),currency:oe,currencyOptions:Jl.optional(),stripePriceId:rn.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:rn.array(rn.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:rn.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 Ce}from"zod";import{z as it}from"zod";var ls=it.object({days:it.number().int().min(1).max(730),cardRequired:it.boolean(),featureAllowances:it.record(it.uuid(),it.number().int().min(0).max(1e9)),creditAmounts:it.record(it.uuid(),be)}).strict(),ds=it.object({id:it.uuid(),planVersionId:it.uuid(),slot:it.string(),cardRequired:it.boolean(),status:it.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:it.iso.datetime().nullable(),endsAt:it.iso.datetime().nullable(),createdAt:it.iso.datetime()}).strict();var ps=Ce.object({group:Ce.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:Ce.enum(["main","addon"]).default("main")}).strict(),w_=Ce.enum(["immediate","end_of_cycle"]),C_=Ce.enum(["attach","change","cancel","resume","cancel_change"]),zl=Ce.object({id:Ce.uuid(),subscriptionId:Ce.uuid().nullable(),targetPlanVersionId:Ce.uuid().nullable(),action:C_,timing:w_,status:Ce.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:Ce.iso.datetime().nullable(),createdAt:Ce.iso.datetime()}),P_=Ce.object({id:Ce.uuid(),planVersionId:Ce.uuid(),planId:Ce.uuid(),basePlanId:Ce.uuid().nullable(),name:Ce.string(),group:Ce.string(),kind:Ce.enum(["main","addon"]),source:Ce.enum(["subscription","assignment","license","apple","google"]),status:Ce.string(),accessEnabled:Ce.boolean(),startsAt:Ce.iso.datetime().nullable(),endsAt:Ce.iso.datetime().nullable(),cancelAtPeriodEnd:Ce.boolean(),scheduledChange:zl.nullable(),trial:ds.nullable().optional()}),pP=Ce.object({customerId:Ce.uuid(),evaluatedAt:Ce.iso.datetime(),holdings:Ce.array(P_),changes:Ce.array(zl),trials:Ce.array(ds).optional()});var on=K.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"),SP=K.record(K.string().min(1).max(80),K.union([K.string().max(500),K.number().finite(),K.boolean(),K.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),ed=K.object({key:on,name:K.string().trim().min(1).max(80),description:K.string().trim().max(240),type:K.enum(["boolean","metered"]),usageType:K.enum(["consumable","non_consumable"]).optional()}),vP=ed.extend({...je.shape,id:K.string().min(1),archived:K.boolean(),createdAt:K.iso.datetime()}),td=K.object({amountCents:K.number().int().min(0).max(1e8),currency:oe,interval:K.enum(["free","month","year"]),currencyOptions:K.partialRecord(oe,K.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"),O_=K.object({featureId:K.string().min(1),allowance:K.number().int().min(0).max(1e9).nullable(),pooled:K.boolean().optional()}),nd=K.object({name:K.string().trim().min(1).max(80),description:K.string().trim().max(240),price:td,membership:ps.optional(),trial:ls.nullable().optional(),licenses:K.array(us).max(20).optional(),items:K.array(O_).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")}),xP=K.object({key:on,config:nd}),IP=je.extend({id:K.string().min(1),key:on,draft:nd,status:K.enum(["draft","published","archived"]),publishedVersionId:K.string().nullable(),isDefault:K.boolean(),updatedAt:K.iso.datetime()}),E_=ed.pick({key:!0,name:!0,type:!0}).extend({featureId:K.string(),allowance:K.number().int().min(0).max(1e9).nullable(),pooled:K.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"),rd=je.extend({id:K.string().min(1),planId:K.string().min(1),variant:K.object({basePlanId:K.uuid(),baseVersionId:K.uuid()}).nullable(),version:K.number().int().positive(),name:K.string(),description:K.string(),price:td,membership:ps.optional(),trial:ls.nullable().optional(),licenses:K.array(us).optional(),items:K.array(E_),publishedAt:K.iso.datetime()}).strict(),ms=K.object({startsAt:K.iso.datetime(),endsAt:K.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"),AP=je.extend({id:K.string(),customerId:K.string(),planVersionId:K.string(),assignedAt:K.iso.datetime(),source:K.literal("demo"),validity:ms.nullable().default(null),used:K.record(K.string(),K.number().int().min(0))}),wP=je.extend({id:K.string(),customerId:K.string(),at:K.iso.datetime(),message:K.string()});import{z as b}from"zod";import{z as ne}from"zod";var id={"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"}},EP=["zh-CN","zh-TW","zh-HK","en","ja","ko","es","fr","de","pt-BR","it","ru","vi","th","id","ar"];function fs(e){let t=Xi(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(o=>["TW","HK","MO"].includes(o))?"zh-Hant":"zh-Hans":n[0]??"en",i=id[r];return i?{locale:t,copy:i}:{locale:"en",copy:id.en}}function T_(e,t,n="zh-CN"){let r=Hi(t);return bu(e,t,fs(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function R_(e,t="zh-CN"){let n=fs(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e.percentOff/100):T_(e.amountOffCents,e.currency,n)}var od={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 ad(e,t="zh-CN",n="month"){let r=fs(t),i=R_(e.discount,r.locale),o=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0]??"en",s=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,c=e.duration.type==="repeating"&&n!=="month"?od[s]??od.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}",o).replace("{period}",u)}var NP=ne.enum(["draft","active","paused","archived"]),gr=ne.discriminatedUnion("type",[ne.object({type:ne.literal("percent"),percentOff:ne.number().int().min(1).max(100)}).strict(),ne.object({type:ne.literal("amount"),amountOffCents:ne.number().int().min(1).max(1e8),currency:oe}).strict()]),Jt=ne.discriminatedUnion("type",[ne.object({type:ne.literal("once")}).strict(),ne.object({type:ne.literal("repeating"),months:ne.number().int().min(1).max(36)}).strict(),ne.object({type:ne.literal("forever")}).strict()]),sd=ne.discriminatedUnion("type",[ne.object({type:ne.literal("all")}).strict(),ne.object({type:ne.literal("plans"),planIds:ne.array(ne.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),j_=ne.strictObject({firstPurchaseOnly:ne.boolean(),condition:An}),cd=ne.object({name:ne.string().trim().min(1).max(80),description:ne.string().max(500),discount:gr,duration:Jt,appliesTo:sd,eligibility:j_,selfClaimEnabled:ne.boolean().default(!1),startsAt:ne.iso.datetime().nullable(),endsAt:ne.iso.datetime().nullable(),totalLimit:ne.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ne.number().int().min(1).max(10),grantWindowHours:ne.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"]}),FP=ne.object({code:ne.string().trim().transform(e=>e.toUpperCase()).pipe(ne.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:ne.number().int().min(1).max(1e6).nullable(),expiresAt:ne.iso.datetime().nullable(),firstPurchaseOnly:ne.boolean(),minimumAmountCents:ne.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:oe.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function UP(){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 hs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function MP(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return hs(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),hs(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),hs(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 k_=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function BP(e,t="zh-CN"){return ad(e,t)}function LP(e){return k_(e)}function qP(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var pi=ne.object({id:ne.uuid(),couponId:ne.uuid(),status:ne.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ne.iso.datetime(),expiresAt:ne.iso.datetime(),coupon:ne.object({name:ne.string(),discount:gr,duration:Jt,appliesTo:sd}).strict()}).strict(),_o=ne.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var md=b.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),gs=b.string().regex(/^(0|[1-9]\d{0,14})$/),br=b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),D_=b.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),mi=D_,bn=be.refine(e=>/[1-9]/.test(e)),ft=b.iso.datetime({offset:!0}),Hn=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"))},N_=b.array(b.object({upTo:bn.nullable(),unitAmountMinor:md,flatAmountMinor:b.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&&Hn(t.upTo)>Hn(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),F_=b.discriminatedUnion("kind",[b.object({kind:b.literal("flat"),units:bn,unitAmountMinor:md}).strict(),b.object({kind:b.enum(["graduated","volume"]),units:bn,tiers:N_}).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"),U_=b.strictObject({interval:b.enum(["month","year"]),count:b.number().int().min(1).max(12),anchor:b.enum(["membership","calendar"])}),Cn=b.object({currency:oe,pricing:F_,billingCycle:U_.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function fd(e){return e.pricing.kind==="flat"&&Hn(e.pricing.units)>0n&&Hn(e.pricing.unitAmountMinor)===Hn(e.pricing.units)*BigInt(10**Hi(e.currency))}var ud={requestId:b.uuid(),productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:oe},hd=b.strictObject({interval:b.enum(["hour","day","week","month"]),intervalCount:b.number().int().min(1).max(12),limit:b.number().int().min(1).max(1e6)}),gd=b.discriminatedUnion("kind",[b.object({...ud,kind:b.literal("auto_topup"),threshold:ja,quantity:bn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:hd.optional()}).strict(),b.object({...ud,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:mi,maxOutstandingMinor:mi}).strict()]),ld={productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:oe},bd=b.discriminatedUnion("kind",[b.object({...ld,kind:b.literal("auto_topup"),threshold:ja,quantity:bn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:hd.optional(),purchaseAmountMinor:mi,purchaseUnits:bn}).strict(),b.object({...ld,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:mi,maxOutstandingMinor:mi,cashPrice:Cn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),yo=b.object({id:b.uuid(),terms:bd,status:b.enum(["prepared","active","revoked","blocked"]),createdAt:ft,acceptedAt:ft.nullable(),effectiveAt:ft.nullable(),revokedAt:ft.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"),_d=b.object({authorizationId:b.uuid(),terms:bd,setupUrl:b.url().nullable()}).strict(),yd=b.object({authorizationId:b.uuid(),accepted:b.literal(!0)}).strict(),Sd=b.object({authorizationId:b.uuid(),requestId:b.uuid()}).strict(),vd=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),anchor:b.enum(["billing_cycle","utc"]).optional(),basis:b.enum(["usage","credits"]),filter:Yt.optional(),limit:be.nullable(),thresholds:b.array(b.number().positive().max(1)).max(8),includedThresholds:b.array(b.number().positive().max(1)).max(8).optional(),absoluteThresholds:b.array(bn).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&&Hn(t)>Hn(i)}),"Notification thresholds must increase"),M_=vd.safeExtend({requestId:b.uuid()}),dd={control:b.literal("overage"),requestId:b.uuid(),internal_feature_id:b.uuid(),entityId:b.uuid().nullable()},B_=b.discriminatedUnion("action",[b.strictObject({...dd,action:b.literal("set"),allowed:b.boolean().nullable(),overageLimit:be.nullable(),skipOverageBilling:b.boolean()}),b.strictObject({...dd,action:b.literal("remove")})]),xd=b.union([M_,B_]),L_=b.strictObject({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),allowed:b.boolean().nullable(),overageLimit:be.nullable(),skipOverageBilling:b.boolean(),interval:b.enum(["day","week","month","year"]),startsAt:ft,endsAt:ft,used:b.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:b.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:b.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),q_=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),anchor:b.enum(["billing_cycle","utc"]).optional(),basis:b.enum(["usage","credits"]),filter:Yt.optional(),startsAt:ft,endsAt:ft,used:At,reserved:At,limit:be.nullable(),thresholds:b.array(b.number().positive().max(1)).max(8),notifiedThresholds:b.array(b.number().positive().max(1)).max(1024),includedThresholds:b.array(b.number().positive().max(1)).max(8).optional(),includedAllowance:b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:b.array(b.number().positive().max(1)).max(1024).optional(),absoluteThresholds:b.array(bn).max(8).optional(),notifiedAbsoluteThresholds:b.array(bn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||be.safeParse(e.used).success&&be.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),V_=b.object({authorizationId:b.uuid(),status:b.enum(["idle","pending","blocked"]),taskId:b.uuid().nullable(),invoiceId:b.uuid().nullable(),hostedInvoiceUrl:b.url().nullable(),purchaseCount:b.number().int().nonnegative(),purchaseWindowEndsAt:ft.nullable(),attemptCount:b.number().int().nonnegative(),failedAttemptCount:b.number().int().nonnegative(),suspendedAt:ft.nullable(),nextAttemptAt:ft.nullable(),failureReason:b.string().min(1).max(240).nullable()}).strict(),Id=b.object({internal_feature_id:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),bs=b.object({authorizations:b.array(yo).max(100),limits:b.array(vd).max(100),overages:b.array(L_).max(100).optional(),windows:b.array(q_).max(200),autoTopups:b.array(V_).max(100),limited:b.boolean()}).strict(),$_=b.object({id:b.uuid(),internal_feature_id:b.uuid(),productVersionId:b.uuid(),authorizationId:b.uuid(),entityId:b.uuid().nullable(),units:be,amountMinor:br,cashPrice:Cn}).strict(),fi=b.object({id:b.uuid(),sourceKind:b.enum(["product","usage","manual"]),providerInvoiceId:b.string().min(1).max(240).nullable(),status:b.enum(["accruing","open","pending","paid","failed","void"]),currency:oe,startsAt:ft.nullable(),endsAt:ft.nullable(),amountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:gs,paidAmountMinor:gs,refundedAmountMinor:gs,createdAt:ft,hostedInvoiceUrl:b.url().nullable(),adjustment:b.object({originalInvoiceId:b.uuid(),amountMinor:b.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:ft.nullable()}).strict().nullable(),lines:b.array($_).max(100),linesLimited:b.boolean()}).strict(),Ad=b.object({invoiceId:b.uuid(),accepted:b.literal(!0)}).strict(),wd=b.object({after:b.uuid().nullable(),limit:b.number().int().min(1).max(100)}).strict(),Cd=b.object({rows:b.array(fi).max(100),nextCursor:b.uuid().nullable()}).strict(),pd=b.strictObject({id:b.string(),coupon:b.string(),start:b.number().nonnegative(),end:b.number().nullable()}),G_=b.strictObject({subscriptionId:b.string(),customerId:b.string(),accountId:b.string(),sourceItems:b.array(b.strictObject({id:b.string(),price_id:b.string(),quantity:b.number().int(),discounts:b.array(pd).optional()})).max(100),items:b.array(b.strictObject({id:b.string(),price:b.string(),quantity:b.number().int(),discounts:b.array(b.strictObject({coupon:b.string().optional(),terms:b.strictObject({id:b.string(),name:b.string().optional(),percent_off:b.number().optional(),amount_off:b.number().optional(),currency:b.string().optional(),duration:b.enum(["once","forever","repeating"]),duration_in_months:b.number().optional()}).optional(),discount:b.string().optional(),receipt:pd.optional()})).max(20)})).max(100)}),Pd=b.strictObject({membershipId:b.uuid(),requestId:b.uuid(),grantIds:b.array(b.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Od=b.strictObject({membershipId:b.uuid(),operationId:b.uuid(),status:b.enum(["pending","effective"]),execution:G_.nullable(),grants:b.array(b.strictObject({id:b.uuid(),couponId:b.uuid(),name:b.string(),discount:gr,duration:Jt,startedAt:ft.nullable()})).max(20)});import{z as hi}from"zod";var gi=hi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),bi=hi.number().int().min(1).max(1e3),Wn=hi.object({cap:be.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:hi.number().positive().max(1e4).nullable(),cycles:hi.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var _s={key:on,name:R.string().trim().min(1).max(80),description:R.string().trim().max(240)},Ed=be.refine(e=>/[1-9]/.test(e)),So=R.array(R.object({currency:oe,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"),ys=R.strictObject({units:Ed,prices:R.array(R.strictObject({currency:oe,amountMinor:R.number().int().min(0).max(1e8),pricing:di.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&&cs({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"),K_=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:be.nullable(),reset:gi,resetCount:bi,pooled:R.boolean(),rollover:Wn.nullable().optional(),cashPrice:Cn.nullable().optional(),prepaidPrice:ys.optional(),feature_override:os.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 vs(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:be,reset:gi,resetCount:bi,rollover:Wn.nullable(),pooled:R.boolean(),feature_override:os.nullish(),cashPrice:Cn.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&fd(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")]),Ss=R.array(K_).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),Td=R.object({days:R.number().int().min(1).max(730),cardRequired:R.boolean(),allowances:Ss}).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"),Rd=R.object({key:on,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:So,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"),_i=R.discriminatedUnion("kind",[R.object({..._s,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:So,allowances:Ss,trial:Td.nullable(),licenses:R.array(Rd).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({..._s,kind:R.literal("topup"),interval:R.literal("one_time"),prices:So,internal_feature_id:R.uuid(),amount:Ed,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")]),vo=R.object({interval:R.enum(["free","week","month","year","one_time"]).optional(),intervalCount:R.number().int().min(1).max(156).nullable().optional(),prices:So.optional(),allowances:R.object({upsert:Ss,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:Td.nullable().optional(),licenses:R.array(Rd).max(20).optional()}).strict(),jd=R.object({..._s,kind:R.literal("variant"),baseProductVersionId:R.uuid(),overrides:vo}).strict(),aO=R.union([_i,jd]);function sO(e,t){let n=jd.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...o}=n.overrides,a=new Map(e.allowances.map(c=>[c.internal_feature_id,c]));for(let c of r?.remove??[])if(!a.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])a.delete(c.internal_feature_id);for(let c of r?.upsert??[])a.set(c.internal_feature_id,c);let s={...structuredClone(e),...structuredClone(o),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...a.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),_i.parse(s)}function cO(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)),o=t.allowances.filter(s=>JSON.stringify(r.get(s.internal_feature_id))!==JSON.stringify(s)),a=e.allowances.filter(s=>!i.has(s.internal_feature_id)).map(s=>s.internal_feature_id);return(o.length||a.length)&&(n.allowances={upsert:o,remove:a}),vo.parse(n)}var uO=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(),H_=Ul.and(R.object({internal_id:R.uuid(),revision:R.number().int().nonnegative(),licenses:R.array(ns)})),lO=R.strictObject({rows:R.array(H_).max(200),nextCursor:R.uuid().nullable()}),dO=R.object({groups:R.array(R.object({id:R.uuid(),name:R.string(),defaultProductVersionId:R.uuid().nullable()}).strict()).max(500),features:Zl.shape.features,products:R.array(R.object({id:R.uuid(),productId:R.uuid(),version:R.number().int().positive(),configuration:_i,baseProductVersionId:R.uuid().nullable()}).strict()).max(500),limited:R.boolean()}).strict();function vs(e,t,n){let r=a=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(a))throw new Error("Invalid quantity");let[s,c=""]=a.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 o=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(o?"."+o:"")}var hO=Xt.object({requestId:Xt.uuid(),baseProductVersionId:Xt.uuid(),name:Xt.string().trim().min(1).max(80),description:Xt.string().trim().max(240),overrides:vo}).strict(),gO=Xt.object({productId:Xt.uuid(),productVersionId:Xt.uuid(),bindingStatus:Xt.enum(["ready","requires_binding"]),missingCurrencies:Xt.array(Xt.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();var Dd="X-Indiana-Protocol",W_="X-Indiana-SDK-Version",_O="X-Indiana-Supported-Protocols",kd={stableSupportMonths:12,retirementNoticeDays:180,documentation:"/docs/release-notes#support-policy"},Q_={current:"0.6",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"}]}]},Nd=/^(?:0\.(?:0|[1-9]\d*)|[1-9]\d*)$/,Z_=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Fd(e){let t=Z_.exec(e);return!t?.[1]||!t[2]?null:t[1]==="0"?`0.${t[2]}`:t[1]}var Is=e=>/^[1-9]\d*$/.test(e);function Y_(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 xs=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 yO(e){let t=[],n=new Set;for(let r of e.releases){let i=r.protocol;(!Nd.test(i)||n.has(i))&&t.push(`Invalid/duplicate protocol ${i}`),n.add(i),(r.firstReleasedAt===null?i!==e.current:!xs(r.firstReleasedAt))&&t.push(`${i}: invalid first release date`),r.noticePublishedAt!==null&&!xs(r.noticePublishedAt)&&t.push(`${i}: invalid notice date`),r.sunsetAt!==null&&!xs(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 o=new Set;for(let a of r.baselines)(Fd(a.version)!==i||o.has(a.version))&&t.push(`${i}: invalid/duplicate baseline ${a.version}`),o.add(a.version),(!/^sha512-[A-Za-z0-9+/]{86}==$/.test(a.integrity)||!/^[a-f0-9]{64}$/.test(a.sha256))&&t.push(`${i}: unpinned baseline ${a.version}`);if(Is(i)&&r.sunsetAt!==null){let a=e.releases.filter(s=>s.firstReleasedAt!==null&&Is(s.protocol)&&Number(s.protocol)>Number(i)).sort((s,c)=>Date.parse(s.firstReleasedAt)-Date.parse(c.firstReleasedAt))[0];a?Date.parse(r.sunsetAt)<Y_(a.firstReleasedAt,kd.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)<kd.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 Qn=class extends Error{constructor(n,r,i=400){super(r);this.code=n;this.status=i}code;status};function SO(e,t=Q_,n=Date.now()){let r=e.get(Dd)??t.unversioned;if(!Nd.test(r))throw new Qn("INVALID_PROTOCOL_VERSION","Invalid Indiana protocol version");let i=t.releases.find(a=>a.protocol===r);if(!i)throw new Qn("UNSUPPORTED_PROTOCOL_VERSION","Indiana protocol version is not supported");if(!Is(r)&&r!==t.current)throw new Qn("UNSUPPORTED_PROTOCOL_VERSION","Only the current pre-1.0 Indiana protocol is supported");if(i.sunsetAt&&n>=Date.parse(i.sunsetAt))throw new Qn("PROTOCOL_RETIRED","Indiana protocol version has retired; follow the published migration notice",410);let o=e.get(W_);if(o!==null&&Fd(o)!==r)throw new Qn("INVALID_PROTOCOL_VERSION","SDK version and protocol version do not match");return i}function vO(e,t=Date.now()){let n={[Dd]: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 $e}from"zod";var J_=$e.object({minAccountAgeDays:$e.number().int().min(0).max(3650),paymentStatus:$e.enum(["all","unpaid","paid"])}),X_=$e.object({percentOff:$e.number().int().min(1).max(100),redemptionWindowHours:$e.number().int().min(1).max(2160)}),z_=$e.object({title:$e.string().trim().min(1).max(80),description:$e.string().trim().min(1).max(240),buttonLabel:$e.string().trim().min(1).max(30)}),ey=$e.object({name:$e.string().trim().min(1).max(80),audience:J_,offer:X_,popup:z_}),wO=ey.extend({id:$e.string().min(1),projectId:$e.string().min(1),environment:_u,status:$e.enum(["draft","active","paused"]),updatedAt:$e.iso.datetime()}),CO=je.extend({id:$e.string().min(1),externalUserId:$e.string().min(1),name:$e.string().min(1),email:$e.union([$e.email(),$e.literal("")]),createdAt:$e.iso.datetime(),paymentStatus:$e.enum(["unpaid","paid"]),stripeCustomerId:$e.string().nullable()});import{z as Pn}from"zod";var Ud=Pn.strictObject({itemKey:Pn.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:Pn.uuid(),includedAmount:Pn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Pn.number().int().min(0).max(1e4),terms:ys,pricing:di.optional(),unitAmountMinor:Pn.number().int().min(0).max(1e8),productId:Pn.string().min(1).max(255).nullable(),priceId:Pn.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{vs(e.includedAmount,e.terms.units,e.quantity),bo({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 H}from"zod";var As=H.object({id:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),productId:H.string().min(1).max(255),priceId:H.string().min(1).max(255),enabled:H.boolean()}).strict(),DO=H.object({productId:H.uuid(),name:H.string(),environment:H.enum(["sandbox","live"]),versions:H.array(H.object({id:H.uuid(),version:H.number().int().positive(),configuration:_i}).strict()),connections:H.array(H.object({id:H.uuid(),accountId:H.string()}).strict()),bindings:H.array(As),seatBindings:H.array(As.extend({key:H.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:H.array(As.extend({internal_feature_id:H.uuid()}).strict()),limited:H.boolean()}).strict(),NO=H.discriminatedUnion("action",[H.strictObject({action:H.literal("bind_feature"),requestId:H.uuid(),productId:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),internal_feature_id:H.uuid(),priceId:H.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}),H.strictObject({action:H.literal("disable_feature"),productId:H.uuid(),bindingId:H.uuid()}),H.object({action:H.literal("bind_seat"),requestId:H.uuid(),productId:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),key:H.string().regex(/^[a-z][a-z0-9_]{0,63}$/),priceId:H.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),H.object({action:H.literal("disable_seat"),productId:H.uuid(),bindingId:H.uuid()}).strict(),H.object({action:H.literal("bind"),requestId:H.uuid(),productId:H.uuid(),productVersionId:H.uuid(),connectionId:H.uuid(),currency:H.string().regex(/^[A-Z]{3}$/),priceId:H.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),H.object({action:H.literal("disable"),productId:H.uuid(),bindingId:H.uuid()}).strict()]);import{z as me}from"zod";var Md=me.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Bd=me.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),yi=me.enum(["apple","google"]),ty=me.strictObject({id:me.uuid(),productVersionId:me.uuid(),priceId:me.uuid(),connectionId:yi,provider:yi,namespace:me.string().min(1).max(255),currency:oe,productId:Md,basePlanId:Bd.nullable(),enabled:me.boolean()}),BO=me.strictObject({productId:me.uuid(),publicId:me.string().min(1),name:me.string().min(1).max(80),environment:me.enum(["sandbox","live"]),versions:me.array(me.strictObject({id:me.uuid(),version:me.number().int().positive(),prices:me.array(me.strictObject({id:me.uuid(),currency:oe,amount:me.number().nonnegative(),interval:me.string().nullable()})).max(50),recurring:me.boolean()})).max(100),connections:me.array(me.strictObject({id:yi,provider:yi,applicationId:me.string().min(1).max(255)})).max(2),bindings:me.array(ty).max(500),limited:me.boolean()}),LO=me.discriminatedUnion("action",[me.strictObject({action:me.literal("bind"),requestId:me.uuid(),productId:me.uuid(),productVersionId:me.uuid(),priceId:me.uuid(),connectionId:yi,storeProductId:Md,basePlanId:Bd.nullable()}),me.strictObject({action:me.literal("disable"),productId:me.uuid(),bindingId:me.uuid()})]);import{z as _e}from"zod";var Zn=_e.iso.datetime({offset:!0}),Ld=be.refine(e=>/[1-9]/.test(e)),qd=_e.strictObject({interval:gi.exclude(["lifetime"]),count:bi}),ny=_e.strictObject({action:_e.literal("create"),requestId:_e.uuid(),internal_feature_id:_e.uuid(),entityId:_e.uuid().nullable(),amount:Ld.nullable(),expiresAt:Zn.nullable(),reset:qd.nullable(),rollover:Wn.nullable(),nextResetAt:Zn.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"),Vd=_e.discriminatedUnion("action",[ny,_e.strictObject({action:_e.literal("update"),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative(),amount:Ld.nullable(),expiresAt:Zn.nullable(),rollover:Wn.nullable(),nextResetAt:Zn.nullable()}),_e.strictObject({action:_e.enum(["add","subtract","set_remaining"]),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative(),amount:be}),_e.strictObject({action:_e.literal("revoke"),requestId:_e.uuid(),grantId:_e.uuid(),revision:_e.number().int().nonnegative()})]),ws=_e.strictObject({id:_e.uuid(),internal_feature_id:_e.uuid(),entityId:_e.uuid().nullable(),amount:be.nullable(),reset:qd.nullable(),rollover:Wn.nullable(),nextResetAt:Zn.nullable(),startsAt:Zn,expiresAt:Zn.nullable(),revision:_e.number().int().nonnegative(),revoked:_e.boolean(),available:At,held:At,spent:At}),$d=_e.strictObject({customerId:_e.uuid(),after:_e.uuid().nullable(),limit:_e.number().int().min(1).max(100)}),Gd=_e.strictObject({rows:_e.array(ws).max(100),nextCursor:_e.uuid().nullable()});import{z as W}from"zod";var an=W.iso.datetime({offset:!0}),Kd=W.strictObject({invoiceId:W.uuid(),after:W.string().min(1).max(180).nullable(),limit:W.number().int().min(1).max(100)}),ry=W.strictObject({kind:W.literal("product"),key:W.string(),productVersionId:W.uuid(),productName:W.string(),itemKey:W.string(),entityId:W.uuid().nullable(),quantity:W.number().int().positive(),subtotalMinor:W.string().regex(/^-?\d+$/),discountMinor:W.string().regex(/^\d+$/),taxMinor:W.string().regex(/^-?\d+$/).nullable(),totalMinor:W.string().regex(/^-?\d+$/),startsAt:an.nullable(),endsAt:an.nullable(),providerLineId:W.string().nullable(),providerItemId:W.string()}),Hd=W.strictObject({invoice:fi,items:W.array(W.discriminatedUnion("kind",[ry,W.strictObject({kind:W.literal("invoice_credit"),key:W.string(),internal_feature_id:W.uuid(),internal_credit_feature_id:W.uuid(),name:W.string(),units:be,reserved:be,amountMinor:br,grossAmountMinor:br,creditsAppliedMinor:br,properties:Yt,cashPrice:Cn,providerItemId:W.string().nullable(),creditProviderItemId:W.string().nullable()}),W.strictObject({kind:W.literal("usage"),key:W.string(),internal_feature_id:W.uuid(),name:W.string(),units:be,reserved:be,amountMinor:br,cashPrice:Cn})])).max(100),nextCursor:W.string().min(1).max(180).nullable()}),iy=W.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Cs=W.strictObject({from:an,to:an,entityId:W.uuid().optional(),snapshotAt:an.nullable(),after:W.strictObject({at:an,id:W.uuid(),position:W.number().int().nonnegative()}).nullable(),limit:W.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"),Wd=W.strictObject({customerId:W.uuid(),entityId:W.uuid().nullable(),from:an,to:an,snapshotAt:an,totals:W.array(W.strictObject({internal_credit_feature_id:W.uuid(),name:W.string(),consumed:At,refunded:At,net:iy})).max(1e3),rows:W.array(W.strictObject({operationId:W.uuid(),position:W.number().int().nonnegative(),kind:W.enum(["consume","confirm","refund"]),originalId:W.uuid().nullable(),occurredAt:an,internal_feature_id:W.uuid(),entitlementName:W.string(),sourceId:W.uuid(),internal_credit_feature_id:W.uuid(),creditName:W.string(),units:Au,amount:At,pricing:W.array(Iu).max(12),properties:Yt})).max(100),nextCursor:Cs.shape.after});import{z as kt}from"zod";var zO=kt.enum(["billing.updated","invoice.finalized","billing.auto_topup_failed","billing.auto_topup_succeeded","billing.conflict","billing.purchase","billing.refund","usage.consume","usage.confirm","usage.refund","usage.limit","usage.alert","usage.allowance"]),Qd=kt.object({operationId:kt.uuid(),windowId:kt.uuid(),customerId:kt.uuid(),entityId:kt.uuid().nullable(),internal_feature_id:kt.uuid(),entitlementKey:Wi,basis:kt.enum(["usage","credits"]),interval:kt.enum(["day","week","month","year"]),filter:Yt,startsAt:kt.iso.datetime({offset:!0}),endsAt:kt.iso.datetime({offset:!0}),limit:be.refine(e=>/[1-9]/.test(e)),used:At,reserved:At,threshold:kt.number().positive().max(1)}).strict(),eE=Qd.omit({threshold:!0,limit:!0}).extend({alertThreshold:be.refine(e=>/[1-9]/.test(e)),limit:be.nullable()}),tE=Qd.omit({limit:!0}).extend({includedAllowance:kt.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z as X}from"zod";var Yd=X.object({customerId:X.uuid()}).strict(),Jd=X.discriminatedUnion("action",[X.object({customerId:X.uuid(),requestId:X.uuid(),action:X.literal("assign"),poolId:X.uuid(),memberCustomerId:X.uuid()}).strict(),X.strictObject({customerId:X.uuid(),requestId:X.uuid(),action:X.literal("assign_entity"),poolId:X.uuid(),entityId:X.uuid()}),X.object({customerId:X.uuid(),requestId:X.uuid(),action:X.literal("release"),poolId:X.uuid(),slotId:X.uuid()}).strict()]),Si=X.number().int().nonnegative(),Ps=X.iso.datetime({offset:!0}),Os=X.strictObject({internalId:X.uuid(),id:X.string(),name:X.string().nullable(),version:X.number().int().positive()}),Zd=X.enum(["active","past_due"]),Es=X.strictObject({customerId:X.uuid(),licenses:X.array(X.strictObject({id:X.uuid(),linkId:X.uuid(),parent:X.strictObject({customerProductId:X.uuid(),status:Zd,product:Os}),product:Os,planLicense:X.strictObject({id:X.uuid(),prepaidOnly:X.boolean(),isCustom:X.boolean()}).nullable(),granted:Si,included:Si,paidQuantity:Si,usage:Si,remaining:Si,createdAt:Ps}).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:X.array(X.strictObject({id:X.uuid(),linkId:X.uuid(),status:Zd,product:Os,entity:X.strictObject({internalId:X.uuid(),id:X.string().nullable(),name:X.string().nullable()}).nullable(),beneficiary:X.strictObject({internalId:X.uuid(),id:X.string().nullable(),name:X.string().nullable()}).nullable(),startedAt:Ps.nullable(),endedAt:Ps.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:X.boolean()});import{z as On}from"zod";var oy=On.object({name:On.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:On.string().trim().max(63).regex(/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,"\u9879\u76EE\u6807\u8BC6\u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26")}),Xd=On.object({description:On.string().trim().max(240)}),aE=On.object({project:oy.extend({id:On.string().min(1)}),environments:On.object({sandbox:Xd,live:Xd})});import{z as zd}from"zod";var _r={funnelId:zd.uuid().optional(),funnelVersionId:zd.uuid().optional()};import{z as qe}from"zod";import{z as Pe}from"zod";import{z as Ne}from"zod";var ay=Ne.discriminatedUnion("action",[Ne.strictObject({action:Ne.literal("create"),couponId:Ne.uuid(),productBindingId:Ne.uuid(),storeOfferId:Ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ne.enum(["introductory","promotional"])}),Ne.strictObject({action:Ne.literal("set_enabled"),id:Ne.uuid(),revision:Ne.number().int().nonnegative(),enabled:Ne.boolean()})]),sy=Ne.array(Ne.strictObject({id:Ne.uuid(),couponId:Ne.uuid(),productBindingId:Ne.uuid(),storeOfferId:Ne.string().min(1).max(255).nullable(),storeOfferType:Ne.enum(["introductory","promotional"]),enabled:Ne.boolean(),revision:Ne.number().int().nonnegative()})).max(500),En=Ne.strictObject({offerKind:Ne.enum(["none","introductory","promotional"]),offerId:Ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ne.number().int().min(0).max(1e8),trialDays:Ne.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"})}),ep=Ne.record(Ne.uuid(),En).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function cy(e,t){if(e.nativeOffers!==void 0)return ep.parse(e.nativeOffers)[t]}function uy(e,t,n,r){return En.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 Ts=Pe.object({type:Pe.literal("native_purchase"),receiptId:Pe.uuid(),orderId:Pe.uuid(),productVersionId:Pe.uuid(),provider:Pe.enum(["apple","google"]),productId:Pe.string().min(1).max(255),productKind:Ru,replacement:Pe.strictObject({sourceOrderId:Pe.uuid(),sourceProductId:Pe.string().min(1).max(255),policy:Pe.enum(["apple_store","google_full_price"]),sourceAccountTokens:Pe.array(Pe.uuid()).max(50)}).nullable(),appAccountToken:Pe.uuid().optional(),obfuscatedAccountId:Pe.string().min(1).max(64).optional(),obfuscatedProfileId:Pe.uuid().optional(),basePlanId:Pe.string().min(1).max(255).optional(),offerId:Pe.string().min(1).max(255).optional(),offerKind:Pe.enum(["none","introductory","promotional"]),currency:oe,catalogAmountMinor:Pe.number().int().nonnegative().max(1e8),discountMinor:Pe.number().int().nonnegative().max(1e8),trialDays:Pe.number().int().min(1).max(730).nullable(),seatBundle:Pe.array(Pe.strictObject({key:Pe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Pe.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Pe.strictObject({offerId:Pe.string().min(1).max(255),keyId:Pe.string().min(1).max(255),nonce:Pe.uuid(),signature:Pe.string().min(1).max(1024),timestamp:Pe.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 ue}from"zod/v4";import{z as ly}from"zod/v4";var dy=ly.registry(),{BillingInterval:tp}=(()=>{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:py}=(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')."})})}))(ue),{withSpecDefault:my}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(dy),{COMMON:np}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:fy}={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:hy}=(e=>({COMMON_SET:new Set(e)}))(np),{hasNoDuplicateCurrencies:rp}={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:ip}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:gy}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(ue),{Infinite:by}={Infinite:"inf"},{TierBehavior:_y}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:op}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:yy}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Sy}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:vy}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:xy}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(ue),{ApiCreditTierSchema:ap}=(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."})})}))(ue),{VIOLATION_MESSAGES:Iy}={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:sp}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(ue),{ModelMarkupsSchema:Ay}=((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()}))(ue,sp),{InvoiceUsageEntrySchema:wy}=(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()}))(ue),{AttachDiscountSchema:cp}=(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."})}))(ue),{CustomLineItemSchema:Cy}=(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."})})}))(ue),{UnixMsTimestampSchema:Py}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(ue),{CreateInvoicePreviewLineSchema:Oy}=(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()})}))(ue),{ReissueInvoiceParamsSchema:Rs}=(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."})})}))(ue),{InvoiceModeParamsSchema:Tn}=(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."})}))(ue),{InvoiceTemplateSchema:Ey}=(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."})})}))(ue),{BasePriceSchema:Ty}=((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."})})}))(ue,tp,py),{CURRENCY_CODES:Ry}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(np,fy,hy),{ApiPriceProcessorsSchema:up}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(ue,gy),{AllocatedBillingFieldSchema:jy}=((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'."})}))(ue,yy),{CreditDimensionNameSchema:ky}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(ue,Sy,vy),{ApiCreditMatchSchema:lp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(xy),{findCreditTierViolations:Dy}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(Iy),{ApiCreditMultiplierSchema:Ny}=((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."})}))(ue,lp),{ProviderMarkupsSchema:Fy}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(ue,sp),{InvoiceFeatureQuantitySchema:dp}=((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."})}))(ue,op,wy),{CreateInvoicePreviewSchema:js}=((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()})}))(ue,Oy),{SUPPORTED_SET:Uy}=(e=>({SUPPORTED_SET:new Set(e)}))(Ry),{ApiCreditDimensionBaseSchema:My}=((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."})})}))(ue,lp),{refineGraduatedTiers:pp}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(o=>o.to));for(let{index:o,message:a}of i)r.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(Dy),{ApiFeatureMarkupsOverrideSchema:By}=((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."})})}))(ue,Fy,Ay),{isValidCurrencyCode:Ly}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Uy),{ApiCreditDimensionSchema:qy}=((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()])}))(ue,My,ap,pp),{CurrencyCodeSchema:mp}=((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')."})}))(ue,Ly),{AdditionalCurrencyTierSchema:Vy}=((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"]})}))(ue,mp),{ApiCreditSchemaItemBaseSchema:fp}=((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."})})}))(ue,ky,qy,Ny),{ApiFlatCreditSchemaItemSchema:$y}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(fp,ue),{AdditionalCurrencyPriceSchema:Gy}=((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."})})}))(ue,mp),{AdditionalCurrencyTierArraySchema:Ky}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(ue,Vy,rp,ip),{ApiGraduatedCreditSchemaItemSchema:Hy}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(fp,ue,ap,pp),{AdditionalCurrencyPriceArraySchema:hp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(ue,Gy,rp,ip),{ApiUsageTierWithCurrenciesSchema:Wy}=((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()}))}))(ue,by,Ky),{ApiCreditSchemaItemSchema:Qy}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(ue,Hy,$y),{BasePriceParamsSchema:Zy}=((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."})}))(Ty,my,ue,hp),{PlanItemPriceParamsSchema:Yy}=((e,t,n,r,i,o,a)=>({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(o).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(ue,hp,Wy,_y,tp,op,jy),{ApiFeatureOverrideSchema:Jy}=((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."})})}))(ue,Qy,By),{InvoiceBasePriceParamsSchema:gp}=((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()}))(Zy,up),{InvoiceItemPriceParamsSchema:Xy}=((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()}))(Yy,up),{InvoiceLicenseQuantitySchema:zy}=((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()}))(ue,gp,dp),{InvoiceCustomizeItemSchema:eS}=((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()}))(ue,Xy,Jy),{InvoiceCustomizeSchema:tS}=((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."})}))(ue,gp,eS),{InvoicePlanParamsSchema:nS}=((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()}))(ue,tS,dp,zy,cp),{CreateInvoiceParamsSchema:yr}=((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(a=>a.period_start===void 0==(a.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(a=>a.period_start===void 0||a.period_end===void 0||a.period_end>a.period_start,{message:"period_end must be after period_start."})}))(ue,nS,Cy,cp,Py);var yp=f.strictObject({requestId:f.uuid(),predecessorOperationId:f.uuid().optional(),invoiceMode:Tn.optional(),entityId:f.uuid().optional(),billingSubscriptionId:f.uuid().optional(),newBillingSubscription:f.literal(!0).optional(),offerId:f.uuid().optional(),nativeOffer:En.optional(),plans:f.array(f.strictObject({productVersionId:f.uuid(),seatQuantities:f.record(on,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:oe}).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"),Jn=f.strictObject({operationId:f.uuid()}),et=f.number().int().min(0).max(1e8),rS=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:et,seats:f.array(f.strictObject({key:on,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:et})).max(20),prepaid:f.array(Ud).max(100).optional(),catalogAmountMinor:et,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+bo({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"),Sp=f.string().regex(/^[A-Za-z0-9_-]{1,200}$/),iS=f.strictObject({id:Sp,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"),oS=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()}),vp=f.strictObject({invoiceMode:Tn.optional(),append:oS.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:Sp,terms:iS})).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})}),vi=f.strictObject({operationId:f.uuid(),entityId:f.uuid().nullable(),billingSubscriptionId:f.uuid().nullable(),discount:f.strictObject({offerId:f.uuid(),couponId:f.uuid(),discount:gr,duration:Jt,amountMinor:et,allocations:f.array(f.strictObject({productVersionId:f.uuid(),amountMinor:et})).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:et,discountMinor:et,taxMinor:et,totalMinor:et}).nullable(),expiresAt:f.iso.datetime({offset:!0}),provider:f.enum(["stripe","apple","google"]),nativeOffer:En.optional(),currency:oe,lines:f.array(rS).min(1).max(20),catalogAmountMinor:et,automaticTax:f.boolean(),execution:vp.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"),Sr=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:vp.nullable(),currency:oe,catalogAmountMinor:et,taxMinor:et,totalMinor:f.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.boolean(),nativePurchase:Ts.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"),Io=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()}),xp=f.strictObject({requestId:f.uuid(),invoiceMode:Tn.optional(),membershipId:f.uuid(),carryOverBalances:Io.optional(),carryOverUsages:Io.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:on,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"),xo=f.string().regex(/^price_[A-Za-z0-9]+$/),bp=f.strictObject({grooveUpdateId:f.uuid(),grooveCustomerId:f.uuid()}),_p=f.strictObject({price:xo.nullable(),priceId:f.uuid().optional(),quantity:f.number().int().min(0).max(1e4)}),Ip=f.strictObject({provider:f.literal("stripe"),invoiceMode:Tn.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(_p).max(20),remove:f.array(xo).max(20),restoreItems:f.array(f.strictObject({price:xo,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:bp}).nullable(),cancel:f.strictObject({prorate:f.literal(!1),invoiceNow:f.literal(!1)}).nullable(),schedule:f.strictObject({currentItems:f.array(f.strictObject({price:xo,quantity:f.number().int().min(0).max(1e4)})).max(20),nextItems:f.array(_p).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:bp}).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"),ks=f.strictObject({carryOverBalances:Io.optional(),carryOverUsages:Io.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:oe,creditMinor:et,debitMinor:et,discountMinor:et,taxMinor:et,totalMinor:et,retainedProductVersionIds:f.array(f.uuid()).max(19),execution:Ip}),aS=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:Ip.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),sS=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:oe,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:et,policy:f.enum(["apple_store","google_full_price"])})}),cS=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:Ts.nullable()}),Ap=f.union([ks,sS]),Ds=f.union([aS,cS]),xi=f.number().int().positive().max(2e8),Yn=f.number().int().min(0).max(2e8),wp=f.strictObject({requestId:f.uuid(),invoiceId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:xi.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"),Cp=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:xi,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)}),Pp=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().regex(/^in_[A-Za-z0-9]+$/),currency:oe,paidMinor:Yn,refundedMinor:Yn,pendingMinor:Yn,amountMinor:xi,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:Cp,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"),Ao=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:oe,amountMinor:xi,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),refundId:f.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Cp.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"),EE=f.strictObject({invoiceId:f.uuid(),currency:oe,paidMinor:Yn,refundedMinor:Yn,pendingMinor:Yn,refundableMinor:Yn,executor:f.enum(["indiana","merchant"]).nullable(),canRefund:f.boolean(),operations:f.array(Ao).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),TE=f.strictObject({requestId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:xi.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 Op=qe.strictObject({requestId:qe.uuid(),targets:qe.array(qe.strictObject({membershipId:qe.uuid(),action:qe.enum(["cancel","uncancel"]),timing:qe.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"),wo=qe.strictObject({batchId:qe.uuid()}),uS=qe.strictObject({operationId:qe.uuid(),membershipIds:qe.array(qe.uuid()).min(1).max(20),provider:qe.enum(["stripe","apple","google"]),action:qe.enum(["cancel","uncancel"]),timing:qe.enum(["immediate","renewal"]),status:qe.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ks.nullable(),managementUrl:qe.url().nullable(),failureCode:qe.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Ii=qe.strictObject({batchId:qe.uuid(),ready:qe.boolean(),status:qe.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:qe.iso.datetime({offset:!0}),acceptedAt:qe.iso.datetime({offset:!0}).nullable(),groups:qe.array(uS).min(1).max(100)});import{z as ge}from"zod";var lS=ge.string().trim().min(1).max(240),Ns={requestId:ge.uuid(),reason:lS},Co=ge.discriminatedUnion("action",[ge.strictObject({...Ns,action:ge.literal("start"),productVersionId:ge.uuid(),entityId:ge.uuid().optional(),days:ge.number().int().min(1).max(730).optional()}),ge.strictObject({...Ns,action:ge.literal("extend"),membershipId:ge.uuid(),days:ge.number().int().min(1).max(730)}),ge.strictObject({...Ns,action:ge.literal("end"),membershipId:ge.uuid()})]),Ep=ge.strictObject({operationId:ge.uuid()}),Tp=ge.iso.datetime({offset:!0}),dS=ge.strictObject({provider:ge.literal("stripe"),executor:ge.enum(["indiana","merchant"]),accountId:ge.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ge.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ge.union([ge.literal("now"),Tp]),prorationBehavior:ge.literal("none")}),Fs=ge.strictObject({operationId:ge.uuid(),action:ge.enum(["start","extend","end"]),status:ge.enum(["pending","effective"]),managedBy:ge.enum(["indiana","stripe"]),membershipIds:ge.array(ge.uuid()).min(1).max(20),endsAt:Tp.nullable(),execution:dS.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"),FE=ge.strictObject({groupId:ge.uuid(),productVersionId:ge.uuid(),enabled:ge.boolean()});import{z as ke}from"zod";var Rp=ke.strictObject({requestId:ke.uuid(),currency:oe,makeDefault:ke.boolean()}),jp=ke.strictObject({setupId:ke.uuid()}),pS=ke.strictObject({provider:ke.literal("stripe"),executor:ke.literal("merchant"),accountId:ke.string().regex(/^acct_[A-Za-z0-9]+$/),mode:ke.literal("setup"),currency:ke.string().regex(/^[a-z]{3}$/),customer:ke.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:ke.uuid(),metadata:ke.strictObject({grooveProjectId:ke.uuid(),grooveEnvironmentId:ke.uuid(),grooveCustomerId:ke.uuid(),groovePaymentSetupId:ke.uuid()}),setDefaultPaymentMethod:ke.boolean(),expiresAt:ke.iso.datetime({offset:!0})}),Us=ke.strictObject({id:ke.uuid(),provider:ke.literal("stripe"),status:ke.enum(["prepared","complete","expired"]),currency:oe,makeDefault:ke.boolean(),url:ke.url().nullable(),createdAt:ke.iso.datetime({offset:!0}),expiresAt:ke.iso.datetime({offset:!0}),completedAt:ke.iso.datetime({offset:!0}).nullable(),execution:pS.nullable()});import{z as tt}from"zod";var kp=tt.union([tt.string(),tt.number(),tt.boolean(),tt.null()]),Dp=tt.strictObject({customerId:tt.uuid()}),Np=tt.strictObject({customerId:tt.uuid(),provider:tt.literal("stripe"),checkedAt:tt.iso.datetime({offset:!0}),status:tt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:tt.number().int().nonnegative(),differences:tt.array(tt.strictObject({subscriptionId:tt.string().startsWith("sub_"),itemId:tt.string().nullable(),field:tt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:kp,actual:kp})).max(1e4)});import{z as ce}from"zod";var Po=ce.iso.datetime({offset:!0}),Oo=ce.strictObject({createdAt:Po,id:ce.uuid()}),Eo=ce.strictObject({customerId:ce.uuid().optional(),entityId:ce.uuid().optional(),productId:ce.string().min(1).max(256).optional(),provider:ce.enum(["stripe","apple","google","free"]).optional(),status:ce.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Oo.optional(),limit:ce.number().int().min(1).max(100).optional()}),Ms={id:ce.uuid(),customerId:ce.uuid(),entityId:ce.uuid().nullable(),productId:ce.string().min(1).max(256),productVersionId:ce.uuid(),name:ce.string().min(1).max(120),provider:ce.enum(["stripe","apple","google","free"]),createdAt:Po},mS=ce.strictObject({...Ms,status:ce.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ce.boolean(),billingSubscriptionId:ce.uuid().nullable()}),fS=ce.strictObject({...Ms,status:ce.enum(["active","ended","refunded"]),orderId:ce.uuid().nullable(),transactionId:ce.uuid().nullable(),currency:oe.nullable(),amountMinor:ce.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),hS=ce.strictObject({...Ms,status:ce.enum(["blocked","resolved"]),conflict:ce.strictObject({detectedAt:Po,blockingMembershipIds:ce.array(ce.uuid()).min(1).max(100),transactionId:ce.uuid()}),resolvedAt:Po.nullable()}),Fp=Eo.extend({status:ce.enum(["blocked","resolved"]).optional()}),Up=ce.strictObject({customerId:ce.uuid(),orderId:ce.uuid()}),Mp=ce.strictObject({orderId:ce.uuid(),status:ce.enum(["blocked","resolved"])}),Bp=ce.strictObject({items:ce.array(mS).max(100),nextCursor:Oo.nullable()}),Lp=ce.strictObject({items:ce.array(fS).max(100),nextCursor:Oo.nullable()}),qp=ce.strictObject({items:ce.array(hS).max(100),nextCursor:Oo.nullable()});import{z as Ue}from"zod";var Vp=Ue.union([Ue.strictObject({intent:Ue.literal("read"),requestId:Ue.uuid(),purchaseIntentId:Ue.uuid()}),Ue.strictObject({requestId:Ue.uuid(),provider:Ue.literal("apple"),purchaseIntentId:Ue.uuid(),productId:Ue.string().min(1).max(255).optional(),signedTransaction:Ue.string().min(1).max(131072)}),Ue.strictObject({requestId:Ue.uuid(),provider:Ue.literal("google"),purchaseIntentId:Ue.uuid(),productId:Ue.string().min(1).max(255).optional(),purchaseToken:Ue.string().min(1).max(16384)})]),$p=Ue.strictObject({requestId:Ue.uuid(),orderId:Ue.uuid(),purchaseIntentId:Ue.uuid(),status:Ue.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:oe,refunded:Ue.boolean(),completion:Ue.strictObject({transactionIds:Ue.array(Ue.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ue.boolean()}).nullable()});import{z as T}from"zod";var qs=T.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),gS=T.record(T.string(),T.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),bS=3,Ai=20,_S=bS*Ai,Bs=T.strictObject({type:T.literal("product"),productId:qs}),Gp={type:T.literal("group"),key:T.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:T.string().trim().min(1).max(80)},yS=T.discriminatedUnion("type",[Bs,T.strictObject({...Gp,items:T.array(Bs).max(Ai)})]),SS=T.discriminatedUnion("type",[Bs,T.strictObject({...Gp,items:T.array(yS).max(Ai)})]),vS=T.array(SS).max(Ai).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function o(a){for(let s of a){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"&&o(s.items)}}o(e),(n.size>Ai||i>_S)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function wi(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:wi(t))}function YE(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 To=T.strictObject({lookupKey:T.string().trim().min(1).max(200),displayName:T.string().trim().min(1).max(1500),items:vS,metadata:gS}),Ls=To.extend({paywallId:T.uuid().nullable()}),xS=T.strictObject({product:T.record(T.string(),T.json()),prices:T.array(T.record(T.string(),T.json())),entitlements:T.array(T.record(T.string(),T.json())),freeTrials:T.array(T.record(T.string(),T.json())),licenses:T.array(T.record(T.string(),T.json()))}),Kp=Ls.extend({id:T.uuid(),projectId:T.uuid(),environmentId:T.uuid(),state:T.enum(["active","archived"]),isCurrent:T.boolean(),revision:T.number().int().nonnegative(),publishedVersionId:T.uuid().nullable(),createdAt:T.number().nonnegative().nullable()}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Hp=T.strictObject({id:T.uuid(),offeringId:T.uuid(),projectId:T.uuid(),environmentId:T.uuid(),version:T.number().int().positive(),document:To,productEvidence:T.record(qs,xS),createdAt:T.number().nonnegative().nullable()}).superRefine((e,t)=>{let n=wi(e.document);(!n.length||wS(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"})}),IS=T.strictObject({rows:T.array(Kp).max(200),versions:T.array(Hp).max(500)}),JE=T.discriminatedUnion("action",[T.strictObject({action:T.literal("create"),document:Ls}),T.strictObject({action:T.literal("save"),id:T.uuid(),revision:T.number().int().nonnegative(),document:Ls}),T.strictObject({action:T.enum(["publish","set_current","archive","restore"]),id:T.uuid(),revision:T.number().int().nonnegative()})]),XE=T.strictObject({record:Kp,version:Hp.nullable()}),Wp=T.discriminatedUnion("type",[T.strictObject({type:T.literal("current")}),T.strictObject({type:T.literal("id"),id:T.uuid()}),T.strictObject({type:T.literal("lookup_key"),lookupKey:T.string().min(1).max(200)}),T.strictObject({type:T.literal("version"),versionId:T.uuid()})]),AS=T.strictObject({internalId:qs,id:T.string(),name:T.string().nullable(),version:T.number().int().positive(),archived:T.boolean()}),zE=IS.extend({products:T.array(AS).max(500),paywalls:T.array(T.strictObject({id:T.uuid(),name:T.string()})).max(200)});function wS(e){let t=[];wi(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 Ro}from"zod";var vr=Ro.strictObject({id:Ro.uuid(),offeringId:Ro.uuid(),version:Ro.number().int().positive(),document:To});import{z as Pt}from"zod";import{z as ee}from"zod";import{z as xr}from"zod";var Qp=xr.strictObject({items:xr.array(xr.strictObject({productVersionId:xr.string().min(1).max(200),label:xr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:xr.string().min(1).max(200).nullable(),grouping:Du.optional()});function aT(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 Ye}from"zod";var CS=Ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Zp=Ye.discriminatedUnion("type",[Ye.object({type:Ye.literal("fixed"),productVersionId:Ye.string().min(1).max(200)}).strict(),Ye.object({type:Ye.literal("picker"),pickerId:CS,allowedProductVersionIds:Ye.array(Ye.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")]),_n=Ye.discriminatedUnion("type",[Ye.object({type:Ye.literal("modal"),size:Ye.enum(["sm","md","lg"])}).strict(),Ye.object({type:Ye.literal("sheet"),size:Ye.enum(["sm","md","lg"])}).strict(),Ye.object({type:Ye.literal("fullscreen")}).strict(),Ye.object({type:Ye.literal("inline")}).strict()]);var PS=ee.discriminatedUnion("type",[ee.strictObject({type:ee.literal("event"),event:ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ee.strictObject({type:ee.literal("open_url"),url:ee.url().refine(e=>new URL(e).protocol==="https:")})]),OS=mt,ES=ee.discriminatedUnion("type",[ee.object({type:ee.literal("checkout"),product:Zp}).strict(),ee.object({type:ee.literal("close")}).strict(),ee.object({type:ee.literal("action"),action:PS}).strict()]),jo=ee.object({schemaVersion:ee.literal(3),kind:ee.literal("paywall"),name:ee.string().trim().min(1).max(80),presentation:_n,requirement:pr.optional(),products:Qp,offeringVersionId:ee.uuid().nullable(),offeringId:ee.uuid().nullable(),screen:OS,buttons:ee.record(ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ES)}).strict(),ko=jo.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 RS(e))t.addIssue({code:"custom",message:r});for(let r of TS(e))t.addIssue({code:"custom",message:r});eo(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 TS(e){let t=e.products.items.map(o=>o.productVersionId),n=Fu(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),(!e.offeringVersionId||!e.offeringId)&&i.push("offering"),e.products.grouping&&(!Nu(e.products.grouping,t)||e.products.grouping.tiers.some(o=>!e.products.grouping.assignments.some(a=>a.tierId===o.id)))&&i.push("grouping");for(let o of Object.values(e.buttons))if(o.type==="checkout"){let a=o.product;if(a.type==="fixed")r.add(a.productVersionId);else{a.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[a.pickerId];c&&(s=!0,(a.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!a.allowedProductVersionIds.includes(u)))&&i.push("picker")),Ct(e.screen,u=>{if(u.id!==a.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(a.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(o=>!t.includes(o)))&&i.push("purchase"),Ct(e.screen,o=>{o.type==="stack"&&o.productSlot&&!o.bind?.plan&&i.push(`productBinding:${o.id}`),(o.type==="stack"||o.type==="button")&&o.bind?.plan&&!t.includes(o.bind.plan)&&i.push("binding"),o.type==="plan_picker"&&(!o.planIds?.length||o.planIds.some(a=>!t.includes(a)))&&i.push("binding")}),[...new Set(i)]}function RS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),ii(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(m=>m.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 o(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])o(c)}}let a=e.screen.initialPageId??e.screen.pages[0]?.id;a?o(a):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Yp=ee.object({id:ee.uuid(),projectId:ee.uuid(),environmentId:ee.uuid(),revision:ee.number().int().nonnegative(),status:ee.enum(["draft","published","archived"]),publishedVersionId:ee.uuid().nullable(),updatedAt:ee.iso.datetime({offset:!0}),draft:jo}).strict(),bT=ee.object({rows:ee.array(Yp).max(200),nextCursor:ee.uuid().nullable()}).strict(),_T=Yp.omit({draft:!0}).extend({name:ee.string(),productCount:ee.number().int().nonnegative()}).strict(),yT=ee.discriminatedUnion("action",[ee.object({action:ee.literal("save"),id:ee.uuid().nullable(),revision:ee.number().int().nonnegative(),document:jo}).strict(),ee.object({action:ee.enum(["publish","archive"]),id:ee.uuid(),revision:ee.number().int().nonnegative()}).strict()]),ST=ee.object({paywalls:ee.array(ee.object({id:ee.uuid(),paywallId:ee.uuid(),version:ee.number().int().positive(),name:ee.string().min(1).max(80),presentation:_n,buttons:jo.shape.buttons}).strict()).max(500),limited:ee.boolean()}).strict();var Jp=Pt.strictObject({..._r,selector:Pt.discriminatedUnion("type",[Pt.strictObject({type:Pt.literal("paywall"),paywallId:Pt.uuid()}),Pt.strictObject({type:Pt.literal("version"),versionId:Pt.uuid()})]),customerId:Pt.uuid().optional(),commerce:zi,locale:Pt.string().min(1).max(35),requirement:pr.optional()}),Do=Pt.strictObject({id:Pt.uuid(),paywallId:Pt.uuid(),version:Pt.number().int().positive(),document:ko,offering:vr,capabilities:mr,check:ri.nullable()}).superRefine((e,t)=>{let n=new Set(wi(e.offering.document)),r=new Set(e.document.products.items.map(i=>i.productVersionId));(e.document.offeringVersionId!==e.offering.id||e.document.offeringId!==e.offering.offeringId||[...r].some(i=>!n.has(i))||Object.values(e.capabilities.plans).some(i=>!r.has(i.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})});import{z as ht}from"zod";var Xp={requestId:ht.uuid(),sourceId:ht.uuid(),expectedAvailable:jt},zp=ht.discriminatedUnion("action",[ht.strictObject({...Xp,action:ht.enum(["add","subtract","set_remaining"]),amount:be}),ht.strictObject({...Xp,action:ht.literal("edit"),granted:be,expiresAt:ht.iso.datetime({offset:!0}).nullable(),nextResetAt:ht.iso.datetime({offset:!0}).nullable(),expectedRevision:ht.number().int().nonnegative()})]),Vs=ht.strictObject({sourceId:ht.uuid(),available:jt,held:jt,spent:jt,adjustmentGrantId:ht.uuid().nullable()}),em=Vs.extend({granted:jt,expiresAt:ht.iso.datetime({offset:!0}).nullable(),nextResetAt:ht.iso.datetime({offset:!0}).nullable(),revision:ht.number().int().nonnegative()});import{z as Dt}from"zod";var tm=Dt.discriminatedUnion("action",[Dt.object({action:Dt.literal("upsert"),externalId:Dt.string().min(1).max(128),name:Dt.string().trim().min(1).max(80)}).strict(),Dt.object({action:Dt.literal("archive"),entityId:Dt.uuid()}).strict()]),nm=Dt.object({id:Dt.uuid(),externalId:Dt.string().min(1).max(128),name:Dt.string().min(1).max(80),archived:Dt.boolean()}).strict();import{z as ot}from"zod";import{z as zn}from"zod";var im=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],rm=zn.string().regex(/.+\/.+/),$s=zn.number().min(-100),Xn=zn.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),jS=zn.strictObject({input:Xn,output:Xn,cache_read:Xn.optional(),cache_write:Xn.optional(),reasoning:Xn.optional(),input_audio:Xn.optional(),output_audio:Xn.optional()}),Gs=(e,t)=>zn.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),MT=zn.strictObject({defaultMarkup:$s,providerMarkups:Gs(zn.string().min(1),$s),modelMarkups:Gs(rm,$s),customModels:Gs(rm,jS.partial())});import{z as re}from"zod";var er=re.iso.datetime({offset:!0}),Rn=re.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),kS=re.discriminatedUnion("kind",[re.object({kind:re.literal("absolute"),from:er,to:er}).strict(),re.object({kind:re.literal("last_days"),days:re.union([re.literal(1),re.literal(7),re.literal(30),re.literal(90)])}).strict(),re.object({kind:re.literal("billing_cycles"),membershipId:re.uuid(),count:re.number().int().min(1).max(12),includeCurrent:re.boolean()}).strict()]),om=re.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"),DS=re.object({key:re.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:re.array(re.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),tr=re.object({range:kS,timezone:om,filterBy:re.array(DS).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:re.enum(["hour","day","week","month"]),internal_feature_id:re.uuid().nullable(),entityId:re.uuid().nullable(),topN:re.number().int().min(1).max(50).nullable(),groupBy:re.union([re.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),re.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:re.object({bucket:er,group:re.string().max(240),isOther:re.boolean(),internal_feature_id:re.uuid(),resourceId:re.uuid()}).strict().nullable(),limit:re.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)"})}),am=re.object({from:er,to:er,interval:re.enum(["hour","day","week","month"]),timezone:om,rows:re.array(re.object({bucket:er,group:re.string().max(240),isOther:re.boolean(),internal_feature_id:re.uuid(),resourceId:re.uuid(),consumedUnits:Rn,refundedUnits:Rn,reservedUnits:Rn,charged:Rn,refunded:Rn,reserved:Rn,netUnits:Rn,netCharged:Rn}).strict()).max(100),nextCursor:re.object({bucket:er,group:re.string().max(240),isOther:re.boolean(),internal_feature_id:re.uuid(),resourceId:re.uuid()}).strict().nullable()}).strict();var Ir=ot.string().regex(/^(0|[1-9]\d{0,29})$/),sm=ot.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Ks=ot.strictObject({bucket:ot.iso.datetime({offset:!0}),group:ot.string().max(240),isOther:ot.boolean(),internal_feature_id:ot.uuid()}),cm=ot.strictObject({...tr.shape,groupBy:ot.union([ot.enum(["customer","entity","entitlement"]),ot.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Ks.nullable()}).superRefine((e,t)=>{let n=tr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),um=ot.strictObject({from:ot.iso.datetime({offset:!0}),to:ot.iso.datetime({offset:!0}),interval:tr.shape.interval,timezone:tr.shape.timezone,rows:ot.array(ot.strictObject({...Ks.shape,eventCount:Ir,units:sm,tokenEventCount:Ir,tokens:ot.strictObject(Object.fromEntries(im.map(e=>[e,Ir]))),totalTokens:Ir,providerCostEventCount:Ir,providerCostUsd:sm,invalidTelemetryEventCount:Ir})).max(100),nextCursor:Ks.nullable()});import{z as We}from"zod";var lm=We.object({requestId:We.uuid(),items:We.array(We.object({customerId:We.uuid(),command:ti.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"),dm=We.object({batchId:We.uuid(),after:We.number().int().min(-1).max(999),limit:We.number().int().min(1).max(100)}).strict(),pm=We.object({batchId:We.uuid(),status:We.enum(["queued","complete"]),total:We.number().int().min(1).max(1e3),processed:We.number().int().min(0).max(1e3),items:We.array(We.object({position:We.number().int().min(0).max(999),customerId:We.uuid(),idempotencyKey:We.string().min(1).max(120),status:We.enum(["queued","accepted","rejected","failed"]),receipt:ni.nullable(),errorCode:We.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:We.number().int().min(0).max(999).nullable()}).strict();import{z as x}from"zod";var NS=x.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),mm=x.enum(["draft","active","paused","archived"]),fm=x.string().min(1).max(256),hm=x.array(fm).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),FS=x.strictObject({duration:x.enum(["day","week","month","year"]),length:x.number().int().min(1).max(3660)}),US=x.strictObject({internal_feature_id:x.uuid(),allowance:x.number().nonnegative().max(1e15).nullable(),expiry:FS.nullable()}),MS=x.discriminatedUnion("type",[x.strictObject({type:x.literal("feature_grant"),grants:x.array(US).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),x.strictObject({type:x.literal("free_product"),productId:fm,duration:Jt}),x.strictObject({type:x.literal("invoice_credits"),amount:x.number().positive().max(1e8),duration:Jt,rollover:x.boolean(),productIds:hm})]),BS=x.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),gm=x.object({key:BS,name:x.string().trim().min(1).max(80),configuration:MS}).strict(),bm=x.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Hs=x.object({code:bm,maxUses:x.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:x.boolean()}).strict(),_m=x.object({key:x.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:x.string().trim().min(1).max(80),rewardId:x.uuid(),redeemOn:x.enum(["customer_creation","checkout"]),receivedBy:x.enum(["referrer","all"]),maxRedemptions:x.number().int().min(1).max(1e6).nullable(),productIds:hm,excludeTrial:x.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),ym={id:x.uuid(),projectId:x.uuid(),environmentId:x.uuid(),revision:x.number().int().nonnegative(),status:mm,createdAt:x.iso.datetime({offset:!0}),updatedAt:x.iso.datetime({offset:!0})},LS=gm.extend(ym).strict(),qS=_m.safeExtend(ym).strict(),XT=x.strictObject({id:x.uuid(),key:x.string(),name:x.string(),type:NS,status:mm}),zT=x.discriminatedUnion("action",[x.object({action:x.literal("save"),id:x.uuid().nullable(),revision:x.number().int().nonnegative(),input:gm}).strict(),x.object({action:x.enum(["activate","pause","resume","archive","delete"]),id:x.uuid(),revision:x.number().int().nonnegative()}).strict()]),eR=x.discriminatedUnion("action",[x.object({action:x.literal("save"),id:x.uuid().nullable(),revision:x.number().int().nonnegative(),input:_m}).strict(),x.object({action:x.enum(["activate","pause","resume","archive","delete"]),id:x.uuid(),revision:x.number().int().nonnegative()}).strict()]),Sm=x.object({id:x.uuid(),rewardId:x.uuid(),programId:x.uuid().nullable(),customerId:x.uuid(),referrerId:x.uuid().nullable(),status:x.enum(["pending","applied","unavailable"]),result:x.record(x.string(),x.unknown()).nullable(),createdAt:x.iso.datetime({offset:!0})}).strict(),vm=x.object({code:bm,requestId:x.uuid()}).strict(),xm=x.strictObject({redemptionId:x.uuid(),currency:oe,requestId:x.uuid(),accepted:x.literal(!0)}),VS=x.strictObject({type:x.literal("checkout"),orderId:x.uuid(),productVersionId:x.uuid(),currency:oe,duration:Jt,renewalAmountMinor:x.number().int().positive().max(1e8),status:x.enum(["created","pending","trialing","paid","cancelled","failed"]),url:x.url().nullable()}),Im=x.discriminatedUnion("type",[VS,x.strictObject({type:x.literal("subscription"),operationId:x.uuid(),membershipId:x.uuid(),productVersionId:x.uuid(),currency:oe,duration:Jt,renewalAmountMinor:x.number().int().positive().max(1e8),status:x.enum(["pending","running","applied","failed"])})]),Am=x.object({programId:x.uuid(),requestId:x.uuid()}).strict(),wm=x.object({id:x.uuid(),programId:x.uuid(),code:Hs.shape.code,createdAt:x.iso.datetime({offset:!0})}).strict(),tR=x.object({rows:x.array(LS).max(100),nextCursor:x.uuid().nullable()}).strict(),nR=x.object({rows:x.array(qS).max(100),nextCursor:x.uuid().nullable()}).strict(),$S=Hs.extend({id:x.uuid(),redemptions:x.number().int().nonnegative()}).strict(),GS=x.strictObject({id:x.uuid(),programId:x.uuid().nullable(),customerId:x.uuid().nullable(),referrerId:x.uuid().nullable(),code:x.string().nullable(),status:x.enum(["pending","triggered","applied"]),createdAt:x.iso.datetime({offset:!0})}),rR=x.object({codes:x.array($S).max(100),redemptions:x.array(GS).max(100),customers:x.record(x.uuid(),x.string()),codesCursor:x.uuid().nullable(),redemptionsCursor:x.uuid().nullable()}).strict(),iR=x.discriminatedUnion("action",[x.object({action:x.literal("create"),rewardId:x.uuid(),revision:x.number().int().nonnegative(),input:Hs}).strict(),x.object({action:x.literal("remove"),rewardId:x.uuid(),revision:x.number().int().nonnegative(),codeId:x.uuid()}).strict()]);import{z as _}from"zod";import{z as F}from"zod";var sn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Ci=e=>new Set(e).size===e.length,Ws=F.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),KS=F.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Pi=F.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"))),HS=F.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Cm=F.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),sR=["isOn","isOff","getFeatureValue","evalFeature","eval_feature"],Pm=F.strictObject({id:F.uuid(),repo:KS,platform:F.enum(["github","gitlab","bitbucket"]),branches:F.array(Pi).min(1).max(4).refine(Ci),workflow:F.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:F.array(F.uuid()).min(1).max(4).refine(Ci),include:F.array(Cm).min(1).max(16),exclude:F.array(Cm).max(16),methods:F.array(F.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Ci),maxAgeHours:F.number().int().min(1).max(720)}),Om=Pm.extend({revision:F.number().int().positive()}),cR=F.strictObject({repository:Pm,expectedRevision:F.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Em=F.strictObject({repositoryId:F.uuid(),branch:Pi}),WS=F.array(Ws).max(sn.keys).refine(Ci),Tm=F.strictObject({repository:Om.omit({keyIds:!0}),branch:Pi,keys:WS,keySetHash:F.string().regex(/^[a-f0-9]{64}$/)}),QS=F.strictObject({filePath:HS,startingLineNumber:F.number().int().min(1).max(1e7)}),Qs=F.strictObject({protocol:F.literal(1),repositoryId:F.uuid(),branch:Pi,workflow:F.string().max(200),configurationRevision:F.number().int().positive(),keySetHash:F.string().regex(/^[a-f0-9]{64}$/),commit:F.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:F.uuid(),runNumber:F.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:F.number().int().min(1).max(1e4),scannerVersion:F.literal("1"),scannedAt:F.iso.datetime({offset:!0}),coverage:F.strictObject({complete:F.literal(!0),files:F.number().int().min(0).max(sn.files),sourceBytes:F.number().int().min(0).max(sn.sourceBytes),unresolvedCalls:F.number().int().min(0).max(1e6),unsupportedFiles:F.number().int().min(0).max(sn.files)}),features:F.array(F.strictObject({key:Ws,refs:F.array(QS).max(sn.referencesPerKey)})).max(sn.keys)}).superRefine((e,t)=>{Ci(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)>sn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Zs=F.strictObject({scanId:F.uuid(),commit:F.string(),receivedAt:F.string(),references:F.number().int().nonnegative(),removedReferences:F.number().int().nonnegative()}),ZS=Zs.extend({repositoryId:F.uuid(),branch:Pi,workflow:F.string(),digest:F.string(),configurationRevision:F.number().int().positive(),runNumber:F.number().int().positive(),runAttempt:F.number().int().positive(),scannedAt:F.string(),keySetHash:F.string(),coverage:Qs.shape.coverage}),YS=F.strictObject({repositories:F.array(Om).max(sn.repositories),scans:F.array(ZS).max(sn.repositories*sn.branches)}),JS=F.strictObject({key:Ws,references:F.number().int().nonnegative(),coveredTargets:F.number().int().nonnegative(),expiredTargets:F.number().int().nonnegative(),uncertainTargets:F.number().int().nonnegative()}),uR=F.strictObject({available:F.boolean().default(!0),settings:YS,expectedTargets:F.number().int().min(0).max(80),features:F.array(JS).max(2001),truncated:F.boolean()});import{z as Y}from"zod";var Ys=Y.array(Y.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"),Ar=Y.intersection(wt,Y.object({tags:Ys.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),No=Y.string().trim().max(80),Fo=Y.union([Y.email().max(254),Y.literal("")]),Uo=Y.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Rm=Y.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),jm=Y.object({externalUserId:Rm.optional(),name:No.default(""),email:Fo.default(""),attributes:Ar.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),wr=Y.discriminatedUnion("type",[Y.strictObject({type:Y.literal("id"),value:Y.uuid()}),Y.strictObject({type:Y.literal("externalUserId"),value:Rm})]),Cr=Y.strictObject({name:No.optional(),email:Fo.optional(),attributes:Ar.optional(),fingerprint:Uo.optional()}),nr=e=>!e.customerData||e.customer?.type==="externalUserId",rr="customerData requires an externalUserId customer",Pr=Y.object({id:Y.uuid(),externalUserId:Y.string().min(1).max(255).nullable(),name:No,email:Fo,attributes:Ar,createdAt:Y.iso.datetime()}).strict(),km=Y.object({customer:Pr,changed:Y.boolean(),replayed:Y.boolean()}).strict(),XS=Y.discriminatedUnion("type",[Y.object({type:Y.literal("id"),value:Y.uuid()}).strict(),Y.object({type:Y.literal("externalUserId"),value:Y.string().trim().min(1).max(255)}).strict()]),zS=Y.object({name:No.optional(),email:Fo.optional(),attributes:Ar.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:Y.array(Y.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:Y.strictObject({add:Ys,remove:Ys}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Js=Y.object({lookup:XS}).strict(),Dm=Js.extend({requestId:Y.uuid(),patch:zS}).strict(),Nm=Y.object({search:Y.string().trim().max(200).default(""),tag:Y.string().trim().max(40).default(""),planId:Y.string().max(200).default(""),versionId:Y.string().max(200).default(""),holdingStatus:Y.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:Y.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:Y.union([Y.iso.datetime(),Y.literal("")]).default(""),createdUntil:Y.union([Y.iso.datetime(),Y.literal("")]).default(""),offset:Y.coerce.number().int().min(0).max(1e5).default(0),limit:Y.coerce.number().int().min(1).max(100).default(50)}).strict(),Fm=Y.object({customers:Pr.array(),hasMore:Y.boolean(),total:Y.number().int().nonnegative().nullable(),evaluatedAt:Y.iso.datetime()}).strict();import{z as $t}from"zod";var Xs=$t.strictObject({customerId:$t.uuid(),eventId:$t.string().trim().min(1).max(200),grantId:$t.uuid(),productVersionId:$t.uuid(),subscriptionId:$t.string().trim().min(1).max(255),occurredAt:$t.iso.datetime({offset:!0})}),Um=Xs.extend({id:$t.uuid(),couponId:$t.uuid(),status:$t.literal("redeemed"),source:$t.literal("merchant"),recordedAt:$t.iso.datetime({offset:!0})});import{z as Re}from"zod";import{z as Mo}from"zod";var zs=Mo.strictObject({eventsEnabled:Mo.boolean(),experimentViewsEnabled:Mo.boolean(),featureUsageEnabled:Mo.boolean()}),bR=Object.freeze({eventsEnabled:!1,experimentViewsEnabled:!0,featureUsageEnabled:!1});function _R(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var ec=nn.extend({analyticsConfig:zs,remoteFeatures:Re.array(Re.string().min(1).max(255)).max(500)}),ev=ec.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"})}),Mm=Re.strictObject({attributes:wt,features:Re.array(Re.string().min(1).max(255)).min(1).max(500).optional(),customerId:Re.uuid().optional()}),tv=Re.strictObject({value:he,source:Re.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Re.boolean(),off:Re.boolean(),ruleId:Re.string(),experimentResult:$u.optional()}),Bm=Re.strictObject({generation:nn.shape.generation,evaluatedAt:nn.shape.evaluatedAt,expiresAt:nn.shape.expiresAt,features:Re.record(Re.string(),tv)}),Lm=Re.strictObject({customerId:Re.uuid().optional(),events:Re.array(Re.strictObject({eventUuid:Re.uuid(),timestamp:Re.iso.datetime({offset:!0}),name:Re.string().min(1).max(255),properties:Re.record(Re.string(),he).default({}),deviceId:Re.string().min(1).max(255).optional(),sessionId:Re.string().min(1).max(255).optional()})).min(1).max(100)}),qm=Re.strictObject({inserted:Re.number().int().nonnegative(),duplicates:Re.number().int().nonnegative(),rejected:Re.number().int().nonnegative(),skipped:Re.number().int().nonnegative(),analyticsConfig:zs});import{z as Q}from"zod";var tc=Q.strictObject({name:Q.string().trim().min(1).max(255),memo:Q.string().max(1e4).nullable().optional(),footer:Q.string().max(1e4).nullable().optional(),net_terms_days:Q.number().int().positive().nullable().optional()}),nv=tc.extend({id:Q.string().min(1).max(255),created_at:Q.number().nullable()}),Vm=Q.strictObject({items:Q.array(nv).max(50),nextCursor:Q.string().nullable()}),PR=Q.discriminatedUnion("action",[Q.strictObject({action:Q.literal("create"),requestId:Q.uuid(),values:tc}),Q.strictObject({action:Q.literal("update"),id:Q.string().min(1).max(255),values:tc}),Q.strictObject({action:Q.literal("delete"),id:Q.string().min(1).max(255)})]),$m=Q.discriminatedUnion("action",[Q.strictObject({action:Q.literal("create"),requestId:Q.uuid(),params:yr}),Q.strictObject({action:Q.enum(["finalize","send","pay","void"]),requestId:Q.uuid(),invoiceId:Q.uuid()}),Q.strictObject({action:Q.literal("reissue"),requestId:Q.uuid(),invoiceId:Q.uuid(),params:Rs})]),nc=Q.strictObject({id:Q.uuid(),customerId:Q.uuid(),providerInvoiceId:Q.string().nullable(),status:Q.enum(["draft","open","paid","void","uncollectible"]),currency:Q.string(),totalMinor:Q.string().regex(/^-?\d+$/),paidMinor:Q.string().regex(/^\d+$/),refundedMinor:Q.string().regex(/^\d+$/),hostedInvoiceUrl:Q.url().nullable(),createdAt:Q.number(),collectionMethod:Q.enum(["send_invoice","charge_automatically"]).nullable()}),Gm=nc.extend({lines:Q.array(Q.strictObject({id:Q.uuid(),description:Q.string(),amountMinor:Q.string().regex(/^-?\d+$/),netAmountMinor:Q.string().regex(/^-?\d+$/),quantity:Q.number().nullable(),periodStart:Q.number().nullable(),periodEnd:Q.number().nullable()})).max(1e3)}),Oi=Q.strictObject({taskId:Q.uuid(),status:Q.enum(["ready","running","done","dead"]),invoice:nc.nullable(),errorCode:Q.string().nullable()}),Km=Q.strictObject({items:Q.array(nc).max(50),nextCursor:Q.uuid().nullable(),operations:Q.array(Oi).max(50),operationsLimited:Q.boolean()}),OR=Tn;var rv=_.enum(["customers:read","customers:write","entitlements: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"]),Hm={scope:je,permissions:_.array(rv),expiresAt:_.iso.datetime().nullable()},hj=_.discriminatedUnion("kind",[_.object({...Hm,kind:_.literal("server"),keyId:_.string().min(1)}),_.object({...Hm,kind:_.literal("customer"),customerId:_.string().min(1),identityKind:_.enum(["identified","guest"]),expiresAt:_.iso.datetime()})]),D=_.object({requestId:_.uuid(),scope:je}).strict(),iv=jm.safeExtend({fingerprint:Uo.optional()}).strict(),ov=D.extend({customer:Pr,created:_.boolean()}),av=_.enum(["unassigned","unknown","scheduled","active","expired"]),gj=_.object({customerId:_.string().min(1),evaluatedAt:_.iso.datetime(),status:av,validity:ms.nullable(),planVersion:rd.nullable(),holdings:_.array(_.object({id:_.uuid(),planVersionId:_.uuid(),source:_.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:_.array(_.object({featureId:_.string(),featureKey:_.string(),featureName:_.string(),type:_.enum(["boolean","metered"]),allowance:_.number().int().nonnegative().nullable(),used:_.number().finite().nonnegative(),remaining:_.number().finite().nonnegative().nullable(),allowed:_.boolean(),sources:_.array(_.object({holdingId:_.uuid(),planVersionId:_.uuid(),group:_.string(),kind:_.enum(["main","addon"]),allowance:_.number().nullable()})).optional()}))});function Wm(){return D.extend({offer:pi.nullable(),reason:_o.nullable()})}var k={listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:_.strictObject({cursor:_.uuid().optional()}),response:D.extend({templates:Vm})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),params:yr}),response:D.extend({preview:js})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),requestId:_.uuid(),params:yr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:Oi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),command:$m}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:Oi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),taskId:_.uuid()}),response:D.extend({operation:Oi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),cursor:_.uuid().optional()}),response:D.extend({invoices:Km})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),invoiceId:_.uuid()}),response:D.extend({invoice:Gm})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Em,response:D.extend({config:Tm})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Qs,response:D.extend({receipt:Zs})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:_.strictObject({}),response:D.extend({payload:ec})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Mm,response:D.merge(Bm)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Lm,response:D.merge(qm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),sourceId:_.uuid()}),response:D.extend({balance:em})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:zp}),response:D.extend({balance:Vs})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:_.strictObject({internal_feature_id:_.uuid(),customerId:_.uuid().optional(),entityId:_.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:D.extend({internal_feature_id:_.uuid(),config:as,model_markups:go})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),query:Cu}),response:D.extend({usage:Da})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Pu}),response:D.extend({usage:Da})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Vd}),response:D.extend({grant:ws})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:$d,response:D.extend({grants:Gd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:_.union(Vp.options.map(e=>e.extend({customerId:_.uuid().optional(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:D.extend({operation:$p})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:Rp.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Us})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:jp.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Us})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Op.safeExtend({customerId:_.uuid()}),response:D.extend({batch:Ii})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:wo.extend({customerId:_.uuid()}),response:D.extend({batch:Ii})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:wo.extend({customerId:_.uuid()}),response:D.extend({batch:Ii})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:wo.extend({customerId:_.uuid()}),response:D.extend({batch:Ii})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:_.discriminatedUnion("action",[Co.options[0].extend({customerId:_.uuid()}),Co.options[1].extend({customerId:_.uuid()}),Co.options[2].extend({customerId:_.uuid()})]),response:D.extend({trial:Fs})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Ep.extend({customerId:_.uuid()}),response:D.extend({trial:Fs})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Eo,response:D.extend({subscriptions:Bp})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Eo,response:D.extend({purchases:Lp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Fp,response:D.extend({conflicts:qp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Up,response:D.extend({resolution:Mp})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Dp,response:D.extend({verification:Np})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:yp.safeExtend({..._r,customerId:_.uuid().optional()}),response:D.extend({quote:vi})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Jn.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:Sr})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Jn.extend({customerId:_.uuid().optional()}),response:D.extend({operation:Sr})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:xp.safeExtend({customerId:_.uuid().optional()}),response:D.extend({quote:Ap})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Jn.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:Ds})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Jn.extend({customerId:_.uuid().optional()}),response:D.extend({operation:Ds})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:wp.safeExtend({customerId:_.uuid()}),response:D.extend({quote:Pp})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Jn.extend({customerId:_.uuid()}),response:D.extend({operation:Ao})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Jn.extend({customerId:_.uuid()}),response:D.extend({operation:Ao})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Id,response:D.extend({controls:bs})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:gd,response:D.extend({prepared:_d})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:yd,response:D.extend({authorization:yo})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Pd,response:D.extend({coupons:Od})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Sd,response:D.extend({authorization:yo})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:wd,response:D.extend({invoices:Cd})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Ad,response:D.extend({invoice:fi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:_.object({customerId:_.uuid(),command:xd}).strict(),response:D.extend({controls:bs})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:_.object({customerId:_.uuid(),command:tm}).strict(),response:D.extend({entity:nm})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid().nullable(),query:cm}),response:D.extend({analytics:um})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:_.object({customerId:_.uuid().nullable(),query:tr}).strict(),response:D.extend({analytics:am})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:lm,response:D.extend({batchId:_.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:dm,response:D.extend({batch:pm})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:ju.extend({customerId:_.string().min(1).optional()}),response:D.extend({check:ri})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Jp,response:D.extend({paywall:Do})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:_.strictObject({..._r,selector:Wp,customerId:_.string().min(1).optional(),commerce:zi,requirement:pr.optional()}),response:D.extend({offering:vr,candidates:_.array(ku).max(20),availability:_.array(_.strictObject({productVersionId:_.uuid(),available:_.boolean(),reason:_.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:ri.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),entityId:_.uuid().optional()}).strict(),response:D.extend({holdings:Ou})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),query:Eu}).strict(),response:D.extend({ledger:Tu})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Kd.extend({customerId:_.uuid().optional()}),response:D.extend({detail:Hd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Cs.safeExtend({customerId:_.uuid().optional()}),response:D.extend({statement:Wd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),command:ti.options[0]}).strict(),response:D.extend({quote:wu})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:_.strictObject({customerId:_.uuid(),command:_.union([_.strictObject({eventName:_.string().min(1),quantity:be.optional(),properties:Yt.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)}),_.strictObject({internal_feature_id:_.uuid(),quantity:be.optional(),properties:Yt.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)})])}),response:D.extend({receipts:_.array(ni).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:_.object({customerId:_.uuid(),command:ti.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:D.extend({receipt:ni})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:vm,response:D.extend({redemption:Sm})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Am,response:D.extend({referralCode:wm})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:xm,response:D.extend({checkout:Im})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Yd,response:D.extend({seats:Es})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Jd,response:D.extend({seats:Es})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:iv,response:ov},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Js,response:D.extend({customer:Pr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Nm,response:D.extend(Fm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Dm,response:D.extend(km.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:_.object({customerId:_.uuid()}).strict(),response:D.extend({customerToken:_.string().min(1),expiresAt:_.iso.datetime(),sessionId:_.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:_.strictObject({customerId:_.uuid(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:D.extend({customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:_.uuid(),expiresAt:_.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:_.strictObject({customerId:_.uuid(),sessionId:_.uuid().optional()}),response:D.extend({revoked:_.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Uo.optional()}),response:D.extend({customerId:_.uuid(),guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:_.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:D.extend({customerId:_.uuid(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:_.uuid(),expiresAt:_.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:_.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:_.uuid()}),response:D.extend({customer:Pr,switched:_.boolean(),replayed:_.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:_.strictObject({code:_.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:_.uuid()}),response:Wm()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:_.object({}).strict(),response:D.extend({offers:_.array(pi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:_.object({customerId:_.string().min(1).max(255).optional(),couponId:_.uuid(),..._r,requestId:_.uuid(),couponContentDigest:_.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Wm()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Xs,response:D.extend({receipt:Um})}},bj={listInvoiceTemplates:k.listInvoiceTemplates,previewInvoice:k.previewInvoice,createInvoice:k.createInvoice,manageInvoice:k.manageInvoice,readInvoiceOperation:k.readInvoiceOperation,listInvoices:k.listInvoices,getInvoice:k.getInvoice,getCodeReferenceConfig:k.getCodeReferenceConfig,submitCodeReferences:k.submitCodeReferences,getFeatures:k.getFeatures,evaluateFeatures:k.evaluateFeatures,trackEvents:k.trackEvents,setupPayment:k.setupPayment,readPaymentSetup:k.readPaymentSetup,previewSubscriptionBatch:k.previewSubscriptionBatch,confirmSubscriptionBatch:k.confirmSubscriptionBatch,readSubscriptionBatch:k.readSubscriptionBatch,abandonSubscriptionBatch:k.abandonSubscriptionBatch,manageSubscriptionTrial:k.manageSubscriptionTrial,readSubscriptionTrial:k.readSubscriptionTrial,listSubscriptions:k.listSubscriptions,listPurchases:k.listPurchases,listSubscriptionConflicts:k.listSubscriptionConflicts,retrySubscriptionConflict:k.retrySubscriptionConflict,readAiPricing:k.readAiPricing,readUsage:k.readUsage,setUsage:k.setUsage,previewRefund:k.previewRefund,refund:k.refund,readRefund:k.readRefund,previewUpdate:k.previewUpdate,update:k.update,readSubscriptionUpdate:k.readSubscriptionUpdate,restoreNativePurchase:k.restoreNativePurchase,verifySubscriptions:k.verifySubscriptions,previewAttach:k.previewAttach,attach:k.attach,readSubscriptionOperation:k.readSubscriptionOperation,manageBalanceGrant:k.manageBalanceGrant,readBalanceSource:k.readBalanceSource,adjustBalance:k.adjustBalance,listBalanceGrants:k.listBalanceGrants,readBillingControls:k.readBillingControls,prepareBillingAuthorization:k.prepareBillingAuthorization,confirmBillingAuthorization:k.confirmBillingAuthorization,setBillingCoupons:k.setBillingCoupons,revokeBillingAuthorization:k.revokeBillingAuthorization,listBillingInvoices:k.listBillingInvoices,confirmBillingAdjustment:k.confirmBillingAdjustment,manageBillingLimits:k.manageBillingLimits,createCustomer:k.createCustomer,getCustomer:k.getCustomer,listCustomers:k.listCustomers,updateCustomer:k.updateCustomer,createSession:k.createSession,renewSession:k.renewSession,revokeSessions:k.revokeSessions,createGuestCustomer:k.createGuestCustomer,resumeGuestSession:k.resumeGuestSession,claimGuestCustomer:k.claimGuestCustomer,checkEntitlement:k.checkEntitlement,resolveOffering:k.resolveOffering,resolvePaywall:k.resolvePaywall,readHoldings:k.readHoldings,readLedger:k.readLedger,readBillingInvoice:k.readBillingInvoice,readCreditStatement:k.readCreditStatement,quoteBalance:k.quoteBalance,trackUsage:k.trackUsage,mutateBalance:k.mutateBalance,manageUsageEntity:k.manageUsageEntity,readUsageAnalytics:k.readUsageAnalytics,readCreditAnalytics:k.readCreditAnalytics,submitUsageBatch:k.submitUsageBatch,readUsageBatch:k.readUsageBatch,listOffers:k.listOffers,grantOffer:k.grantOffer,recordCouponRedemption:k.recordCouponRedemption,redeemCoupon:k.redeemCoupon,redeemReward:k.redeemReward,createReferralCode:k.createReferralCode,claimRewardProduct:k.claimRewardProduct,readSeats:k.readSeats,manageSeat:k.manageSeat};var Qe={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Qm="00000000-0000-0000-0000-000000000000";var Bo={maxTransitions:1e4,runTimeoutSeconds:2592e3},xj={detailBytes:16384};function Ij(e,t){return Number.isInteger(e)&&e>=1&&e<=Bo.maxTransitions&&Number.isInteger(t)&&t>=0&&t<e}function gt(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 o=t.charAt(i);if(r)o==="\\"?i++:o==='"'&&(r=!1);else if(o==='"')r=!0;else if(o===":"||o===",")n++;else if(o==="-"||o>="0"&&o<="9"){let a=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(a,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),d=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):d)+Number(u),g=m<=0?2-m+d:m>=d?m:d+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var Ym={primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},Ei=(e,t,n,r,i)=>({kind:"screen",schemaVersion:4,name:e,surface:"popup",presentation:{type:"modal",size:"md"},theme:{...Ym},pages:[{id:"main",name:"\u4E3B\u9875\u9762",root:t}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":n,en:r}},actions:i}),Or=e=>({type:"stack",id:"root",direction:"vertical",align:"stretch",justify:"start",children:e,style:{gap:12,padding:{top:24,right:24,bottom:24,left:24}}}),Lo={id:"dismiss",type:"close",event:"popup.dismissed",properties:{},close:!0},Zm=[{id:"blank",label:"\u7A7A\u767D",description:"\u4E00\u4E2A\u6807\u9898\u548C\u4E00\u4E2A\u6309\u94AE\uFF0C\u4ECE\u96F6\u5F00\u59CB\u642D\u3002",document:Ei("\u672A\u547D\u540D\u5F39\u7A97",Or([{type:"text",id:"title",text:"title",variant:"heading"},{type:"button",id:"cta",label:"cta",variant:"primary",action:"dismiss",style:{width:"fill"}}]),{title:"\u6807\u9898",cta:"\u77E5\u9053\u4E86"},{title:"Title",cta:"Got it"},[Lo])},{id:"announcement",label:"\u516C\u544A",description:"\u65B0\u529F\u80FD\u6216\u91CD\u8981\u901A\u77E5\uFF0C\u4E00\u4E2A\u4E3B\u6309\u94AE\u3002",document:Ei("\u65B0\u529F\u80FD\u516C\u544A",Or([{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{text:{color:"primary",weight:700}}},{type:"text",id:"title",text:"title",variant:"heading"},{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"learn_more",style:{width:"fill"}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}]),{eyebrow:"\u65B0\u529F\u80FD",title:"\u73B0\u5728\u53EF\u4EE5\u4E00\u952E\u5BFC\u51FA\u62A5\u8868",body:"\u5728\u4EFB\u610F\u6570\u636E\u9875\u70B9\u51FB\u53F3\u4E0A\u89D2\u300C\u5BFC\u51FA\u300D\uFF0C\u5373\u53EF\u4E0B\u8F7D CSV \u6216 PDF\u3002",cta:"\u53BB\u770B\u770B",later:"\u4EE5\u540E\u518D\u8BF4"},{eyebrow:"NEW",title:"Export reports in one click",body:"Click Export on any data page to download a CSV or PDF.",cta:"Take a look",later:"Not now"},[{id:"learn_more",type:"event",event:"announcement_clicked",properties:{},close:!0},Lo])},{id:"upgrade",label:"\u5347\u7EA7\u5230 Pro",description:"\u5217\u51FA\u51E0\u9879\u6743\u76CA\uFF0C\u5F15\u5BFC\u5347\u7EA7\u3002",document:Ei("\u5347\u7EA7\u5230 Pro",Or([{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{text:{color:"primary",weight:700}}},{type:"text",id:"title",text:"title",variant:"heading"},{type:"stack",id:"benefits",name:"\u6743\u76CA\u5217\u8868",direction:"vertical",align:"stretch",justify:"start",children:[{type:"text",id:"benefit1",text:"benefit1",variant:"body"},{type:"text",id:"benefit2",text:"benefit2",variant:"body"},{type:"text",id:"benefit3",text:"benefit3",variant:"body"}],style:{background:{type:"color",color:"surface"},shape:{type:"rect",radius:8},gap:4,padding:{top:16,right:16,bottom:16,left:16}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"upgrade",style:{width:"fill"}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}]),{eyebrow:"PRO",title:"\u89E3\u9501\u5168\u90E8\u9AD8\u7EA7\u529F\u80FD",benefit1:"\u2713 \u65E0\u9650\u9879\u76EE\u4E0E\u6210\u5458",benefit2:"\u2713 \u9AD8\u7EA7\u6570\u636E\u5206\u6790",benefit3:"\u2713 \u4F18\u5148\u5BA2\u670D\u652F\u6301",cta:"\u67E5\u770B Pro \u65B9\u6848",later:"\u7EE7\u7EED\u4F7F\u7528\u514D\u8D39\u7248"},{eyebrow:"PRO",title:"Unlock every advanced feature",benefit1:"\u2713 Unlimited projects and members",benefit2:"\u2713 Advanced analytics",benefit3:"\u2713 Priority support",cta:"See Pro plans",later:"Stay on Free"},[{id:"upgrade",type:"event",event:"checkout_requested",properties:{planId:"pro"},close:!0},Lo])},{id:"offer",label:"\u9650\u65F6\u4F18\u60E0",description:"\u6E10\u53D8\u5934\u56FE + \u89D2\u6807 + \u539F\u4EF7\u5212\u7EBF\u7684\u4F18\u60E0\u4EF7\uFF0C\u9002\u5408\u9886\u5238\u5F39\u7A97\u3002",document:{...Ei("\u9650\u65F6\u4F18\u60E0",{type:"stack",id:"root",direction:"vertical",align:"stretch",justify:"start",children:[{type:"stack",id:"hero",name:"\u5934\u56FE",direction:"overlay",align:"start",justify:"start",children:[{type:"stack",id:"heroContent",name:"\u5934\u56FE\u5185\u5BB9",direction:"vertical",align:"center",justify:"center",children:[{type:"text",id:"eyebrow",text:"eyebrow",variant:"caption",style:{width:"fit",padding:{top:3,right:10,bottom:3,left:10},background:{type:"color",color:"#FFFFFF2E"},shape:{type:"pill"},text:{color:"#FFFFFF",weight:700,letterSpacing:1,align:"center"}}},{type:"text",id:"title",text:"title",variant:"title",style:{text:{size:40,weight:900,color:"#FFFFFF",align:"center",lineHeight:1.1}}},{type:"text",id:"subtitle",text:"subtitle",variant:"body",style:{text:{size:14,color:"#FFFFFFD9",align:"center"}}}],style:{width:"fill",padding:{top:32,right:24,bottom:28,left:24},gap:6}},{type:"text",id:"badge",name:"\u89D2\u6807",text:"badge",variant:"caption",style:{width:"fit",margin:{top:14,right:0,bottom:0,left:14},padding:{top:4,right:10,bottom:4,left:10},background:{type:"color",color:"#FFD84D"},shape:{type:"pill"},shadow:{x:0,y:4,blur:10,spread:0,color:"#00000026"},text:{color:"#3A1D00",weight:800,size:13}}}],style:{gap:0,padding:{top:0,right:0,bottom:0,left:0},background:{type:"linear",angle:135,stops:[{color:"#FF7A45",at:0},{color:"#E8336D",at:100}]}}},{type:"stack",id:"body",name:"\u4EF7\u683C\u4E0E\u6309\u94AE",direction:"vertical",align:"stretch",justify:"start",children:[{type:"stack",id:"price",name:"\u4EF7\u683C",direction:"horizontal",align:"end",justify:"center",children:[{type:"text",id:"newPrice",text:"newPrice",variant:"title",style:{text:{size:34,weight:800,color:"#E8336D",lineHeight:1}}},{type:"text",id:"period",text:"period",variant:"body",style:{text:{color:"muted",size:14,lineHeight:1.6}}},{type:"text",id:"oldPrice",text:"oldPrice",variant:"body",style:{text:{color:"muted",size:15,decoration:"line-through",lineHeight:1.6}}}],style:{gap:8,padding:{top:0,right:0,bottom:0,left:0}}},{type:"text",id:"then",text:"then",variant:"caption",style:{text:{color:"muted",align:"center"}}},{type:"button",id:"cta",label:"cta",variant:"primary",action:"claim",style:{width:"fill",height:52,background:{type:"linear",angle:90,stops:[{color:"#FF7A45",at:0},{color:"#E8336D",at:100}]},shape:{type:"pill"},shadow:{x:0,y:10,blur:24,spread:-6,color:"#E8336D66"},text:{size:17,weight:800,color:"#FFFFFF"}}},{type:"button",id:"later",label:"later",variant:"link",action:"dismiss",style:{width:"fill"}}],style:{gap:14,padding:{top:22,right:24,bottom:22,left:24}}}],style:{gap:0,padding:{top:0,right:0,bottom:0,left:0}}},{eyebrow:"\u9650\u65F6 48 \u5C0F\u65F6",title:"\u9996\u6708 7 \u6298",subtitle:"\u65B0\u7528\u6237\u4E13\u4EAB \xB7 \u9886\u53D6\u540E 3 \u5929\u5185\u6709\u6548",badge:"-30%",newPrice:"$20.30",period:"/\u9996\u6708",oldPrice:"$29",then:"\u4E4B\u540E\u6BCF\u6708 $29\uFF0C\u53EF\u968F\u65F6\u53D6\u6D88",cta:"\u7ACB\u5373\u9886\u53D6",later:"\u6682\u4E0D\u9700\u8981"},{eyebrow:"48 HOURS ONLY",title:"30% off",subtitle:"For new members \xB7 valid 3 days after claiming",badge:"-30%",newPrice:"$20.30",period:"/first month",oldPrice:"$29",then:"Then $29/month. Cancel anytime.",cta:"Claim offer",later:"Not now"},[{id:"claim",type:"event",event:"offer_claimed",properties:{discount:30},close:!0},Lo]),theme:{...Ym,primary:"#E8336D",radius:"lg"}}},{id:"feedback",label:"\u6536\u96C6\u53CD\u9988",description:"\u4E24\u4E2A\u9009\u9879\u6309\u94AE\uFF0C\u8BB0\u5F55\u7528\u6237\u7684\u9009\u62E9\u3002",document:Ei("\u6EE1\u610F\u5EA6\u8C03\u67E5",Or([{type:"text",id:"title",text:"title",variant:"heading",style:{text:{align:"center"}}},{type:"text",id:"body",text:"body",variant:"body",style:{text:{align:"center",color:"muted"}}},{type:"stack",id:"choices",name:"\u9009\u9879",direction:"horizontal",align:"stretch",justify:"center",children:[{type:"button",id:"yes",label:"yes",variant:"secondary",action:"positive",style:{width:"fill"}},{type:"button",id:"no",label:"no",variant:"secondary",action:"negative",style:{width:"fill"}}],style:{gap:8,padding:{top:0,right:0,bottom:0,left:0}}}]),{title:"\u8FD9\u4E2A\u529F\u80FD\u5BF9\u4F60\u6709\u5E2E\u52A9\u5417\uFF1F",body:"\u4F60\u7684\u53CD\u9988\u4F1A\u76F4\u63A5\u5F71\u54CD\u6211\u4EEC\u4E0B\u4E00\u6B65\u505A\u4EC0\u4E48\u3002",yes:"\u6709\u5E2E\u52A9",no:"\u6CA1\u5E2E\u52A9"},{title:"Was this feature helpful?",body:"Your answer shapes what we build next.",yes:"Yes",no:"No"},[{id:"positive",type:"event",event:"feedback_submitted",properties:{helpful:!0},close:!0},{id:"negative",type:"event",event:"feedback_submitted",properties:{helpful:!1},close:!0}])}];function qo(e="blank"){let t=Zm.find(n=>n.id===e)??Zm[0];if(!t)throw new Error("Screen templates are unavailable");return structuredClone(t.document)}var sv=(e,t,n)=>({type:"stack",id:e,name:"Web \u81EA\u9002\u5E94\u5E03\u5C40",direction:"horizontal",align:"center",justify:"center",children:[{...Or(t),id:`${e}_intro`,name:"\u4ECB\u7ECD",style:{width:480,gap:20,padding:{top:0,right:0,bottom:0,left:0}}},{...Or(n),id:`${e}_detail`,name:"\u5185\u5BB9\u4E0E\u64CD\u4F5C",style:{width:400,gap:20,padding:{top:24,right:24,bottom:24,left:24},background:{type:"color",color:"surface"},shape:{type:"rect",radius:8}}}],style:{gap:40,padding:{top:40,right:24,bottom:40,left:24}}});function Cj(e,t="blank"){let n=qo(t);if(e==="popup"||(n.surface=e,n.presentation={type:"fullscreen"},e==="page"))return n;if(e==="paywall"){let r=qo("upgrade");r.actions=r.actions.map(a=>a.id==="upgrade"&&a.type==="event"?{...a,event:"paywall.upgrade_clicked",properties:{},close:!1}:a),(r.strings.locales["zh-CN"]??={}).cta="\u4E86\u89E3\u5347\u7EA7\u65B9\u6848",(r.strings.locales.en??={}).cta="Explore upgrade options",(r.strings.locales["zh-CN"]??={}).body="\u4E3A\u4F60\u7684\u5DE5\u4F5C\u533A\u9009\u62E9\u9002\u5408\u7684\u529F\u80FD\u4E0E\u534F\u4F5C\u65B9\u5F0F\u3002",(r.strings.locales.en??={}).body="Find the right features and collaboration tools for your workspace.";let i=r.pages[0];if(!i)throw new Error("Paywall template requires a page");let o=i.root.children;return i.root=sv("root",[...o.slice(0,2),{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}}],o.slice(2)),{...r,surface:e,presentation:{type:"fullscreen"},name:"\u9AD8\u7EA7\u529F\u80FD\u4ED8\u8D39\u5899"}}return{...n,surface:e,presentation:{type:"fullscreen"}}}function Jm(e,t){if(t!=="en"&&t!=="zh-CN")throw new Error("Unsupported blank content language");let n=t==="en"?{popup:"popup",paywall:"paywall",onboarding:"funnel",page:"page"}:{popup:"\u5F39\u7A97",paywall:"\u4ED8\u8D39\u5899",onboarding:"\u5F15\u5BFC\u6D41\u7A0B",page:"\u9875\u9762"},r=qo(),i=r.pages[0];if(!i)throw new Error("Blank template requires a page");return{...r,name:t==="en"?`Untitled ${n[e]}`:`\u672A\u547D\u540D${n[e]}`,surface:e,presentation:e==="popup"?{type:"modal",size:"md"}:{type:"fullscreen"},pages:[{id:"main",name:t==="en"?e==="onboarding"?"Start":"Main page":e==="onboarding"?"\u5F00\u59CB":"\u4E3B\u9875\u9762",root:{...i.root,name:t==="en"?"Canvas":"\u753B\u5E03",style:e==="popup"?{gap:16,padding:{top:32,right:28,bottom:28,left:28}}:{gap:16,padding:{top:24,right:24,bottom:24,left:24}},children:[]}}],strings:{defaultLocale:t,locales:{[t]:{}}},actions:[]}}import{z as pe}from"zod";var Ti=pe.number().int().min(0).max(1e4),jj=pe.strictObject({couponId:pe.uuid(),couponRevision:pe.number().int().nonnegative(),savedGroupId:pe.uuid(),savedGroupRevision:pe.number().int().nonnegative(),savedGroupName:pe.string().min(1).max(128),count:Ti,snapshotHash:pe.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:pe.iso.datetime({offset:!0})}),cv=pe.strictObject({id:pe.uuid(),couponId:pe.uuid(),couponName:pe.string().min(1).max(80),savedGroupId:pe.uuid(),savedGroupName:pe.string().min(1).max(128),savedGroupRevision:pe.number().int().nonnegative(),status:pe.enum(["pending","running","completed"]),total:Ti,issued:Ti,skipped:Ti,remaining:Ti,createdAt:pe.iso.datetime({offset:!0}),completedAt:pe.iso.datetime({offset:!0}).nullable()}).refine(e=>e.total>0&&e.total===e.issued+e.skipped+e.remaining&&e.status==="completed"==(e.completedAt!==null)&&(e.status!=="completed"||e.remaining===0)),uv=pe.strictObject({id:pe.uuid(),customerId:pe.uuid(),customerName:pe.string().max(255),position:pe.number().int().min(1).max(1e4),status:pe.enum(["pending","issued","skipped"]),grantId:pe.uuid().nullable(),reason:_o.nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),kj=pe.strictObject({batch:cv,recipients:pe.array(uv).max(50),nextPosition:pe.number().int().min(1).max(1e4).nullable()}),Dj=pe.discriminatedUnion("action",[pe.strictObject({action:pe.literal("create"),requestId:pe.uuid(),couponId:pe.uuid(),couponRevision:pe.number().int().nonnegative(),savedGroupId:pe.uuid(),savedGroupRevision:pe.number().int().nonnegative(),snapshotHash:pe.string().regex(/^[a-f0-9]{64}$/)}),pe.strictObject({action:pe.literal("process"),batchId:pe.uuid()})]);import{z as L}from"zod";var bt=L.number().int().min(0),Ri=L.iso.datetime({offset:!0}),Vo=L.strictObject({internalId:L.uuid(),version:L.number().int().positive()}),Xm=L.enum(["subscription_change_required","unsupported_operation_input"]),lv=L.enum([...Xm.options,"internal_error"]),Uj=L.strictObject({productId:L.string().min(1),productName:L.string(),from:Vo,to:Vo,noBillingChanges:L.boolean(),counts:L.strictObject({customers:bt,movable:bt,blocked:bt,unsupported:bt,canceled:bt,custom:bt}),rows:L.array(L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),holdings:L.number().int().positive(),outcome:L.enum(["move","blocked","unsupported"]),reason:Xm.nullable()})).max(50),nextCursor:L.uuid().nullable()}),dv=L.enum(["queued","running","succeeded","no_changes","failed","canceled"]),zm=L.enum(["running","succeeded","skipped","failed"]),ef=L.strictObject({internalId:L.uuid(),id:L.string().min(1),productId:L.string().min(1),productName:L.string(),from:Vo,to:Vo,noBillingChanges:L.boolean(),retryFailed:L.boolean(),step:L.enum(["queued","received","get_customers","migrate_customers","finished","failed"]),snapshot:L.strictObject({total_customers:bt,canceled_customers:bt,custom_customers:bt,migration_customers:bt}),createdAt:Ri,run:L.strictObject({id:L.uuid(),status:dv,errorMessage:L.string().nullable(),createdAt:Ri,startedAt:Ri.nullable(),finishedAt:Ri.nullable()}).nullable(),totals:L.strictObject({succeeded:bt,skipped:bt,failed:bt,running:bt,blocked:bt,remaining:bt})}),pv=L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),status:zm,skipReason:L.enum(["no_updates_needed","ineligible"]).nullable(),updatedAt:Ri,error:L.strictObject({code:lv,message:L.string().nullable()}).nullable()}),Mj=L.strictObject({migration:ef,items:L.array(pv).max(50),nextCursor:L.uuid().nullable()}),Bj=L.array(ef).max(20),Lj=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),requestId:L.uuid(),fromInternalId:L.uuid(),toInternalId:L.uuid()}),L.strictObject({action:L.enum(["process","retry","cancel"]),migrationId:L.uuid()})]),qj=L.discriminatedUnion("action",[L.strictObject({action:L.literal("preview"),from:L.uuid(),to:L.uuid(),after:L.uuid().optional()}),L.strictObject({action:L.literal("read"),migrationId:L.uuid(),status:zm.optional(),after:L.uuid().optional()}),L.strictObject({action:L.literal("list"),productId:L.string().min(1).max(120)})]);import{z as at}from"zod";var rc=at.iso.datetime({offset:!0}),tf=at.strictObject({internalId:at.uuid(),productId:at.string().min(1),name:at.string(),version:at.number().int().positive()}),mv=at.strictObject({id:at.uuid(),status:at.literal("scheduled"),effectiveAt:rc,createdAt:rc,entityId:at.string().nullable(),to:tf,from:tf.extend({customerProductId:at.uuid(),status:at.enum(["active","past_due","trialing"]),endsAt:rc.nullable()}).nullable(),scheduleId:at.uuid().nullable(),providerManaged:at.boolean()}),Gj=at.array(mv).max(100),Kj=at.strictObject({customerProductId:at.uuid()});import{z as ji}from"zod";var fv=ji.url().refine(e=>new URL(e).protocol==="https:"),Qj=ji.strictObject({requestId:ji.uuid()}),Zj=ji.strictObject({url:fv,createdAt:ji.iso.datetime()});import{z as He}from"zod";var nf=He.object({id:He.uuid(),key:He.string().nullable(),label:He.string().min(1).max(80),description:He.string().max(300),category:He.string().min(1).max(40),tags:He.array(He.string().max(30)).max(10),surface:qu,source:He.enum(["official","private"]),document:mt,revision:He.number().int().positive(),archived_at:He.string().nullable(),created_at:He.string()}).strict(),zj=He.object({projectId:He.uuid(),environmentId:He.uuid(),label:He.string().trim().min(1).max(80),description:He.string().trim().max(300),category:He.string().trim().min(1).max(40),document:mt}).strict(),ek=He.object({projectId:He.uuid(),environmentId:He.uuid(),id:He.uuid(),revision:He.number().int().positive()}).strict();import{z as M}from"zod";import{z as Oe}from"zod";import{z as st}from"zod";var Ze=st.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"),ic=st.strictObject({type:st.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:st.boolean(),enum:st.array(st.string().max(255)).min(1).max(100).optional()}),Er=ic.extend({type:st.enum([...ic.shape.type.options,"array"]),items:ic.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"})}),Tr=Er.safeExtend({source:st.discriminatedUnion("type",[st.strictObject({type:st.literal("input")}),st.strictObject({type:st.literal("node")}),st.strictObject({type:st.enum(["parameter","attribute"]),key:Ze})])}),hv=st.record(Ze,Tr),$o=st.record(Ze,Ze).refine(e=>Object.keys(e).length<=20);function Nt(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=>Nt(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&&st.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 oc(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&&oc(e.items,t.items)}function ir(e,t){let n={};for(let[r,i]of Object.entries(e)){let o=i.source,a=o.type==="input"?t.answers:o.type==="node"?t.results??{}:o.type==="parameter"?t.parameters:t.attributes,s=o.type==="parameter"||o.type==="attribute"?o.key:r;if(!Object.hasOwn(a,s))continue;let c=a[s];if(!Nt(i,c))throw new Error(`Invalid variable value: ${r}`);n[r]=c}return n}function or(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 ac(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,o]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!Nt(e[i],o))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var ki=he;function Go(e){let t={};for(let[n,r]of Object.entries(ir(e.declarations,e))){let i=n.split(".");if(i.some(s=>["__proto__","constructor","prototype"].includes(s)))throw new Error("Reserved result path");let o=t;for(let s of i.slice(0,-1)){Object.hasOwn(o,s)||(o[s]={});let c=o[s];if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Ambiguous result path");o=c}let a=i.at(-1);if(a===void 0)throw new Error("Empty result path");o[a]=r}return{...e.attributes,variables:t}}function sc(e,t){return Yi(Go(t),e,t.savedGroups)}function Di(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i.startsWith("$")||t.add(i),i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.attributeKey=="string"&&t.add(o.attributeKey),["$and","$or","$nor","$not"].includes(i)&&n(o)}return n(e),[...t]}import{z as ar}from"zod";var Gt=ar.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"),cn=ar.discriminatedUnion("source",[ar.strictObject({source:ar.literal("literal"),value:he}),ar.strictObject({source:ar.literal("variable"),key:ar.string().min(1).max(255),path:Gt.optional()})]);function Rr(e,t){if(!t)return e;for(let n of Gt.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 sr(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ir(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(he.parse(Rr(n[e.key],e.path)))}function rf(e,t){let n={},r=Object.entries(e).sort(([i],[o])=>i.split(".").length-o.split(".").length||i.localeCompare(o,"en",{numeric:!0}));for(let[i,o]of r){let a=Gt.parse(i).split("."),s=n;for(let u=0;u<a.length-1;u++){let l=a[u],d=a[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 m=Array.isArray(s)?s[Number(l)]:s[l];if(!m||typeof m!="object")throw new Error("Nested input requires an object or array");if(Array.isArray(m)!==/^(0|[1-9]\d*)$/.test(d))throw new Error("Nested input container does not match its path");s=m}let c=a.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,sr(o,t))}return n}var Ko=Oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),of=Oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),Ho=Vt.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),cc=Oe.record(Ko,Oe.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),gv=cn,af=Oe.strictObject({type:Oe.literal("external_task"),endpointId:Oe.uuid(),taskKey:Ko,inputs:Oe.record(Ko,gv).refine(e=>Object.keys(e).length<=20),outputs:cc}),sf=Oe.strictObject({maxAttempts:Oe.number().int().min(1).max(5),retryDelaySeconds:Oe.number().int().min(1).max(30),backoff:Oe.enum(["fixed","exponential"]),requestTimeoutSeconds:Oe.number().int().min(1).max(10),timeoutSeconds:Oe.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline"),cf={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},gk=Oe.strictObject({outcome:Oe.enum(["success","failure"]),data:Ho});function bk(e,t){let n=Ho.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(o=>typeof o=="string"):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function _k(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=sr(i,t);return Ho.parse(n)}var yk=Oe.discriminatedUnion("operation",[Oe.strictObject({operation:Oe.literal("signal"),runId:Oe.uuid(),nodeId:of,eventName:Ko,eventId:Oe.uuid(),data:Ho}),Oe.strictObject({operation:Oe.literal("read_results"),runId:Oe.uuid()})]),Sk=Oe.strictObject({scope:je,runId:Oe.uuid(),eventId:Oe.uuid(),accepted:Oe.boolean()}),bv=Oe.record(of,ki),vk=Oe.strictObject({scope:je,runId:Oe.uuid(),results:bv});import{z as U}from"zod";import{z as De}from"zod";var uc=De.enum(["local","remote"]),Ni=De.strictObject({port:De.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:he.optional(),sticky:De.array(De.strictObject({expected:Ji.nullable(),next:Ji})).max(100),exposures:De.array(he).max(100),features:De.array(he).max(100)}),Wo=De.strictObject({type:De.literal("evaluate"),receiptId:De.uuid(),environmentId:De.uuid(),policyRevision:De.number().int().nonnegative(),attributes:wt,sticky:De.record(De.string(),Ji)}),uf=Wo.extend({runId:De.uuid(),versionId:De.uuid(),nodeId:De.string().min(1).max(64),visit:De.number().int().nonnegative(),revision:De.number().int().nonnegative()}),lc=Wo.omit({type:!0,receiptId:!0}).extend({type:De.literal("evaluate_segment")}),Qo=De.strictObject({nodeId:De.string().min(1).max(64),result:Ni}),lf=lc.extend({runId:De.uuid(),versionId:De.uuid(),nodeId:De.string().min(1).max(64),visit:De.number().int().nonnegative(),revision:De.number().int().nonnegative(),parameters:Vt,answers:Kn,variables:De.record(De.string(),he)});var Fi=U.discriminatedUnion("type",[U.strictObject({type:U.literal("literal"),value:he}),U.strictObject({type:U.literal("variable"),key:Ze,path:Gt.optional()}),U.strictObject({type:U.literal("feature"),featureKey:U.string().min(1).max(128)})]),_v=U.strictObject({requestId:U.uuid(),decisionId:U.uuid(),customerId:U.uuid(),externalUserId:U.string().min(1).max(255).nullable(),versionId:U.uuid(),receiptId:U.uuid(),value:he}),dc={funnelId:U.uuid(),requestId:U.uuid(),customer:wr,customerData:Cr.optional(),attributes:wt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},Dk=U.discriminatedUnion("operation",[U.strictObject({operation:U.literal("decide"),...dc}).refine(nr,rr),U.strictObject({operation:U.literal("read_decision"),decisionId:U.uuid()}),U.strictObject({operation:U.literal("evaluate_decision"),decisionId:U.uuid(),requestId:U.uuid(),nodeId:U.string().min(1).max(64),visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),receiptId:U.uuid(),policyRevision:U.number().int().nonnegative(),generation:U.string().min(1).max(256),result:Ni}),U.strictObject({operation:U.literal("feature_config"),funnelId:U.uuid()}),U.strictObject({operation:U.literal("commit_decision_segment"),decisionId:U.uuid(),requestId:U.uuid(),nodeId:U.string().min(1).max(64),visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),policyRevision:U.number().int().nonnegative(),generation:U.string().min(1).max(256),steps:U.array(Qo).max(32),boundary:U.strictObject({nodeId:U.string().min(1).max(64),visit:U.number().int().nonnegative()}).optional()}),U.strictObject({operation:U.literal("segment_configuration"),funnelId:U.uuid(),versionId:U.uuid()}),U.strictObject({operation:U.literal("configuration"),funnelId:U.uuid(),versionId:U.uuid().optional()}),U.strictObject({operation:U.literal("local_configuration"),funnelId:U.uuid()}),U.strictObject({operation:U.literal("report_used"),decisionId:U.uuid(),eventId:U.uuid(),occurredAt:U.iso.datetime({offset:!0}),reference:U.string().min(1).max(128).optional()})]),Nk=U.strictObject({scope:je,decisionId:U.uuid(),requestId:U.uuid(),status:U.enum(["pending","completed","failed"]),decision:_v.nullable(),evaluation:U.discriminatedUnion("type",[uf,lf]).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"),Fk=U.strictObject({scope:je,decisionId:U.uuid(),eventId:U.uuid(),source:U.literal("caller_reported")});import{z as Je}from"zod";var df=Je.strictObject({type:Je.literal("bundle"),paywall:cn.optional(),offering:cn.optional(),coupons:cn,data:cn}),Zo=e=>Je.strictObject({type:Je.literal(e),id:Je.uuid()}),yv=Je.strictObject({type:Je.literal("bundle"),paywallVersionId:Je.uuid().optional(),offeringVersionId:Je.uuid().optional(),couponIds:Je.array(Je.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:he});function Vk(e,t,n){let r=o=>sr(o,t),i=Je.array(Zo("reward")).max(20).parse(r(e.coupons));for(let o of[e.paywall,e.offering,e.coupons]){if(!o)continue;let a=r(o);for(let s of Array.isArray(a)?a:[a])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 yv.parse({type:"bundle",...e.paywall?{paywallVersionId:Zo("paywall_version").parse(r(e.paywall)).id}:{},...e.offering?{offeringVersionId:Zo("offering_version").parse(r(e.offering)).id}:{},couponIds:i.map(o=>o.id),data:r(e.data)})}var $k=Je.strictObject({type:Je.literal("bundle"),offering:Zo("offering_version").nullable(),paywall:Je.strictObject({versionId:Je.uuid(),paywallId:Je.uuid(),offeringVersionId:Je.uuid()}).nullable(),coupons:Je.array(pi).max(20),data:he});function Gk(e){let t=o=>o?.source==="literal"&&o.value&&typeof o.value=="object"&&!Array.isArray(o.value)&&typeof o.value.id=="string"?o.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(o=>o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?[o.id]:[]),data:e.data.source==="literal"?e.data.value:{variable:e.data.key}}}import{z as zt}from"zod";import{z as ct}from"zod";var pf=ct.union([ct.string(),ct.number().finite(),ct.boolean(),ct.null()]),Sv=ct.union([pf,ct.array(pf).min(1).max(20)]),vv=ct.record(Gt,Sv).refine(e=>Object.keys(e).length<=10),pc=ct.strictObject({path:Gt,type:ct.enum(["string","number","boolean","strings"]),nullable:ct.boolean().optional(),aggregation:ct.enum(["count","exists"]).optional(),where:vv.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 Qk(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{let i=pc.parse(r),o=Rr(t,i.path);if(i.nullable&&o==null)return[n,null];if(i.aggregation){if(!Array.isArray(o))throw new Error("Collection projection requires an array");let s=o.filter(c=>Object.entries(i.where??{}).every(([u,l])=>{let d=Rr(c,u);return Array.isArray(l)?l.some(m=>m===d):l===d}));return[n,i.aggregation==="count"?s.length:s.length>0]}let a=i.type==="strings"?ct.array(ct.string()):i.type==="string"?ct.string():i.type==="number"?ct.number().finite():ct.boolean();return[n,a.parse(o)]}))}var xv=["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"],mf=zt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Iv=cn,ff=zt.discriminatedUnion("type",[af,zt.strictObject({type:zt.literal("claim_offer"),coupon:cn}),zt.strictObject({type:zt.literal("event"),event:mf}),zt.strictObject({type:zt.literal("api"),operation:zt.enum(xv),inputs:zt.record(Gt,Iv).refine(e=>Object.keys(e).length<=40),outputs:zt.record(mf,pc).refine(e=>Object.keys(e).length<=20)})]);function eD(e,t){return rf(e,t)}var Ge=M.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Av=M.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),Ft={id:Ge,name:M.string().trim().min(1).max(80),position:M.strictObject({x:M.number().finite(),y:M.number().finite()}).optional()},wv={success:Ge,cancel:Ge,unavailable:Ge,failure:Ge},mc=M.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),fc=M.enum(["same_window","new_window"]),Cv=M.discriminatedUnion("type",[M.strictObject({...Ft,type:M.literal("entry"),next:Ge}),M.strictObject({...Ft,type:M.literal("screen"),screenId:Ge,presentation:_n,outputs:M.record(Ge,Ge),offering:M.discriminatedUnion("source",[M.strictObject({source:M.literal("variable"),key:Ze}),M.strictObject({source:M.literal("fixed"),versionId:M.uuid()})]).optional()}),M.strictObject({...Ft,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:Ze}),next:Ge}),M.strictObject({...Ft,type:M.literal("coupon"),couponId:M.uuid(),writes:M.strictObject({value:Ze}),next:Ge}),M.strictObject({...Ft,type:M.literal("coupons"),couponIds:M.array(M.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:M.strictObject({value:Ze}),next:Ge}),M.strictObject({...Ft,type:M.literal("output"),value:M.discriminatedUnion("type",[...Fi.options,df,M.strictObject({type:M.literal("selection"),screenId:Ge,offeringKey:Ze})])}),M.strictObject({...Ft,type:M.literal("condition"),cases:M.array(M.strictObject({condition:An,target:Ge})).min(1).max(50),default:Ge}),M.strictObject({...Ft,type:M.literal("feature"),featureKey:M.string().min(1).max(128),writes:M.strictObject({value:Ze}),next:Ge}),M.strictObject({...Ft,type:M.literal("split"),experimentId:M.uuid(),routes:M.record(Av,Ge).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Ge}),M.strictObject({...Ft,type:M.literal("action"),...wv,execution:sf,action:ff,writes:$o.optional()}),M.strictObject({...Ft,type:M.literal("external_page"),appManifest:Ku.optional(),url:mc,openIn:fc,opened:Ge,failed:Ge}),M.strictObject({...Ft,type:M.literal("end"),outcome:M.enum(["completed","closed","ineligible","failed"]),output:Fi.optional()}),M.strictObject({...Ft,type:M.literal("wait"),writes:$o.optional(),wait:M.discriminatedUnion("type",[M.strictObject({type:M.literal("duration"),delaySeconds:M.number().int().min(1).max(2592e3),elapsed:Ge}),M.strictObject({type:M.literal("event"),eventName:Ge,outputs:cc,timeoutSeconds:M.number().int().min(1).max(2592e3),received:Ge,timeout:Ge})])})]),hc=M.strictObject({version:M.literal(5),entry:Ge,nodes:M.array(Cv).min(1).max(Qe.flowNodes)}),gc=hc.superRefine((e,t)=>{Pv(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function jr(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 Pv(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,d,m)=>{n.push(l),t?.({message:l,reason:d,path:m?["nodes",e.nodes.indexOf(m)]:[]})};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>Qe.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Qe.logicNodes)&&i("Flow node limit exceeded","budget");let o=new Set;for(let l of e.nodes){for(let d of jr(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"&&(o.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),o.add(l.screenId))}let a=new Set,s=new Set,c=new Set;function u(l){if(a.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){a.add(l),c.add(l);for(let d of jr(r.get(l)))u(d);a.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 Ov(e,t){let n=e.cases.findIndex(r=>sc(r.condition,t));return{ruleIndex:n<0?null:n,target:e.cases[n]?.target??e.default}}function mD(e,t,n,r){let i=e.nodes.find(c=>c.id===t.nodeId),o=[...t.history];if(!i||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let a,s=[];switch(n.type){case"start":if(i.type!=="entry")throw new Error("Flow already started");a=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");a=c}o.push(i.id);break;case"back":if(i.type!=="screen"||!o.length)throw new Error("No previous screen");if(a=o.pop(),e.nodes.find(c=>c.id===a)?.type!=="screen")throw new Error("Invalid screen history");break;case"condition":if(i.type!=="condition")throw new Error("Not a condition node");{let c=Ov(i,r);a=c.target,s.push({nodeId:i.id,...c})}break;case"feature":if(i.type!=="feature")throw new Error("Not a Feature node");a=i.next;break;case"configuration":if(i.type!=="offering"&&i.type!=="coupon")throw new Error("Not a configuration node");a=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");a=c}break;case"result":if(i.type!=="action")throw new Error("Not a capability invocation");a=i[n.result];break;case"page":if(i.type!=="external_page")throw new Error("Not an external page");a=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");a=i.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid event result");a=i.wait[n.result]}break}if(!e.nodes.some(c=>c.id===a))throw new Error("Target does not exist");return{state:{nodeId:a,history:o.slice(-Qe.pages),status:"running"},entered:[a],routed:s}}import{z as bc}from"zod";var Ui=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function _c(e,t,n){let r={},i,o,a,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>Yi(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=zr(e.featureKey,t),a=i.value,Object.assign(r,or(e,{value:a})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new Ui("Required GB Experiment is unavailable");if(o=Su(u,t),a=o.value,s=o.inExperiment&&!o.passthrough&&typeof a=="string"?a:"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:zr(e.configuration.featureKey,t).value;a={type:"offering_version",id:bc.uuid().parse(u)},Object.assign(r,or(e,{value:a})),c=e.next;break}case"coupon":case"coupons":a=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,or(e,{value:a})),c=e.next;break}return{port:s,target:c,projections:r,...a===void 0?{}:{value:a},...i?{feature:i}:{},...o?{experiment:o}:{}}}function hf(e,t,n){bc.uuid().parse(e),bc.number().int().nonnegative().parse(t);let r=Qi(Zi(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 nt}from"zod";import{z as _t}from"zod";var kr=_t.string().regex(/^[a-f0-9]{64}$/),Ev=Uu.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),gf=_t.strictObject({couponDigests:_t.record(_t.uuid(),kr),variables:_t.record(hn,_t.record(_t.uuid(),_t.partialRecord(_t.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),_t.string()))),locales:_t.record(hn,mr.extend({nodes:_t.record(_t.string(),_t.strictObject({base:Ev})),plans:_t.object({}).strict(),pickers:_t.object({}).strict()}).omit({paywall:!0}))});var bf=nt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),TD=nt.strictObject({operation:nt.literal("resolve_screen"),funnelId:nt.uuid(),versionId:nt.uuid(),screenId:bf,locale:hn,customerId:nt.uuid().optional()}),RD=nt.strictObject({scope:je,funnelId:nt.uuid(),versionId:nt.uuid(),screenId:bf,locale:hn,coupons:nt.record(nt.uuid(),nt.strictObject({available:nt.boolean(),offer:nt.strictObject({id:nt.uuid(),expiresAt:nt.iso.datetime()}).nullable()})),couponDigests:nt.record(nt.uuid(),kr)});import{z as E}from"zod";function Tv(e,t=[]){let n=[];Ct(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(Na(e).map(i=>i.key));for(let[i,o]of Object.entries(e.strings.locales))for(let a of Object.keys(o))r.has(a)||n.push(`Unused string ${a} must not be delivered (${i})`);return n}function _f(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>_f(t)??[])}}function Rv(e){let t=e.pages.map(i=>{let o=_f(i.root);return o?.type==="stack"?{...i,root:o}:{...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(Na({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,o])=>[i,Object.fromEntries(Object.entries(o).filter(([a])=>n.has(a)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function Yo(e,t=[]){let n=mt.parse(structuredClone(Rv(e))),r=o=>o.type!=="stack"||o.interaction!==void 0||o.children.some(r);for(let o of n.pages)if(!r(o.root))throw new Error(`Page ${o.id} has no visible content`);let i=Tv(n,t);if(i.length)throw new Error(i.join("; "));return n}function Jo(e,t){let n=[...t].sort((i,o)=>o.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&&!Gt.safeParse(r).success?null:{key:n,path:r}}function yc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Ct(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Mu))]}function Sc(e){return yc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function LD(e,t){let n=ir(t.declarations,t);return Object.fromEntries(Sc(e).flatMap(r=>{let i=Jo(r,Object.keys(t.declarations)),o=i&&Object.hasOwn(n,i.key)?Rr(n[i.key],i.path):void 0;return o!==void 0?[[r,he.parse(o)]]:[]}))}function qD(e,t,n){let r=i=>i.replace(/\{\{\s*variables\.([^{}]+?)\s*\}\}/g,(o,a)=>(a=a.trim(),a===t||a.startsWith(t+".")?"{{ variables."+n+a.slice(t.length)+" }}":o));return e.screens.map(i=>{if(i.type!=="owned")return i;let o=structuredClone(i.document);for(let a of Object.values(o.strings.locales))for(let s of Object.keys(a))a[s]=r(a[s]);return Ct(o,a=>{if(a.type==="custom_html")for(let s of Object.keys(a.html))a.html[s]=r(a.html[s])}),{...i,document:o}})}function yf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,o=(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 Di(c.condition))u.startsWith("variables.")&&o(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&o(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"&&o(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&o(e.action.coupon.key);let a=e.type==="output"?e.value:e.type==="end"?e.output:null;if(a?.type==="variable"&&o(a.key),a?.type==="bundle")for(let s of[a.paywall,a.offering,a.coupons,a.data])s?.source==="variable"&&o(s.key);return a?.type==="selection"&&o(a.offeringKey),[...i]}import{z as P}from"zod";var Dr=P.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Xo=e=>P.record(P.string(),he).refine(t=>gt(t)<=e,"Funnel evidence exceeds its byte budget"),QD=P.enum(["local_segment","evaluation","presentation","timer","event","operation"]),xc=P.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Ic=P.discriminatedUnion("type",[P.strictObject({type:P.literal("flag"),key:P.string().min(1).max(128)}),P.strictObject({type:P.literal("experiment"),id:P.uuid()}),P.strictObject({type:P.literal("saved_group"),id:P.uuid()}),P.strictObject({type:P.literal("config"),key:P.string().min(1).max(128)}),P.strictObject({type:P.literal("constant"),key:P.string().min(1).max(128)}),P.strictObject({type:P.literal("paywall_version"),id:P.uuid()}),P.strictObject({type:P.literal("offering_version"),id:P.uuid()}),P.strictObject({type:P.literal("reward"),id:P.uuid()})]),Nr=P.strictObject({schemaVersion:P.literal(1),kind:xc,selector:Ic.nullable(),context:Xo(131072),contract:P.strictObject({version:P.number().int().positive(),evaluator:P.string().min(1).max(128),policyRevision:P.number().int().nonnegative()})}).refine(e=>gt(e)<=131072,"Node input exceeds its byte budget"),Sf=P.strictObject({schemaVersion:P.literal(1),kind:xc,outcome:P.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Xo(131072),route:P.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Xo(131072)}).refine(e=>gt(e)<=131072,"Node result exceeds its byte budget"),ZD=P.strictObject({schemaVersion:P.literal(1),operations:P.record(Dr,P.strictObject({attempts:P.number().int().nonnegative(),maxAttempts:P.number().int().min(1).max(5),deadlineAt:P.iso.datetime({offset:!0}),retryAt:P.iso.datetime({offset:!0}).nullable(),error:P.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:P.strictObject({type:Dr,id:P.uuid()}).nullable()}))}).refine(e=>gt(e)<=65536,"Execution state exceeds its byte budget"),cr={receiptId:P.uuid()},vc=P.iso.datetime({offset:!0}),YD=P.discriminatedUnion("type",[P.strictObject({type:P.literal("node_entered"),details:P.strictObject({kind:xc})}),P.strictObject({type:P.literal("presentation_shown"),details:P.strictObject({...cr,source:P.literal("client"),occurredAt:vc.optional()})}),P.strictObject({type:P.literal("decision_accepted"),details:P.strictObject(cr)}),P.strictObject({type:P.literal("signal_received"),details:P.strictObject({signalId:P.uuid(),nodeId:Dr,eventName:Dr,data:Xo(8192),source:P.literal("server"),occurredAt:vc})}),P.strictObject({type:P.literal("signal_consumed"),details:P.strictObject({...cr,signalId:P.uuid()})}),P.strictObject({type:P.literal("wait_elapsed"),details:P.strictObject(cr)}),P.strictObject({type:P.literal("wait_timeout"),details:P.strictObject(cr)}),P.strictObject({type:P.literal("operation_completed"),details:P.strictObject({...cr,operation:Dr,reference:P.strictObject({type:Dr,id:P.uuid()}).nullable()})}),P.strictObject({type:P.literal("execution_recovered"),details:P.strictObject({generation:P.number().int().positive(),reason:P.enum(["interrupted","expired_lease","delivery_failed"])})}),P.strictObject({type:P.literal("execution_failed"),details:P.strictObject({generation:P.number().int().positive(),code:P.string().regex(/^[a-z_]{1,64}$/)})}),P.strictObject({type:P.literal("run_completed"),details:P.strictObject({outcome:P.enum(["completed","ineligible","failed"])})}),P.strictObject({type:P.literal("run_closed"),details:P.strictObject({source:P.enum(["client","server","expiry"])})}),P.strictObject({type:P.literal("treatment_used"),details:P.strictObject({...cr,source:P.enum(["client","server"]),occurredAt:vc,reference:P.string().min(1).max(128).optional()})})]);var Kt=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),jv=E.discriminatedUnion("type",[E.strictObject({id:Kt,type:E.literal("owned"),publicData:gf.optional(),document:mt.refine(e=>e.surface!=="paywall"&&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")}),E.strictObject({id:Kt,type:E.literal("paywall"),paywallVersionId:E.uuid()})]),wc={kind:E.literal("funnel"),schemaVersion:E.literal(4),screens:E.array(jv).max(Qe.pages),references:E.record(Kt,Ic).refine(e=>Object.keys(e).length<=500),inputs:E.array(E.strictObject({variable:Kt,screenId:Kt,componentId:Kt,required:E.boolean()})).max(Qe.questions),variables:E.record(Ze,Tr).refine(e=>Object.keys(e).length<=Qe.logicNodes),outputSchema:Er,execution:E.strictObject({runTimeoutSeconds:E.number().int().min(1).max(Bo.runTimeoutSeconds),maxTransitions:E.number().int().min(1).max(Bo.maxTransitions)})},Ut=E.strictObject({...wc,graph:hc});function kv(e,t){let n=!1,r=(i,o)=>{let a=i.type==="stack"||i.type==="button"?i.bind?.coupon??o:o;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(a&&t(a))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,a))};for(let i of e.pages)r(i.root);return n}function ea(e){return Array.isArray(e)?e.some(ea):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Qm:ea(n))}function Dv(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 o;try{o=Yo(i.document)}catch(a){t.push({message:a instanceof Error?a.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[a,s]of e.inputs.entries())s.screenId===i.id&&!oi(o,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",a]})}for(let[r,i]of e.graph.nodes.entries()){let o=["graph","nodes",r],a=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;a?.type==="owned"&&(a.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:o}),kv(a.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:o})),(i.type==="output"&&i.value.type==="literal"&&ea(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&ea(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:o})}return t}function vf(e,t){for(let{message:n,reason:r,path:i}of Dv(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function xf(e,t){let n=(g,p,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),o=(g,p)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let a=e.graph.nodes.filter(g=>g.type==="screen");(a.length!==i.size||a.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(p=>g!==p&&p.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,p){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let h=s.get(g)??new Set;h.add(p.id),s.set(g,h)}for(let[g,p]of e.graph.nodes.entries()){let h=["graph","nodes",g],y=p.type==="feature"?p.featureKey:p.type==="offering"&&p.configuration.source==="feature"?p.configuration.featureKey:p.type==="output"&&p.value.type==="feature"?p.value.featureKey:p.type==="end"&&p.output?.type==="feature"?p.output.featureKey:null;y&&!o("flag",y)&&n("Flag selectors require an explicit GB resource reference","feature",h);let A=p.type==="feature"||p.type==="offering"||p.type==="coupon"||p.type==="coupons"||p.type==="action"&&p.action.type==="api"?["value"]:p.type==="action"&&p.action.type==="external_task"?Object.keys(p.action.outputs):p.type==="wait"&&p.wait.type==="event"?Object.keys(p.wait.outputs):[],S="writes"in p?p.writes??{}:{};(A.length!==Object.keys(S).length||A.some(I=>!Object.hasOwn(S,I))||new Set(Object.values(S)).size!==Object.values(S).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[I,v]of Object.entries(S)){u(v,p);let $=e.variables[v],G=p.type==="offering"?"offering_version":p.type==="coupon"?"reward":p.type==="action"&&p.action.type==="api"?"json":p.type==="action"&&p.action.type==="external_task"?p.action.outputs[I]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[I]:void 0;($?.source.type!=="node"||G&&$.type!==G)&&n("Node writer source or output type does not match declaration","variable",h)}if(p.type==="coupons"){let I=e.variables[p.writes.value];(I?.type!=="array"||I.items?.type!=="reward"||I.items.nullable||I.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let v of p.couponIds)o("reward",v)||n("Coupons require Reward references","coupon",h)}if(p.type==="split"&&!o("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),p.type==="coupon"&&!o("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let I=p.action.coupon.value;(!I||typeof I!="object"||Array.isArray(I)||I.type!=="reward"||typeof I.id!="string"||Object.keys(I).length!==2||!o("reward",I.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!o("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),p.type==="screen"&&p.offering?.source==="variable"&&e.variables[p.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="variable"&&(e.variables[p.action.coupon.key]?.type!=="reward"||p.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),p.type==="screen"){let I=i.get(p.screenId);if(p.offering?.source==="fixed"&&!o("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),I?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",h),I?.type==="paywall"&&!o("paywall_version",I.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),I?.type==="owned"){let v=I.document.pages[0];if(!v){n("Owned screen requires a page","screen",h);continue}eo(I.document).some(G=>!G.complete)&&n("Owned screens require complete local content","translations",h);let $=new Set(I.document.actions.map(G=>G.id));($.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(G=>!$.has(G)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),ii(v.root,G=>{!p.offering&&(G.type==="plan_picker"||(G.type==="stack"||G.type==="button")&&G.bind?.plan||G.type==="customer_data"&&["customer_plans","credit_packs"].includes(G.data.source))&&n("Product presentation requires an Offering Version","offering",h),G.type==="customer_data"&&Object.values(G.data.outputs??{}).some(we=>we!==void 0&&!$.has(we))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",h),p.type==="end"&&p.output?.type==="literal"&&!Nt(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",h),p.type==="output"&&p.value.type==="literal"&&!Nt(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",h);let j=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(j?.type==="variable"&&!j.path){let I=e.variables[j.key];I&&!oc(I,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(p.type==="screen"){let I=i.get(p.screenId);if(I?.type==="owned")for(let v of yc(I.document))(/^(input|params)\./.test(v)||v.startsWith("variables.")&&!Jo(v.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(p.type==="condition")for(let I of p.cases){for(let v of dr(I.condition))o("saved_group",v)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let v of Di(I.condition))v.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[I,v]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let $=p.value[I];if($)if($.source==="literal"){let G=I==="coupons"?$.value:[$.value];(!Array.isArray(G)||G.length>20||G.some(we=>!Nt({type:v,nullable:!1},we)||!o(v,we.id))||I==="coupons"&&new Set(G.map(we=>we.id)).size!==G.length)&&n("Bundle requires distinct scoped resource references",I==="coupons"?"coupon":I==="paywall"?"paywall":"offering",[...h,"value",I])}else{let G=e.variables[$.key];($.path||!G||G.nullable||(I==="coupons"?G.type!=="array"||G.items?.type!=="reward"||G.items.nullable:G.type!==v))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,p]of e.graph.nodes.entries()){let h=p.type==="screen"?i.get(p.screenId):void 0,y=[...yf(p,c),...h?.type==="owned"?Sc(h.document).map(A=>Jo(A,c)?.key??A):[]];for(let A of new Set(y)){let v=function($){if($===p.id)return!0;if(I.has($))return!1;I.add($);let G=e.graph.nodes.find(Te=>Te.id===$);return G?(j.has($)?G.type==="action"?[G.cancel,G.unavailable,G.failure]:G.type==="wait"&&G.wait.type==="event"?[G.wait.timeout]:[]:jr(G)).some(v):!1};var m=v;if(!Object.hasOwn(e.variables,A)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let S=e.variables[A];if(p.type==="screen"&&S.source.type==="input"&&e.inputs.some($=>$.screenId===p.screenId&&$.variable===A)||S.source.type==="parameter"||S.source.type==="attribute")continue;let j=S.source.type==="input"?new Set(e.inputs.filter($=>$.variable===A&&$.required).flatMap($=>a.filter(G=>G.screenId===$.screenId).map(G=>G.id))):s.get(A)??new Set,I=new Set;(!j.size||v(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,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(p.screenId),y=h?.type==="owned"?oi(h.document,p.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 A=y.interaction.type==="toggle"?"boolean":y.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==A&&n("Input variable type does not match component","inputBinding",["inputs",g]);let S=e.variables[p.variable]?.enum;S&&!y.children.filter(j=>!j.hidden).every(j=>S.includes(j.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),p.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 p of g.document.pages)ii(p.root,()=>{l++});d+=g.document.actions.length}(l>Qe.components||d>Qe.actions||gt(e)>Qe.documentBytes)&&n("Funnel document exceeds its budget","budget")}var Cc=E.strictObject({...wc,graph:gc}).superRefine(xf),un=E.strictObject({...wc,graph:gc,displayName:E.string().trim().min(1).max(80)}).superRefine(xf),hN=un.superRefine(vf),gN=Cc.superRefine(vf),zo=E.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),Fr={requestId:E.uuid(),nodeId:Kt,visit:E.number().int().nonnegative(),revision:E.number().int().nonnegative(),customerToken:zo.optional()},Nv=E.discriminatedUnion("type",[E.strictObject({type:E.literal("screen"),output:Kt,answers:Kn,selection:E.record(Kt,E.union([E.string().max(200),E.boolean()])).optional()}),E.strictObject({type:E.literal("paywall_quote"),actionId:Kt,productVersionId:E.uuid(),offerId:E.uuid().optional(),nativeOffer:En.optional(),predecessor:E.strictObject({operationId:E.uuid().nullable(),generation:E.number().int().positive()}).optional()}),E.strictObject({type:E.literal("paywall_confirm"),operationId:E.uuid()}),E.strictObject({type:E.literal("paywall_cancel"),operationId:E.uuid()}),E.strictObject({type:E.literal("client_action"),receiptId:E.uuid(),outcome:E.enum(["success","cancel","failure","opened","failed"])})]),Fv=E.object({nodeId:Kt,visit:E.number().int().nonnegative(),revision:E.number().int().nonnegative(),components:E.record(Kt,E.object({resourceKey:E.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:E.number().int().min(1).max(1e5),after:to.nullable(),filter:E.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Mi=E.discriminatedUnion("operation",[E.strictObject({operation:E.literal("start"),funnelId:E.uuid(),requestId:E.uuid(),customer:wr.optional(),customerData:Cr.optional(),locale:E.string().min(1).max(35),parameters:Vt}).refine(nr,rr),E.strictObject({operation:E.literal("get"),settlementRequestId:E.uuid().optional(),data:Fv.optional(),purchase:E.strictObject({receiptId:E.uuid(),operationId:E.uuid()}).optional(),customerToken:zo.optional()}),E.strictObject({operation:E.literal("resume"),requestId:E.uuid(),customerToken:zo.optional()}),E.strictObject({operation:E.literal("submit"),...Fr,input:Nv}),E.strictObject({operation:E.literal("back"),...Fr}),E.strictObject({operation:E.literal("shown"),...Fr}),E.strictObject({operation:E.literal("close"),...Fr}),E.strictObject({operation:E.literal("commit_segment"),...Fr,policyRevision:E.number().int().nonnegative(),generation:E.string().min(1).max(256),steps:E.array(Qo).max(32),boundary:E.strictObject({nodeId:E.string().min(1).max(64),visit:E.number().int().nonnegative()}).optional()}),E.strictObject({operation:E.literal("evaluate"),...Fr,receiptId:E.uuid(),policyRevision:E.number().int().nonnegative(),generation:E.string().min(1).max(256),result:Ni}),E.strictObject({operation:E.literal("review"),receiptId:E.uuid().optional(),customerToken:zo.optional()})]);function Ac(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=Ac(n,t);if(r)return r}return null}function Uv(e,t,n,r,i){let o=e.graph.nodes.find(u=>u.id===t);if(o?.type!=="screen")throw new Error("Input is only accepted on a screen");let a=e.screens.find(u=>u.id===o.screenId),s=e.inputs.filter(u=>u.screenId===o.screenId),c={...r};for(let[u,l]of Object.entries(n)){let d=s.find(h=>h.variable===u);if(!d||a?.type!=="owned")throw new Error("Unknown screen input");let m=Ac(a.document.pages[0]?.root,d.componentId);if(m?.type!=="stack"||!m.interaction)throw new Error("Input is unavailable");let g=m.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"&&!E.email().safeParse(l).success)throw new Error("Invalid email");if(l&&g.keyboard==="url"&&!E.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"||!m.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=>!m.children.some(y=>y.id===h&&!y.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}let p=e.variables[u];if(p?.source.type!=="input"||!Nt(p,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)&&Uv(e,t,{[u.variable]:l},{},!1);let d=a?.type==="owned"?Ac(a.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}import{z as ye}from"zod";var Mv=ye.strictObject({id:ye.uuid(),projectId:ye.uuid(),environmentId:ye.uuid(),name:ye.string().min(1).max(80),revision:ye.number().int().nonnegative(),evaluationMode:uc,evaluationRevision:ye.number().int().nonnegative(),state:ye.enum(["active","paused","archived"]),publishedVersionId:ye.uuid().nullable(),updatedAt:ye.iso.datetime({offset:!0}),draft:Ut}),wN=ye.strictObject({rows:ye.array(Mv).max(200),nextCursor:ye.uuid().nullable()}),CN=ye.discriminatedUnion("action",[ye.strictObject({action:ye.literal("setEvaluationMode"),id:ye.uuid(),revision:ye.number().int().nonnegative(),evaluationMode:uc}),ye.strictObject({action:ye.literal("create"),requestId:ye.uuid(),name:ye.string().trim().min(1).max(80),document:Ut}),ye.strictObject({action:ye.literal("save"),id:ye.uuid(),revision:ye.number().int().nonnegative(),name:ye.string().trim().min(1).max(80),document:Ut}),ye.strictObject({action:ye.literal("terminateRun"),id:ye.uuid(),revision:ye.number().int().nonnegative(),runId:ye.uuid()}),ye.strictObject({action:ye.enum(["publish","archive","pause","activate","stop"]),id:ye.uuid(),revision:ye.number().int().nonnegative()})]).superRefine((e,t)=>{(e.action==="create"||e.action==="save")&&gt(e.document)>Qe.documentBytes&&t.addIssue({code:"custom",path:["document"],message:"Funnel document exceeds its byte budget"})});function PN(e){let t=e==="en",n=Jm("popup",e);n.name=t?"Welcome":"\u6B22\u8FCE";let r=n.pages[0];if(!r)throw new Error("Blank screen requires a page");return r.root.children=[{id:"heading",type:"text",text:"heading",variant:"title",style:{text:{align:"center"}}},{id:"body",type:"text",text:"body",variant:"body",style:{text:{align:"center"}}},{id:"continue_button",type:"button",label:"continue",variant:"primary",action:"continue",style:{width:"fill",margin:{top:8,right:0,bottom:0,left:0}}}],n.actions=[{id:"continue",type:"event",event:"continue",properties:{},close:!1}],n.strings.locales[e]={heading:t?"Welcome":"\u6B22\u8FCE",body:t?"Tell people what this step is for and what happens next.":"\u544A\u8BC9\u7528\u6237\u8FD9\u4E00\u6B65\u7684\u4F5C\u7528\uFF0C\u4EE5\u53CA\u63A5\u4E0B\u6765\u4F1A\u53D1\u751F\u4EC0\u4E48\u3002",continue:t?"Continue":"\u7EE7\u7EED"},Cc.parse({schemaVersion:4,references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",inputs:[],screens:[{id:"welcome",type:"owned",document:n}],graph:{version:5,entry:"entry",nodes:[{id:"entry",name:t?"Entry":"\u5165\u53E3",type:"entry",next:"welcome"},{id:"welcome",name:t?"Welcome":"\u6B22\u8FCE",type:"screen",screenId:"welcome",presentation:{type:"modal",size:"md"},outputs:{continue:"done"}},{id:"done",name:t?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed",output:{type:"literal",value:null}}]}})}import{z as N}from"zod";var jn=N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pc=N.enum(["running","waiting","completed","closed","ineligible","failed"]),Bv=N.discriminatedUnion("type",[Wo,lc,N.strictObject({type:N.literal("wait"),receiptId:N.uuid(),kind:N.enum(["timer","event","operation"]),deadline:N.iso.datetime({offset:!0}).nullable(),eventName:jn.optional()}),N.strictObject({type:N.literal("open_url"),receiptId:N.uuid(),url:mc,openIn:fc}),N.strictObject({type:N.literal("event"),receiptId:N.uuid(),event:jn})]),Lv=N.strictObject({type:N.literal("funnel"),id:N.uuid(),versionId:N.uuid()}),qv={id:jn,presentation:_n,outputs:N.array(jn).max(250),inputs:Ua,values:N.record(N.string(),he).optional(),offeringKey:Ze.optional(),capabilities:mr,customerData:Bu,dataCursors:N.record(jn,to.nullable())},Vv=N.strictObject({...qv,content:N.strictObject({type:N.literal("document"),document:mt})}),Oc=N.strictObject({id:N.uuid(),source:Lv,revision:N.number().int().nonnegative(),visit:N.number().int().nonnegative(),nodeId:jn,nodeType:N.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:Pc,stopped:N.boolean(),canBack:N.boolean(),recoveryRestricted:N.boolean().optional(),authenticated:N.boolean(),locale:N.string().min(1).max(35),answers:Kn,parameters:Vt,variables:N.record(N.string(),he),output:he.nullable(),screen:Vv.nullable(),paywall:N.strictObject({receiptId:N.uuid(),resolution:Do,quote:vi.nullable(),operation:Sr.nullable(),purchaseRequestId:N.uuid().nullable(),selectionGeneration:N.number().int().nonnegative().optional(),canReselect:N.boolean().optional()}).nullable(),instruction:Bv.nullable(),pendingRequest:N.strictObject({requestId:N.uuid(),authenticationRequired:N.boolean()}).nullable(),runExpiresAt:N.iso.datetime({offset:!0}),credentialExpiresAt:N.iso.datetime({offset:!0}).nullable()}),If=N.strictObject({scope:je,run:Oc,settlement:N.strictObject({requestId:N.uuid(),state:N.enum(["pending","unknown","settled"]),operationId:N.uuid().nullable(),receiptId:N.uuid().nullable().optional()}).optional(),purchase:N.strictObject({receiptId:N.uuid(),quote:vi.nullable(),operation:Sr.nullable(),canReselect:N.boolean().optional()}).optional(),review:N.strictObject({activeOperationId:N.uuid().nullable(),pages:N.array(N.strictObject({receiptId:N.uuid(),nodeId:jn,visit:N.number().int().nonnegative()})).max(100),page:N.strictObject({receiptId:N.uuid(),nodeId:jn,visit:N.number().int().nonnegative(),document:mt,answers:Kn,inputs:Ua,values:N.record(N.string(),he).optional()}).nullable(),coupons:N.array(N.strictObject({grantId:N.uuid(),status:N.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:N.string().nullable()})).max(100),purchases:N.array(N.strictObject({receiptId:N.uuid(),operationId:N.uuid(),status:N.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:N.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:N.uuid().optional()}),VN="X-Indiana-Server-Key";import{z as Ot}from"zod";import{z as ta}from"zod";var HN=ta.strictObject({operation:ta.literal("renew_run"),runId:ta.uuid(),customerId:ta.uuid()}),Af=If.refine(e=>!!e.runToken,"Renewal returns a credential");var eF=Ot.discriminatedUnion("operation",[Ot.strictObject({operation:Ot.literal("campaign_decide"),...dc}).refine(nr,rr),Ot.strictObject({operation:Ot.literal("campaign_start"),funnelId:Ot.uuid(),requestId:Ot.uuid(),customer:wr,customerData:Cr.optional(),locale:Ot.string().min(1).max(35),parameters:Vt,cooldownSeconds:Ot.number().int().min(1).max(2592e3)}).refine(nr,rr)]),tF=Ot.union([Ot.strictObject({scope:je,suppressed:Ot.literal(!0),reason:Ot.enum(["frequency","in_progress"]),retryAt:Ot.iso.datetime({offset:!0})}),Af]);import{z as Se}from"zod";function na(e,t){let n=new Set,r=new Set,i=new Set,o=[],a=new Map,s=new Map,c=new Map;function u(p){for(let h of dr(p))l(h)}function l(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let h=t.savedGroups[p];h&&(i.add(p),c.set(p,h),o.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function d(p){u(p.condition);for(let h of p.parentConditions??[])m(h.id),u(h.condition)}function m(p,h=!1){let y=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!y){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),a.set(p,y),o.push(()=>{for(let A of y.rules??[]){d(A);for(let S of A.tracks??[])d(S.experiment)}}))}function g(p){let h=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,h),o.push(()=>d(h)))}for(let p of e.graph.nodes){p.type==="feature"&&m(p.featureKey,!0),p.type==="split"&&g(p.experimentId),p.type==="condition"&&p.cases.forEach(y=>u(y.condition)),p.type==="offering"&&p.configuration.source==="feature"&&m(p.configuration.featureKey,!0);let h=p.type==="output"?p.value:p.type==="end"?p.output:null;h?.type==="feature"&&m(h.featureKey,!0)}for(let p of o)p();return{...t,features:Object.fromEntries(a),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var Ur=Se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cf=Se.strictObject({entry:Ur,nodes:Se.array(Se.strictObject({id:Ur,type:Se.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Se.record(Se.string(),Ur),writes:Se.record(Ze,Ze),resources:Se.strictObject({screenId:Ur.optional(),paywallVersionId:Se.uuid().optional(),couponId:Se.uuid().optional(),couponIds:Se.array(Se.uuid()).max(20).optional(),experimentId:Se.uuid().optional(),featureKey:Se.string().optional(),offeringVersionId:Se.uuid().optional()})})).min(1).max(500)}),wf={scope:je,funnelId:Se.uuid(),versionId:Se.uuid(),evaluationRevision:Se.number().int().nonnegative(),expiresAt:Se.iso.datetime({offset:!0}).nullable(),topology:Cf},Mr=Se.discriminatedUnion("evaluationMode",[Se.strictObject({...wf,evaluationMode:Se.literal("local"),growth:nn,conditions:Se.record(Ur,Se.array(Se.strictObject({condition:An,port:Se.string()})))}),Se.strictObject({...wf,evaluationMode:Se.literal("remote")})]),$v=Mr.options[0].extend({evaluation:Se.strictObject({maxTransitions:Se.number().int().min(1).max(1e4),variables:Se.record(Ze,Tr),outputSchema:Er,terminals:Se.record(Ur,Se.strictObject({outcome:Se.enum(["completed","closed","ineligible","failed"]),output:Fi.nullable()}))})});function Gv(e){return Cf.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 o=e.screens.find(a=>a.id===t.screenId);o?.type==="paywall"&&(r.paywallVersionId=o.paywallVersionId)}break;case"condition":t.cases.forEach((o,a)=>{n[`case:${a}`]=o.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 o of["success","cancel","unavailable","failure"])n[o]=t[o];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=Se.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 Kv(e){let t=un.parse(e.document),n=e.evaluationMode==="local"?nn.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:Gv(t)};return Mr.parse(e.evaluationMode==="remote"?r:{...r,growth:na(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((o,a)=>({condition:o.condition,port:`case:${a}`}))]))})}function mF(e){let t=Kv(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=un.parse(e.document);return $v.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 B}from"zod";var Of={commands:Qe.flowNodes*4,receipts:Qe.flowNodes*2,requestBytes:Qe.documentBytes+2e6},Br=B.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Pf={requestId:B.uuid(),nodeId:Br,visit:B.number().int().nonnegative(),revision:B.number().int().nonnegative()},Hv=B.union([Mi.options[3].omit({customerToken:!0}),Mi.options[4].omit({customerToken:!0}),Mi.options[5].omit({customerToken:!0}),Mi.options[6].omit({customerToken:!0}),B.strictObject({operation:B.literal("wait"),...Pf,result:B.enum(["elapsed","received","timeout"])}),B.strictObject({operation:B.literal("simulate"),...Pf,outcome:B.enum(["success","cancel","failure","unavailable"])})]),Ec=B.enum(["success","cancel","failure","unavailable","pending"]),Tc=B.strictObject({seed:B.uuid(),now:B.iso.datetime({offset:!0}),locale:B.string().min(2).max(35),currency:oe,parameters:Vt,attributes:B.record(B.string(),ki).refine(e=>Object.keys(e).length<=100),authenticated:B.boolean(),holdings:B.enum(["sample","empty"]),results:B.record(B.string(),he).optional(),outcomes:B.record(Br,Ec),variants:B.record(Br,B.string().min(1).max(128).nullable())}),Rc=B.strictObject({schemaVersion:B.literal(1),growth:nn,paywalls:B.record(B.uuid(),ko),offerings:B.record(B.uuid(),vr),surfaces:B.record(Br,he)}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=1e6,"Preview dependencies exceed their byte budget"),Wv=B.array(B.strictObject({command:Hv,authenticated:B.boolean(),outcome:Ec})).max(Of.commands),Qv=B.discriminatedUnion("type",[B.strictObject({type:B.literal("draft"),document:Ut}),B.strictObject({type:B.literal("snapshot"),id:B.uuid()})]),CF=B.strictObject({previewId:B.uuid(),source:Qv,scenario:Tc,journal:Wv,dependencySnapshot:Rc.optional()}),PF=B.strictObject({mode:B.literal("simulation"),run:Oc,dependencySnapshot:Rc,traceTruncated:B.boolean(),trace:B.array(B.strictObject({nodeId:Br,visit:B.number().int().nonnegative(),type:B.enum(["entered","shown","assigned","feature_evaluated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:B.record(B.string(),B.union([B.string(),B.number(),B.boolean(),B.null()]))})).max(2e3),receipts:B.array(B.strictObject({id:B.uuid(),nodeId:Br,visit:B.number().int().nonnegative(),outcome:Ec})).max(Of.receipts)}),OF=B.strictObject({id:B.uuid(),projectId:B.uuid(),environmentId:B.uuid(),document:Ut,scenario:Tc,dependencySnapshot:Rc,expiresAt:B.iso.datetime({offset:!0})}),EF=B.discriminatedUnion("action",[B.strictObject({action:B.literal("create"),requestId:B.uuid(),document:Ut,scenario:Tc}),B.strictObject({action:B.literal("revoke"),id:B.uuid()})]);import{z as xe}from"zod";var jF=xe.object({overall:xe.object({entered:xe.number(),running:xe.number(),closed:xe.number(),completed:xe.number(),authenticated:xe.number(),authReached:xe.number(),paid:xe.number(),free:xe.number()}),steps:xe.array(xe.object({node_id:xe.string(),visitors:xe.number()})),edges:xe.array(xe.object({node_id:xe.string(),target:xe.string(),visitors:xe.number()})),currencies:xe.array(xe.object({currency:xe.string(),grossCents:xe.number(),refundCents:xe.number()})),variants:xe.array(xe.object({experimentId:xe.uuid(),revision:xe.number(),variantId:xe.string(),exposed:xe.number(),completed:xe.number(),paid:xe.number(),exposedRuns:xe.number().optional(),completedRuns:xe.number().optional(),paidRuns:xe.number().optional()}))});var jc={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 NF(e,t,n=[],r={}){let i=Xi(t)??"en",[o="en",...a]=i.split("-"),s=o==="zh"&&!a.includes("Hans")&&a.some(h=>["Hant","TW","HK","MO"].includes(h))?"zh-Hant":o,c=jc[s]??jc.en,u=jc[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",m=[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&&Ef(e.eligibility.condition)?`: ${Ef(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 "),p=[m,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:m,validity:g,terms:p}}function Ef(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(", "):""}var kc={"popup-coupon-welcome-ticket":{discount:"20%",zh:"\u9996\u671F\u8BA2\u9605\u4F18\u60E0",en:"Off your first subscription payment"},"popup-coupon-return-ticket":{discount:"$5",zh:"\u56DE\u6765\u7EE7\u7EED\u4F60\u7684\u8BA1\u5212",en:"Pick up where you left off"},"popup-coupon-launch-poster":{discount:"30%",zh:"\u65B0\u7248\u672C\u4E0A\u7EBF\u4F18\u60E0",en:"A special offer for our new release"},"popup-coupon-friday-poster":{discount:"40%",zh:"\u6D3B\u52A8\u671F\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for the campaign"},"popup-coupon-studio-split":{discount:"25%",zh:"\u4E3A\u521B\u4F5C\u8005\u51C6\u5907\u7684\u8BA2\u9605\u793C\u9047",en:"A subscription offer for creators"},"popup-coupon-team-split":{discount:"$10",zh:"\u56E2\u961F\u65B9\u6848\u9996\u671F\u51CF\u514D",en:"Off the first payment on a team plan"},"popup-coupon-member-letter":{discount:"20%",zh:"\u4E00\u4EFD\u4E13\u5C5E\u7684\u4F1A\u5458\u793C\u9047",en:"A membership offer just for you"},"popup-coupon-founder-letter":{discount:"30%",zh:"\u7ED9\u65E9\u671F\u652F\u6301\u8005\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for early supporters"},"popup-coupon-gift-box":{discount:"$5",zh:"\u4F60\u7684\u4E0B\u4E00\u6B21\u8BA2\u9605\u4F18\u60E0",en:"An offer for your next subscription"},"popup-coupon-birthday-box":{discount:"25%",zh:"\u751F\u65E5\u4E3B\u9898\u4F1A\u5458\u4F18\u60E0",en:"A birthday-themed membership offer"},"popup-coupon-first-receipt":{discount:"20%",zh:"\u9996\u671F\u4ED8\u6B3E\u6298\u6263",en:"A discount on the first payment"},"popup-coupon-loyalty-receipt":{discount:"$8",zh:"\u8001\u5BA2\u6237\u8BA2\u9605\u793C\u9047",en:"A subscription offer for returning customers"},"popup-coupon-upgrade-sheet":{discount:"20%",zh:"\u4E86\u89E3\u8BA2\u9605\u4F18\u60E0",en:"Explore a subscription offer"},"popup-coupon-return-sheet":{discount:"$5",zh:"\u56DE\u5F52\u8BA2\u9605\u4F18\u60E0",en:"A returning subscriber offer"},"popup-coupon-minimal-number":{discount:"20%",zh:"\u9996\u671F\u8BA2\u9605\u51CF\u514D",en:"Off the first subscription payment"},"popup-coupon-bold-number":{discount:"50%",zh:"\u6D3B\u52A8\u8BA2\u9605\u6298\u6263",en:"A campaign subscription discount"},"popup-coupon-studio-editorial":{discount:"25%",zh:"\u4E13\u4E1A\u8BA2\u9605\u65B9\u6848\u4F18\u60E0",en:"An offer on a professional subscription"},"popup-coupon-autumn-editorial":{discount:"30%",zh:"\u79CB\u5B63\u8BA2\u9605\u6D3B\u52A8",en:"An autumn subscription campaign"},"popup-coupon-vip-pass":{discount:"20%",zh:"\u4F1A\u5458\u8BA2\u9605\u793C\u9047",en:"A membership subscription offer"},"popup-coupon-beta-pass":{discount:"35%",zh:"\u65E9\u671F\u4F53\u9A8C\u8005\u4F18\u60E0",en:"An offer for early adopters"},"popup-coupon-welcome-stamp":{discount:"20%",zh:"\u9996\u6B21\u8BA2\u9605\u793C\u9047",en:"A first subscription offer"},"popup-coupon-milestone-stamp":{discount:"$5",zh:"\u7EE7\u7EED\u524D\u884C\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for your next step"},"popup-coupon-quiet-frame":{discount:"15%",zh:"\u4E13\u6CE8\u5DE5\u4F5C\u6D41\u8BA2\u9605\u4F18\u60E0",en:"An offer for a focused workflow"},"popup-coupon-premium-frame":{discount:"25%",zh:"\u7CBE\u9009\u4F1A\u5458\u65B9\u6848\u793C\u9047",en:"An offer on selected membership plans"},"popup-coupon-starter-steps":{discount:"20%",zh:"\u4E86\u89E3\u4F18\u60E0\uFF0C\u9886\u53D6\u540E\u9009\u5957\u9910",en:"Explore the offer, then choose your plan"},"popup-coupon-comeback-steps":{discount:"$5",zh:"\u4E3A\u56DE\u5F52\u51C6\u5907\u7684\u8BA2\u9605\u4F18\u60E0",en:"A subscription offer for your return"},"popup-coupon-spring-banner":{discount:"20%",zh:"\u6625\u5B63\u8BA2\u9605\u793C\u9047",en:"A spring subscription offer"},"popup-coupon-year-banner":{discount:"30%",zh:"\u65B0\u5E74\u4F1A\u5458\u8BA2\u9605\u4F18\u60E0",en:"A new-year membership offer"},"popup-coupon-mono-card":{discount:"20%",zh:"\u4E13\u4E1A\u5DE5\u5177\u8BA2\u9605\u4F18\u60E0",en:"An offer on professional tools"},"popup-coupon-night-card":{discount:"$5",zh:"\u521B\u4F5C\u5DE5\u5177\u8BA2\u9605\u4F18\u60E0",en:"An offer on creative tools"},"popup-coupon-spotlight-panel":{discount:"30%",zh:"\u4E13\u4E1A\u7248\u8BA2\u9605\u6D3B\u52A8",en:"A professional subscription campaign"},"popup-coupon-summer-panel":{discount:"25%",zh:"\u590F\u5B63\u8BA2\u9605\u4F18\u60E0",en:"A summer subscription offer"}};function Tf(e){return e.actions.map(t=>t.properties.templateKey).find(t=>typeof t=="string"&&t.startsWith("popup-coupon-"))}function BF(e,t){let n=Tf(e);if(!n||!Object.hasOwn(kc,n))return e;let r=i=>{let o={...i.root.bind,coupon:t};return i.root.bind?.coupon!==t&&delete o.promotionCode,{bind:o}};return{...e,pages:e.pages.map(i=>({...i,root:{...i.root,...r(i)}})),actions:e.actions.map(i=>i.properties.templateKey===n&&i.type!=="close"?{id:i.id,type:"claim_offer",couponId:t,event:"offer.claimed",properties:i.properties,close:i.close}:i)}}function LF(e){let t=Tf(e),n=t?kc[t]:void 0;return!n||e.actions.some(r=>r.type==="claim_offer")?e:{...e,strings:{...e.strings,locales:Object.fromEntries(Object.entries(e.strings.locales).map(([r,i])=>[r,Object.fromEntries(Object.entries(i).map(([o,a])=>[o,a.replaceAll("{{offer.discount}}",n.discount).replaceAll("{{offer.headline}}",r.startsWith("zh")?n.zh:n.en).replaceAll("{{offer.terms}}",r.startsWith("zh")?"\u6F14\u793A\u91D1\u989D \xB7 \u7ED1\u5B9A\u4F18\u60E0\u5238\u540E\u81EA\u52A8\u663E\u793A\u771F\u5B9E\u6761\u6B3E":"Demo amount \xB7 Bind a coupon to show actual terms")]))]))}}}import{z}from"zod";var Ht=z.string().min(1).max(255),kn=z.number().finite().nonnegative(),Rf=z.strictObject({properties:z.record(z.string().min(1).max(64),z.union([z.string().min(1).max(128),z.number().finite(),z.boolean()]).transform(String).pipe(z.string())).refine(e=>Object.keys(e).length>=1&&Object.keys(e).length<=4)}),Zv=z.strictObject({feature_id:Ht,enabled:z.boolean().default(!1),threshold:z.number().finite(),quantity:z.number().finite().min(1),purchase_limit:z.strictObject({interval:z.enum(["hour","day","week","month"]),interval_count:z.number().finite().min(1).default(1),limit:z.number().finite().min(1)}).optional(),invoice_mode:z.boolean().optional()}),Yv=z.strictObject({feature_id:Ht.optional(),enabled:z.boolean().default(!1),limit_type:z.enum(["absolute","usage_percentage"]).optional(),overage_limit:kn.optional(),skip_overage_billing:z.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"),Jv=z.strictObject({feature_id:Ht,enabled:z.boolean().default(!0),limit:kn,interval:z.enum(["day","week","month","year"]),anchor:z.enum(["billing_cycle","utc"]).optional(),filter:Rf.optional()}),Xv=z.strictObject({feature_id:Ht.optional(),enabled:z.boolean().default(!0),threshold:kn,threshold_type:z.enum(["usage","usage_percentage","remaining","remaining_percentage"]),basis:z.enum(["balance","included","recurring","usage_limit"]).default("balance"),filter:Rf.optional(),name:z.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"),zv=z.strictObject({feature_id:Ht,enabled:z.boolean().default(!1)}),e0=z.strictObject({auto_topups:z.array(Zv).nullable(),spend_limits:z.array(Yv).nullable(),usage_limits:z.array(Jv).nullable(),usage_alerts:z.array(Xv).nullable(),overage_allowed:z.array(zv).nullable()}),GF=e0.omit({auto_topups:!0}),t0=Ar,KF=z.strictObject({internal_id:z.uuid(),id:Ht.nullable(),project_id:z.uuid(),environment_id:z.uuid(),name:z.string().max(80).nullable(),email:z.string().max(254).nullable(),metadata:t0.nullable(),created_at:z.number().finite().nonnegative().max(864e13)}),HF=z.strictObject({id:Ht,internal_product_id:Ht,product_id:Ht.nullable(),status:z.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:kn.nullable(),free_trial_id:Ht.nullable(),trial_ends_at:kn.nullable(),starts_at:kn.nullable(),access_starts_at:kn.nullable(),ended_at:kn.nullable(),product:z.strictObject({internal_id:Ht,id:Ht,name:z.string(),version:z.number().int().positive(),is_add_on:z.boolean()})});function YF(e,t,n=[]){let r={nodes:{}},i=t.startsWith("zh"),o=(s,c)=>i?s:c,a=(s,c,u,l,d=[])=>({id:s,label:c,value:u,status:l,detail:d,facts:[]});return Ct(e,s=>{if(s.type!=="customer_data")return;let c={...Lu(s.data.source),status:"ready",stale:!1,preview:!0};if(s.data.source==="credit_balance"){let u=s.data.resourceKey??n[0]?.key??"credits";c.resources=[{key:u,name:n.find(l=>l.key===u)?.label??o("\u521B\u4F5C\u79EF\u5206","Creative credits"),spendable:"3,840",available:"4,040",reserved:"200",expiry:o("1,200 \xB7 2026\u5E7411\u67081\u65E5","1,200 \xB7 November 1, 2026"),sources:[a("sample-monthly",o("\u4F1A\u5458\u6708\u5EA6\u79EF\u5206","Monthly membership credits"),"2,640",o("\u53EF\u7528","Available")),a("sample-pack",o("\u8D2D\u4E70\u79EF\u5206\u5305","Purchased credit pack"),"1,200",o("\u53EF\u7528","Available"))],sourceCount:2,sourcePage:1,hasNextSources:!1,hasPreviousSources:!1}]}else s.data.source==="credit_transactions"?(c.rows=[a("sample-usage-1",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67083\u65E5 09:42","Oct 3, 09:42")]),a("sample-usage-2",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u9884\u6263","Reserved"),[o("10\u67083\u65E5 09:30","Oct 3, 09:30")]),a("sample-usage-3",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u9000\u56DE","Refund"),[o("10\u67082\u65E5 16:10","Oct 2, 16:10")]),a("sample-usage-4",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 15:24","Oct 2, 15:24")]),a("sample-usage-5",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 14:08","Oct 2, 14:08")])].slice(0,s.data.pageSize),c.rows.forEach((u,l)=>{u.facts=[{label:o("\u521B\u4F5C\u79EF\u5206","Creative credits"),value:l%2===1?"180":l===4?"24":"12"}]})):s.data.source==="membership"?c.rows=[a("sample-plan",o("\u4E13\u4E1A\u7248 \xB7 \u6708\u4ED8","Pro \xB7 Monthly"),"",o("\u6709\u6548","Active"),[o("\u5F53\u524D\u5468\u671F\u7ED3\u675F \xB7 2026\u5E7411\u67081\u65E5","Current period ends \xB7 November 1, 2026")])]:s.data.source==="customer_plans"?c.rows=[a("sample-free",o("\u57FA\u7840\u7248","Starter"),o("\u514D\u8D39","Free"),o("\u53EF\u9009\u62E9","Available")),a("sample-pro",o("\u4E13\u4E1A\u7248","Pro"),o("$29 / \u6708","$29 / month"),o("\u5F53\u524D\u5957\u9910","Current plan")),a("sample-team",o("\u56E2\u961F\u7248","Team"),o("$79 / \u6708","$79 / month"),o("\u53EF\u9009\u62E9","Available"))].slice(0,s.data.pageSize):s.data.source==="billing_controls"?c.rows=[a("sample-control",o("\u6708\u5EA6\u7528\u91CF\u4E0A\u9650","Monthly usage limit"),"240 / 1,000",o("\u793A\u4F8B \xB7 \u672A\u6388\u6743\u4ED8\u6B3E","Sample \xB7 Payments not authorized"),[o("\u4EC5\u5C55\u793A\u793A\u4F8B\uFF0C\u9884\u89C8\u4E0D\u4F1A\u542F\u7528\u81EA\u52A8\u5145\u503C\u6216\u540E\u4ED8\u8D39\u3002","Preview does not authorize auto top-ups or postpaid billing.")])]:s.data.source==="billing"?c.rows=[{...a("sample-invoice","GROW-2026-001","$29.00",o("\u5DF2\u652F\u4ED8","Paid"),["October 1, 2026"]),billingActions:[{action:"invoice_open",label:o("\u67E5\u770B\u53D1\u7968","View invoice")}]}]:s.data.source==="credit_packs"?c.rows=[a("sample-pack-small",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12","",[o("1,200 \u79EF\u5206 \xB7 90 \u5929\u6709\u6548","1,200 credits \xB7 90 days validity")]),a("sample-pack-large",o("\u521B\u4F5C\u6269\u5C55\u5305","Creative expansion"),"$40","",[o("5,000 \u79EF\u5206 \xB7 180 \u5929\u6709\u6548","5,000 credits \xB7 180 days validity")])].slice(0,s.data.pageSize).map((u,l)=>({...u,...s.data.allowPurchase?{purchaseId:`10000000-0000-4000-8000-${String(l+1).padStart(12,"0")}`}:{}})):s.data.source==="credit_pack_orders"?c.rows=[a("sample-order",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12",o("\u5DF2\u4ED8\u6B3E","Paid"),["2026-10-01 12:30"])]:c.rows=[a("sample-offer",o("\u4F1A\u5458\u7EED\u8D39\u4F18\u60E0","Membership renewal offer"),"",o("\u53EF\u7528","Available"),[o("2026\u5E7411\u67081\u65E5\u5230\u671F","Expires November 1, 2026")])];r.nodes[s.id]=c}),r}import{z as Ee}from"zod";import{z as le}from"zod";var n0=le.enum(["customer","coupon","audience"]),r0=le.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),ra=le.object({baseRevision:le.number().int().nonnegative(),latestRevision:le.number().int().nonnegative(),mode:le.enum(["merge","use_latest"]),decisions:le.array(le.object({field:r0,mine:le.number().int().min(0).max(1e3),latest:le.number().int().min(0).max(1e3)}).strict().refine(e=>e.mine+e.latest>0)).max(28)}).strict().refine(e=>e.latestRevision>e.baseRevision).refine(e=>new Set(e.decisions.map(t=>t.field)).size===e.decisions.length).refine(e=>e.mode!=="use_latest"||e.decisions.length===0),jf=le.number().int().nonnegative().nullable(),i0=le.object({resource:n0,id:le.uuid(),projectId:le.uuid(),environmentId:le.uuid(),fromRevision:jf,toRevision:jf,provenance:le.enum(["recorded","historical"]),changes:le.array(le.object({field:le.string(),redacted:le.boolean(),before:le.union([le.string(),le.number(),le.boolean(),le.null()]),after:le.union([le.string(),le.number(),le.boolean(),le.null()])})),merge:ra.safeExtend({source:le.literal("client")}).nullable()}),o0=le.object({createdAt:le.iso.datetime({offset:!0}),id:le.uuid()}).strict(),zF=le.object({events:le.array(le.object({id:le.uuid(),action:le.string(),actorId:le.uuid().nullable(),actorEmail:le.email().nullable(),createdAt:le.iso.datetime({offset:!0}),object:i0})),nextCursor:o0.nullable()});var i2={type:"condition",condition:{}},o2=Ee.strictObject({id:Ee.uuid(),name:Ee.string().min(1).max(80),description:Ee.string().max(500),config:ka,revision:Ee.number().int().min(1),status:Ee.enum(["active","archived"]),batchable:Ee.boolean(),created_at:Ee.iso.datetime({offset:!0}),updated_at:Ee.iso.datetime({offset:!0})}),a2=Ee.discriminatedUnion("action",[Ee.strictObject({action:Ee.literal("save"),id:Ee.uuid().nullable(),audit:ra.nullable().optional(),revision:Ee.number().int().min(0),name:Ee.string().trim().min(1).max(80),description:Ee.string().max(500),config:ka}),Ee.strictObject({action:Ee.literal("archive"),id:Ee.uuid(),audit:ra.nullable().optional(),revision:Ee.number().int().min(1)})]),a0=Ee.object({id:Ee.uuid(),name:Ee.string().nullable(),external_user_id:Ee.string(),attributes:wt,created_at:Ee.iso.datetime({offset:!0})}),s2=Ee.object({customers:a0.array(),hasMore:Ee.boolean(),offset:Ee.number().int().min(0),limit:Ee.number().int().min(1),evaluatedAt:Ee.iso.datetime({offset:!0}),revision:Ee.number().int().min(1)});import{z as Bi}from"zod";var d2=Bi.object({defaultLocale:hn,locales:Bi.record(hn,Bi.object({name:Bi.string().max(80),description:Bi.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 p2(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=xu([t],r,n.defaultLocale),o=n.locales[i],a=n.locales[n.defaultLocale];return{name:o?.name.trim()?o.name:a?.name.trim()?a.name:e.name,description:o?.description.trim()?o.description:a?.description.trim()?a.description:""}}var kf="#172033",ia="#667085",s0="#E2E6EE",c0="#2C3C96",xt=e=>({top:e,right:e,bottom:e,left:e}),ut=e=>({type:"color",color:e}),Mt=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,o=ia,a={}){return this.zh[t]=n,this.en[t]=r,{id:t,type:"text",text:t,variant:i>=30?"title":"body",style:{text:{size:i,color:o,weight:i>=30?600:400,lineHeight:1.35,...i>=30?{letterSpacing:-1.2}:{}},...a}}}stack(t,n,r={},i=!1){return{id:t,type:"stack",direction:i?"horizontal":"vertical",align:"stretch",justify:"start",children:n,style:{gap:i?40:24,...r}}}widget(t,n,r,i,o=!1,a={}){let s=t+"_title";return this.zh[s]=r,this.en[s]=i,{id:t,type:"customer_data",title:s,data:{source:n,layout:o?"compact":"full",pageSize:n==="credit_transactions"?5:4,showSources:n==="credit_balance"&&!o,allowPurchase:n==="credit_packs"},style:a}}rule(t,n=s0){return{id:t,type:"divider",style:{background:ut(n),height:1}}}header(t,n,r,i,o,a=!1){return this.stack("account_header",[this.stack("intro",[this.text("eyebrow","\u5DE5\u4F5C\u7A7A\u95F4 / \u8D26\u6237","WORKSPACE / ACCOUNT",11,a?"#A9B4CB":ia,{text:{size:11,color:a?"#A9B4CB":ia,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,a?"#FFFFFF":kf),this.text("description",r,i,14,a?"#A9B4CB":ia)],{gap:12,width:660,grow:!0}),...o?[o]:[]],{gap:32},!0)}document(t,n=!1){return mt.parse({kind:"screen",schemaVersion:4,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:c0,background:n?"#101A30":"#F5F6FA",text:kf,radius:"md",font:"system",...this.design.theme},pages:[{id:"account_page",name:this.name,root:{...this.stack("root",[this.stack("content",t,{width:this.design.width??1200,gap:this.design.gap??32})],{padding:this.design.padding??{top:40,right:24,bottom:36,left:24}}),align:"center"}}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":this.zh,en:this.en}},actions:[]})}};var aa="#19202E",u0="#667080",Dc="#2C3C96",Df="#DDE2E9",Nf="#F0F3FA",l0=(e=72,t=aa)=>({text:{size:e,color:t,weight:600,font:"system"}}),oa=(e,t=1)=>({width:e,grow:t}),d0={background:ut("#FFFFFF"),shape:{type:"rect",radius:10}};function p0(e){return new Mt(e,{theme:{background:"#FFFFFF",text:aa,primary:Dc},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function m0(e,t,n,r,i){let o=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,Dc,{text:{size:13,color:Dc,weight:700,letterSpacing:.8}});return e.stack("page_header",[o,e.text("heading",t,n,40,aa,{text:{size:40,color:aa,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,u0)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function Ff(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new Mt("\u8D26\u6237\u4E00\u89C8",{theme:{background:e,text:t,primary:n,radius:"none"},width:1120,gap:36,padding:{top:32,right:24,bottom:48,left:24}}),o=(a,s,c)=>i.text(a,s,c,12,n,{text:{size:12,color:n,font:"mono",weight:500,letterSpacing:1.1}});return i.document([i.stack("journal_masthead",[i.stack("journal_identity",[i.text("wordmark","GROW","GROW",22,t,{text:{size:22,color:t,weight:700,letterSpacing:-1}}),o("edition","\u8D26\u6237 / ACCOUNT","ACCOUNT / JOURNAL")],{gap:16},!0),i.rule("masthead_rule",t),i.stack("journal_intro",[i.text("heading","\u8D26\u6237\u4E00\u89C8","Your account.",64,t,{width:720,grow:2,text:{size:64,color:t,font:"serif",weight:400,lineHeight:1.12,letterSpacing:-2}}),i.stack("intro_note",[o("intro_index","\u4E3A\u4F60\u7684\u4E0B\u4E00\u6B21\u521B\u4F5C","FOR YOUR NEXT CHAPTER"),i.text("description",`\u4F60\u7684\u4F1A\u5458\u3001\u79EF\u5206\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C
2
- \u5728\u4E00\u5904\u4ECE\u5BB9\u638C\u63E1\u3002`,`Membership, credits and purchases.
3
- A little clarity for what's next.`,14,r)],{width:300,grow:1,gap:12,padding:{top:8,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("account_summary",[i.stack("member_column",[o("member_index","01 / \u4F1A\u5458","01 / MEMBERSHIP"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:t,font:"serif",size:40,weight:400}})],{width:660,grow:2,gap:16}),i.stack("balance_column",[o("balance_index","02 / \u79EF\u5206","02 / CREDITS"),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:t,font:"serif",size:64,weight:400}})],{width:340,grow:1,gap:16})],{gap:48,padding:{top:12,right:0,bottom:12,left:0}},!0),i.rule("records_rule","#D9CFC1"),i.stack("account_records",[i.stack("purchase_column",[o("purchase_index","03 / \u8D2D\u4E70\u8BB0\u5F55","03 / PURCHASES"),i.widget("orders","credit_pack_orders","\u6BCF\u4E00\u7B14\u8D2D\u4E70","Your purchases",!1,{text:{color:t}})],{width:660,grow:2,gap:16}),i.stack("offer_column",[o("offer_index","04 / \u4E13\u5C5E\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u53EF\u7528\u4F18\u60E0","Available offers",!0,{text:{color:t}})],{width:340,grow:1,gap:16})],{gap:48},!0),i.rule("catalog_rule","#D9CFC1"),i.stack("account_catalog",[o("catalog_index","05 / \u65B9\u6848","05 / PLANS"),i.widget("plans","customer_plans","\u63A2\u7D22\u9002\u5408\u4F60\u7684\u65B9\u6848","Find your next plan",!0,{text:{color:t}})],{gap:16}),i.text("journal_footer","GROW / \u8BA9\u521B\u4F5C\u7EE7\u7EED","GROW / KEEP CREATING",11,r,{text:{size:11,color:r,font:"mono",letterSpacing:1}})])}function Uf(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new Mt("\u79EF\u5206\u5DE5\u4F5C\u53F0",{theme:{background:"#EDF1F7",text:e,primary:"#244F9E",radius:"sm"},width:1200,gap:24,padding:{top:24,right:24,bottom:40,left:24}}),i=(o,a,s)=>r.text(o,a,s,11,t,{text:{size:11,color:t,font:"mono",weight:500,letterSpacing:1}});return r.document([r.stack("terminal_header",[i("wordmark","GROW / \u79EF\u5206\u5DE5\u4F5C\u53F0","GROW / CREDIT WORKSPACE"),r.stack("terminal_intro",[r.text("heading","\u79EF\u5206\u4E0E\u7528\u91CF","Credits & usage",36,e,{width:780,grow:2,text:{size:36,color:e,weight:600,letterSpacing:-1.2,lineHeight:1.15}}),r.text("description","\u4F59\u989D\u3001\u5230\u671F\u6765\u6E90\u4E0E\u6BCF\u4E00\u7B14\u4F7F\u7528\u3002","Balance, expiry and every transaction.",13,t,{width:340,grow:1})],{gap:32},!0)],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),r.stack("terminal_workspace",[r.stack("ledger_workspace",[r.stack("credit_summary",[i("balance_index","01 / \u8D26\u6237\u4F59\u989D","01 / BALANCE"),r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{text:{size:80,color:e,font:"mono",weight:500}})],{gap:16,padding:xt(28),background:ut("#E0E8F4")}),r.stack("ledger_panel",[i("activity_index","02 / \u8D26\u76EE\u660E\u7EC6","02 / ACTIVITY"),r.widget("activity","credit_transactions","\u79EF\u5206\u6D41\u6C34","Credit history",!1,{text:{color:e}})],{gap:16,padding:xt(28),background:ut("#FFFFFF")})],{width:820,grow:2,gap:2}),r.stack("purchase_rail",[r.stack("plan_context",[i("membership_index","\u8D26\u6237 / \u65B9\u6848","ACCOUNT / PLAN"),r.widget("membership","membership","\u5F53\u524D\u65B9\u6848","Current plan",!0,{text:{color:e}})],{gap:16,padding:xt(24),background:ut("#FFFFFF")}),r.stack("purchase_panel",[i("purchase_index","03 / \u8865\u5145\u79EF\u5206","03 / TOP UP"),r.widget("packs","credit_packs","\u8D2D\u4E70\u79EF\u5206","Buy credits",!0,{text:{color:e}}),r.text("purchase_note","\u8D2D\u4E70\u524D\u67E5\u770B\u79EF\u5206\u6570\u91CF\u4E0E\u6709\u6548\u671F\u3002","Check the credit amount and validity before purchase.",12,t)],{gap:16,padding:xt(24),background:ut("#FFFFFF")}),r.stack("orders_panel",[i("orders_index","04 / \u8D2D\u4E70\u8BB0\u5F55","04 / PURCHASES"),r.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0,{text:{color:e}})],{gap:16,padding:xt(24),background:ut("#FFFFFF")})],{width:348,grow:1,gap:2})],{gap:24},!0),r.rule("terminal_rule",n),i("terminal_footer","GROW / \u6309\u8D44\u6E90\u67E5\u770B\u4F59\u989D \xB7 \u6309\u8BB0\u5F55\u6838\u5BF9\u4F7F\u7528","GROW / RESOURCE BALANCES \xB7 TRANSACTION RECORDS")])}function Mf(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new Mt("\u4F1A\u5458\u4FF1\u4E50\u90E8",{theme:{background:t,text:e,primary:e,radius:"none"},width:1160,gap:32,padding:{top:28,right:24,bottom:48,left:24}}),o=(a,s,c,u=n)=>i.text(a,s,c,12,u,{text:{size:12,color:u,font:"mono",letterSpacing:1,weight:500}});return i.document([i.stack("club_masthead",[i.stack("club_identity",[i.text("wordmark","GROW CLUB","GROW CLUB",22,e,{text:{size:22,color:e,weight:700,letterSpacing:-.6}}),o("club_edition","\u4F1A\u5458 / MEMBERSHIP","MEMBERSHIP / YOUR SPACE")],{gap:20},!0),i.rule("club_rule",e),i.stack("club_intro",[i.text("heading","\u4F1A\u5458\u4E0E\u65B9\u6848","Room to grow.",64,e,{width:752,grow:2,text:{size:64,color:e,font:"serif",weight:400,lineHeight:1.1,letterSpacing:-2}}),i.stack("club_description",[o("club_intro_label","\u4E3A\u6301\u7EED\u7684\u521B\u9020\u529B","FOR WHAT COMES NEXT"),i.text("description",`\u67E5\u770B\u4F60\u7684\u4F1A\u5458\u72B6\u6001\uFF0C
4
- \u627E\u5230\u9002\u5408\u4E0B\u4E00\u6B65\u7684\u65B9\u6848\u3002`,`Your membership, at a glance.
5
- A plan for what comes next.`,14,n)],{width:320,grow:1,gap:12,padding:{top:10,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("membership_summary",[i.stack("member_spread",[o("member_index","01 / \u4F60\u7684\u4F1A\u5458","01 / YOUR MEMBERSHIP","#CCD9CA"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:"#FFFFFF",font:"serif",size:52,weight:400}})],{width:744,grow:2,gap:20,padding:xt(32),background:ut(e)}),i.stack("balance_inset",[o("balance_index","02 / \u521B\u4F5C\u4F59\u989D","02 / CREDIT BALANCE",e),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:e,size:60,weight:500}})],{width:376,grow:1,gap:20,padding:xt(28),background:ut(r)})],{gap:0},!0),i.stack("plan_comparison",[o("plans_index","03 / \u9009\u62E9\u4F60\u7684\u4E0B\u4E00\u6B65","03 / YOUR NEXT STEP"),i.widget("plans","customer_plans","\u627E\u5230\u9002\u5408\u4F60\u7684\u65B9\u6848","A plan to make it yours",!1,{text:{color:e,font:"serif"}})],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),i.rule("benefits_rule","#C8CEC2"),i.stack("benefit_records",[i.stack("member_offers",[o("offers_index","04 / \u4F60\u7684\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u4F1A\u5458\u4F18\u60E0","Member offers",!1,{text:{color:e}})],{width:556,grow:1,gap:16}),i.stack("member_purchases",[o("orders_index","05 / \u8D2D\u4E70\u8BB0\u5F55","05 / PURCHASES"),i.widget("orders","credit_pack_orders","\u8D2D\u4E70\u4E0E\u8BB0\u5F55","Purchases & records",!1,{text:{color:e}})],{width:556,grow:1,gap:16})],{gap:48},!0),i.rule("footer_rule","#C8CEC2"),o("club_footer","GROW CLUB / \u7559\u51FA\u521B\u9020\u7684\u7A7A\u95F4","GROW CLUB / ROOM FOR WHAT'S NEXT")])}function Bf(){let e=p0("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([m0(e,"\u521B\u4F5C\u5DE5\u4F5C\u533A","Your workspace","\u79EF\u5206\u3001\u4F1A\u5458\u548C\u4F7F\u7528\u8BB0\u5F55\uFF0C\u90FD\u5728\u8FD9\u91CC\u3002","Your credits, membership and activity."),e.stack("studio_summary",[e.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{...oa(784,2),...l0(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{...oa(328),background:ut(Nf),padding:xt(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",Df),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,oa(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",Df),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{...oa(328),...d0,padding:xt(24),gap:24,background:ut(Nf)})],{gap:48},!0)])}function Lf(){return Bf()}var ln=(e,t=1)=>({width:e,grow:t}),sa=(e=16)=>({shape:{type:"rect",radius:e}}),Xe=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),yn=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function f0(e,t,n,r,i="system"){return e.text("heading",t,n,28,r,{text:{size:28,font:i,weight:600,color:r,lineHeight:1.2,letterSpacing:-.8}})}function h0(e,t,n,r,i){return e.text(t,n,r,11,i,{text:{size:11,font:"system",weight:500,color:i,letterSpacing:.6}})}function Li(e,t,n,r,i,o="system"){let a=e.stack("masthead",[f0(e,t,n,r,o),h0(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return a.justify="between",a.align="center",a}function qf(e,t,n=!1,r=5){let i=e.widget("activity","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",n,Xe(t));return i.data.pageSize=r,i}function g0(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new Mt("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:yn(32,24,48)});return i.document([Li(i,"\u79EF\u5206\u8D26\u6237","Credits",t,n),i.rule("header_rule","#354039"),i.stack("wallet_workspace",[i.stack("wallet_primary",[i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,Xe(t,96)),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,Xe(t))],{...ln(680,2),gap:32,padding:yn(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,Xe(e))],{...ln(328),background:ut(r),padding:xt(24),...sa(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),qf(i,t,!1,4)])}function b0(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new Mt("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:yn(40,24,48)});return r.document([Li(r,"\u8D26\u6237\u6863\u6848","Account journal",e,t,"serif"),r.rule("header_rule",e),r.stack("statement",[r.stack("balance_column",[r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,Xe(e,96,"serif"))],{...ln(628,2),padding:yn(12,0),gap:24}),r.stack("membership_column",[r.widget("membership","membership","\u4F1A\u5458\u72B6\u6001","Membership",!1,Xe(e)),r.widget("offers","offer_history","\u8D26\u6237\u4F18\u60E0","Your offers",!0,Xe(e))],{...ln(356),gap:20,padding:yn(12,0)})],{gap:96},!0),r.rule("orders_rule",n),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Purchases",!1,Xe(e))])}function _0(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new Mt("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:yn(32,24,48)});return i.document([Li(i,"\u4F1A\u5458\u4E2D\u5FC3","Membership",e,t),i.stack("current_membership",[i.stack("member_credential",[i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,Xe("#F4F7F0"))],{...ln(640,2),gap:24,background:ut(n),padding:xt(32),...sa(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,Xe(e,64))],{...ln(400),background:ut("#E9EFE5"),padding:xt(28),...sa(20)})],{gap:24},!0),i.widget("plans","customer_plans","\u65B9\u6848\u4E0E\u4EF7\u683C","Plans & pricing",!1,Xe(e)),i.rule("offer_rule","#D5DFD3"),i.widget("offers","offer_history","\u6211\u7684\u4F18\u60E0","Your offers",!0,Xe(e))])}function y0(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new Mt("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:yn(32,24,48)});return r.document([Li(r,"\u7528\u91CF\u4E0E\u8BB0\u5F55","Usage & history",e,t),r.rule("header_rule",e),r.stack("account_context",[r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{...ln(688,2),...Xe(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...ln(372),...Xe(e)})],{gap:72,padding:yn(4,0,8)},!0),r.rule("activity_rule",n),qf(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,Xe(e))])}function S0(){let e="#3F3029",t="#8B766A",n="#A34525",r=new Mt("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:yn(32,24,48)});return r.document([Li(r,"\u8865\u5145\u79EF\u5206","Add credits",e,t),r.rule("header_rule","#E8DDD3"),r.stack("purchase_workspace",[r.stack("account_context",[r.widget("balance","credit_balance","\u73B0\u6709\u79EF\u5206","Current credits",!0,Xe(e,56)),r.rule("context_rule","#DBC5B5"),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,Xe(e))],{...ln(304),gap:28,padding:xt(24),background:ut("#F1E5D9"),...sa(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,Xe(e))],{...ln(800,2),gap:24})],{gap:32},!0),r.rule("orders_rule","#E8DDD3"),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Recent purchases",!1,Xe(e))])}function Vf(){return[{key:"page-credits-midnight",label:"\u6697\u7EFF\u79EF\u5206\u53F0 \xB7 \u591C\u95F4\u6A21\u5F0F",description:"\u4EE5\u5B9E\u65F6\u4F59\u989D\u4E3A\u4E3B\u89C6\u89C9\uFF0C\u6D45\u7EFF\u8D2D\u4E70\u533A\u4E0E\u5B8C\u6574\u6D41\u6C34\u5F62\u6210\u660E\u786E\u64CD\u4F5C\u987A\u5E8F\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u6697\u8272","\u79EF\u5206","\u8D2D\u4E70","\u684C\u9762"],create:g0},{key:"page-account-journal",label:"\u8D26\u6237\u6863\u6848 \xB7 \u7EB8\u611F\u6392\u7248",description:"\u7EB8\u611F\u8D26\u76EE\u3001\u886C\u7EBF\u4F59\u989D\u3001\u8FB9\u680F\u4F1A\u5458\u4E0E\u4F18\u60E0\uFF0C\u4FDD\u7559\u6E05\u6670\u7684\u8D2D\u4E70\u8BB0\u5F55\u3002",category:"\u8D26\u6237\u7A7A\u95F4",tags:["\u7EB8\u611F","\u886C\u7EBF","\u8D26\u6237","\u8BB0\u5F55"],create:b0},{key:"page-membership-sage",label:"\u4F1A\u5458\u7A7A\u95F4 \xB7 \u677E\u7EFF",description:"\u677E\u7EFF\u4F1A\u5458\u51ED\u8BC1\u4E0E\u4F59\u989D\u5E76\u6392\uFF0C\u4E0B\u65B9\u5C55\u793A\u5F53\u524D\u5BA2\u6237\u53EF\u89C1\u7684\u65B9\u6848\u4E0E\u4EF7\u683C\u3002",category:"\u4F1A\u5458\u4E0E\u65B9\u6848",tags:["\u677E\u7EFF","\u4F1A\u5458","\u65B9\u6848","\u684C\u9762"],create:_0},{key:"page-wallet-violet",label:"\u521B\u4F5C\u5DE5\u4F5C\u533A \xB7 \u79EF\u5206\u4E0E\u8BB0\u5F55",description:"\u8D26\u6237\u72B6\u6001\u3001\u5B8C\u6574\u4F7F\u7528\u8BB0\u5F55\u548C\u4FA7\u680F\u79EF\u5206\u8D2D\u4E70\uFF0C\u96C6\u4E2D\u5728\u6E05\u6670\u7684\u5DE5\u4F5C\u533A\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u5DE5\u4F5C\u533A","\u521B\u4F5C","\u79EF\u5206","\u8BB0\u5F55"],create:Lf},{key:"page-usage-ledger",label:"\u7528\u91CF\u8D26\u518C \xB7 \u9ED1\u767D",description:"\u7D27\u51D1\u8D26\u6237\u72B6\u6001\u3001\u5BBD\u5E45\u6D41\u6C34\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C\u9002\u5408\u7528\u91CF\u5BC6\u96C6\u7684\u4EA7\u54C1\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u9ED1\u767D","\u7B49\u5BBD","\u6D41\u6C34","\u684C\u9762"],create:y0},{key:"page-topup-orange",label:"\u79EF\u5206\u8865\u7ED9 \xB7 \u6696\u6A59",description:"\u5546\u54C1\u4EF7\u683C\u4E0E\u8D2D\u4E70\u5165\u53E3\u5E76\u6392\u5448\u73B0\uFF0C\u65C1\u8FB9\u4FDD\u7559\u5B9E\u65F6\u4F59\u989D\u548C\u4F1A\u5458\u72B6\u6001\u3002",category:"\u79EF\u5206\u4E0E\u7528\u91CF",tags:["\u6696\u6A59","\u8D2D\u4E70","\u79EF\u5206\u5305","\u8BA2\u5355"],create:S0}].map(({create:e,...t})=>({...t,document:e()}))}function v0(){return Uf()}function x0(){return Ff()}function I0(){return Mf()}function w2(){return[...Vf(),{key:"page-credit-center-wallet",label:"\u79EF\u5206\u5DE5\u4F5C\u53F0 \xB7 Terminal",description:"\u84DD\u7070\u8D26\u76EE\u5DE5\u4F5C\u53F0\uFF1A\u7CBE\u786E\u4F59\u989D\u4E0E\u5B8C\u6574\u6D41\u6C34\u4E3A\u4E3B\uFF0C\u65B9\u6848\u3001\u79EF\u5206\u8D2D\u4E70\u4E0E\u8BA2\u5355\u7F6E\u4E8E\u72EC\u7ACB\u64CD\u4F5C\u680F\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u79EF\u5206","\u6D41\u6C34","\u771F\u5B9E\u6570\u636E","\u684C\u9762"],document:v0()},{key:"page-account-overview",label:"\u8D26\u6237\u4E00\u89C8 \xB7 Journal",description:"\u6696\u7EB8\u8272\u4E0E\u886C\u7EBF\u5B57\u4F53\u7684\u6742\u5FD7\u5F0F\u8D26\u6237\u9875\uFF1A\u4F1A\u5458\u4E0E\u79EF\u5206\u5C55\u5F00\u5448\u73B0\uFF0C\u8D2D\u4E70\u3001\u4F18\u60E0\u548C\u65B9\u6848\u5206\u533A\u9605\u8BFB\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u8D26\u6237","\u4F1A\u5458","\u4F18\u60E0","\u771F\u5B9E\u6570\u636E"],document:x0()},{key:"page-membership-catalog",label:"\u4F1A\u5458\u4FF1\u4E50\u90E8 \xB7 Club",description:"\u68EE\u6797\u7EFF\u4E0E\u8C61\u7259\u767D\u7684\u54C1\u724C\u4F1A\u5458\u9875\uFF1A\u5F3A\u5B57\u4F53\u3001\u5BF9\u6BD4\u8272\u4F1A\u5458\u533A\u3001\u5F00\u653E\u5F0F\u65B9\u6848\u6BD4\u8F83\u4E0E\u5B8C\u6574\u8D26\u6237\u8BB0\u5F55\u3002",category:"\u8D26\u6237\u4E0E\u79EF\u5206",tags:["\u4F1A\u5458","\u5957\u9910","\u8D44\u683C","\u771F\u5B9E\u6570\u636E"],document:I0()}]}import{z as Et}from"zod";var $f=Et.object({id:Et.string().min(1).max(136),name:Et.string().min(1).max(128),type:Et.enum(["entry","condition","feature"])}).strict(),A0=Et.object({id:Et.uuid(),name:Et.string().min(1).max(80),status:Et.enum(["draft","published","archived"]),draftNodes:Et.array($f).max(600),publishedNodes:Et.array($f).max(600),runningVersions:Et.number().int().nonnegative()}).strict().refine(e=>e.draftNodes.length>0||e.publishedNodes.length>0||e.runningVersions>0,"A Funnel usage must have a current reference or an unfinished run"),O2=Et.object({rows:Et.array(A0).max(50),nextCursor:Et.uuid().nullable()}).strict();import{z as ve}from"zod";var yt=ve.number().int().nonnegative(),Gf=ve.strictObject({at:ve.iso.datetime({offset:!0}),id:ve.uuid()}),k2=ve.strictObject({versionId:ve.uuid().nullable(),from:ve.iso.datetime({offset:!0}).nullable(),to:ve.iso.datetime({offset:!0}).nullable(),after:Gf.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),D2=ve.strictObject({funnelId:ve.uuid(),snapshotAt:ve.iso.datetime({offset:!0}),versions:ve.array(ve.strictObject({id:ve.uuid(),version:ve.number().int().positive(),createdAt:ve.iso.datetime({offset:!0})})).max(100),versionsLimited:ve.boolean(),overall:ve.strictObject({started:yt,completed:yt,closed:yt,failed:yt,waiting:yt,paid:yt}),decisions:ve.strictObject({queries:yt,completed:yt,reportedUsed:yt,pending:yt,failed:yt}),revenue:ve.array(ve.strictObject({currency:oe,grossMinor:ve.string().regex(/^\d+$/),refundMinor:ve.string().regex(/^\d+$/),netMinor:ve.string().regex(/^-?\d+$/)})).max(100),nodes:ve.array(ve.strictObject({versionId:ve.uuid(),nodeId:ve.string(),visits:yt,completed:yt,shown:yt,waiting:yt})).max(1e4),recentRuns:ve.array(ve.strictObject({id:ve.uuid(),versionId:ve.uuid(),customerId:ve.uuid(),status:Pc,nodeId:ve.string(),visit:yt,createdAt:ve.iso.datetime({offset:!0}),updatedAt:ve.iso.datetime({offset:!0})})).max(100),nextCursor:Gf.nullable()});import{z as Dn}from"zod";var B2=Dn.object({requestId:Dn.uuid(),coupon:cd,audienceId:Dn.uuid().nullable(),productVersionId:Dn.uuid().optional(),presentation:_n,locale:Dn.enum(["en","zh-CN"])}).strict(),L2=Dn.object({couponId:Dn.uuid(),funnelId:Dn.uuid()}).strict();import{z as Ae}from"zod";var lt=Ae.number().int().nonnegative(),ca=Ae.string().regex(/^-?\d+$/),w0=Ae.object({currency:oe,grossMinor:ca,refundMinor:ca,netMinor:ca,purchases:lt,refunds:lt}).strict(),G2=Ae.object({snapshotAt:Ae.iso.datetime({offset:!0}),customers:Ae.object({total:lt,created:lt,paid:lt}).strict(),memberships:Ae.object({active:lt,trial:lt,pastDue:lt,ended:lt}).strict(),runs:Ae.object({started:lt,completed:lt,closed:lt,paid:lt}).strict(),revenue:Ae.array(w0).max(100),unknownMoney:lt,funnels:Ae.array(Ae.object({id:Ae.uuid(),name:Ae.string(),started:lt,completed:lt,paid:lt}).strict()).max(50),daily:Ae.array(Ae.object({date:Ae.iso.date(),currency:oe,netMinor:ca}).strict()).max(9e3)}).strict(),K2=Ae.object({customerId:Ae.uuid(),rows:Ae.array(Ae.object({id:Ae.string().regex(/^\d+$/),funnelId:Ae.uuid(),funnelName:Ae.string(),versionId:Ae.uuid(),runId:Ae.uuid(),nodeId:Ae.string(),experimentId:Ae.uuid(),visit:Ae.number().int().nonnegative(),variationKey:Ae.string(),inExperiment:Ae.boolean(),hashUsed:Ae.boolean(),acceptedAt:Ae.iso.datetime({offset:!0}),runStatus:Ae.string()}).strict()).max(50),nextCursor:Ae.string().regex(/^\d+$/).nullable()}).strict();import{z as Wt}from"zod";import{z as dt}from"zod";var Kf=dt.discriminatedUnion("provider",[dt.strictObject({provider:dt.literal("apple"),orderId:dt.uuid(),receiptId:dt.uuid(),signedTransaction:dt.string().min(1).max(131072)}),dt.strictObject({provider:dt.literal("google"),orderId:dt.uuid(),receiptId:dt.uuid(),purchaseToken:dt.string().min(1).max(16384)})]),Hf=dt.strictObject({orderId:dt.uuid(),receiptId:dt.uuid(),transactionIds:dt.array(dt.string().min(1).max(255)).min(1).max(50),membership:dt.boolean()});var X2=Wt.strictObject({operation:Wt.literal("native_receipt"),requestId:Wt.uuid(),customerToken:Wt.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:Wt.uuid(),receiptId:Wt.uuid(),nativeEvidence:Kf.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),z2=Wt.strictObject({scope:je,requestId:Wt.uuid(),orderId:Wt.uuid(),receiptId:Wt.uuid(),orderStatus:Wt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:Wt.boolean(),nativeCompletion:Hf.optional()});import{z as C0}from"zod";var P0=nf.extend({document:C0.union([mt.refine(e=>e.pages.length===1,"Use a single owned screen template"),Ut.refine(e=>e.screens.every(t=>t.type==="owned"),"Flow templates own their screens")])}).superRefine((e,t)=>{if((e.document.kind==="funnel"?e.surface!=="onboarding":e.surface!==e.document.surface)&&t.addIssue({code:"custom",message:"Template category does not match its document"}),e.document.kind==="funnel"){let n=e.document,r=n.graph.nodes.filter(i=>i.type==="screen");(new Set(n.screens.map(i=>i.id)).size!==n.screens.length||new Set(n.graph.nodes.map(i=>i.id)).size!==n.graph.nodes.length||r.length!==n.screens.length||n.screens.some(i=>r.filter(o=>o.screenId===i.id).length!==1))&&t.addIssue({code:"custom",message:"Every template screen requires one unique flow node"})}});function uU(e,t=0){if(e.document.kind==="screen")return e.document;let n=e.document.screens[t];if(n?.type!=="owned")throw new Error("Owned template screen required");let r=e.document.graph.nodes.find(i=>i.type==="screen"&&i.screenId===n.id);if(r?.type!=="screen")throw new Error("Template screen node required");return{...n.document,presentation:r.presentation.type==="inline"?{type:"fullscreen"}:r.presentation}}var dn="00000000-0000-0000-0000-000000000000";function O0(e){return e.type==="event"&&typeof e.properties.templateKey=="string"&&e.properties.templateKey.startsWith("popup-coupon-")}function E0(e,t){let n=structuredClone(P0.parse(e).document);if(n.kind==="funnel"){let m=function(g){if(Array.isArray(g)){g.forEach(m);return}if(!g||typeof g!="object")return;let p=g;p.type==="experiment-ref"&&(p.experimentId=dn),p.$savedGroup&&typeof p.$savedGroup=="object"&&(p.$savedGroup.id=dn),typeof p.$inGroup=="string"&&(p.$inGroup=dn),typeof p.$notInGroup=="string"&&(p.$notInGroup=dn),Object.values(p).forEach(m)};var d=m;for(let[g,p]of Object.entries(n.references))"id"in p&&delete n.references[g];for(let g of n.graph.nodes)g.type==="condition"&&g.cases.forEach(p=>m(p.condition));for(let g of n.screens)g.type==="owned"&&Wf(g.document);return Ut.parse({...n,screens:n.screens.map(g=>g.type==="owned"?{...g,document:{...g.document,strings:{...g.document.strings,defaultLocale:Fa(g.document,[t])}}}:g),graph:{...n.graph,nodes:n.graph.nodes.map(g=>{if(g.type==="split")return{...g,experimentId:"00000000-0000-0000-0000-000000000000"};if(g.type==="offering")return{...g,configuration:g.configuration.source==="fixed"?{source:"fixed",versionId:dn}:g.configuration};if(g.type==="coupons")return{...g,couponIds:[]};if(g.type==="coupon")return{...g,couponId:dn};if(g.type==="screen"&&g.offering?.source==="fixed")return{...g,offering:{source:"fixed",versionId:dn}};if(g.type==="action"&&g.action.type==="claim_offer"&&g.action.coupon.source==="literal")return{...g,action:{...g.action,coupon:{source:"literal",value:{type:"reward",id:dn}}}};if(g.type==="output"&&g.value.type==="bundle"){let p={...g.value};for(let[h,y]of[["paywall","paywall_version"],["offering","offering_version"]])p[h]?.source==="literal"&&(p[h]={source:"literal",value:{type:y,id:dn}});return p.coupons.source==="literal"&&(p.coupons={source:"literal",value:[]}),{...g,value:p}}return g})}})}let r={...n,strings:{...n.strings,defaultLocale:Fa(n,[t])}},i=[{id:"entry",type:"entry",name:t==="en"?"Entry":"\u5165\u53E3",next:"screen"},{id:"done",name:t==="en"?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed",output:{type:"literal",value:null}},{id:"closed",name:t==="en"?"Closed":"\u5173\u95ED",type:"end",outcome:"closed"}],o={},a=t==="en",s,c=()=>s||(s="claim",i.push({id:s,name:a?"Claim Coupon":"\u9886\u53D6 Coupon",type:"action",execution:{...cf},action:{type:"claim_offer",coupon:{source:"literal",value:{type:"reward",id:dn}}},success:"done",cancel:"closed",unavailable:"unavailable",failure:"failed"},{id:"unavailable",name:a?"Offer unavailable":"\u4F18\u60E0\u4E0D\u53EF\u7528",type:"end",outcome:"ineligible",output:{type:"literal",value:null}},{id:"failed",name:a?"Claim failed":"\u9886\u53D6\u5931\u8D25",type:"end",outcome:"failed"}),s);r.actions=r.actions.map((m,g)=>{let p=`action_${g}`;return o[m.id]=m.close?"closed":"done",m.type==="open_url"?(o[m.id]=p,i.push({id:p,name:m.id,type:"output",value:{type:"literal",value:{intent:"open_url",url:m.url}}})):(m.type==="claim_offer"||O0(m))&&(o[m.id]=c()),{id:m.id,type:"event",event:m.id,properties:{},close:!1}}),Wf(r),i.push({id:"screen",name:e.label,type:"screen",screenId:"screen",presentation:e.surface==="page"?{type:"inline"}:n.presentation,outputs:o});let u=new Set(i.flatMap(jr)),l={};return Ut.parse({references:{},variables:l,outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",schemaVersion:4,inputs:(()=>{let m=[];return Ct(r,g=>{if(g.type==="stack"&&g.interaction&&["input","select","multiselect","toggle","tabs"].includes(g.interaction.type)){let p=`answer_${crypto.randomUUID().replaceAll("-","")}`;l[p]={type:g.interaction.type==="toggle"?"boolean":g.interaction.type==="multiselect"?"strings":"string",nullable:!1,source:{type:"input"}},m.push({variable:p,screenId:"screen",componentId:g.id,required:!1})}}),m})(),screens:[{id:"screen",type:"owned",document:r}],graph:{version:5,entry:"entry",nodes:i.filter(m=>m.type!=="end"||u.has(m.id))}})}function lU(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=E0(t,n),i=`tpl_${crypto.randomUUID().replaceAll("-","").slice(0,16)}_`,o=new Map,a=d=>d==="unconnected"?d:(o.has(d)||o.set(d,`${i}${crypto.randomUUID().replaceAll("-","").slice(0,24)}`),o.get(d)),s=r.graph.nodes.slice().sort((d,m)=>+(m.type==="screen")-+(d.type==="screen")).filter(d=>d.type!=="entry").map(d=>d.type==="screen"?{...d,id:a(d.id),screenId:a(d.screenId),outputs:Object.fromEntries(Object.entries(d.outputs).map(([m,g])=>[m,a(g)]))}:d.type==="action"?{...d,id:a(d.id),success:a(d.success),cancel:a(d.cancel),unavailable:a(d.unavailable),failure:a(d.failure)}:d.type==="external_page"?{...d,id:a(d.id),opened:a(d.opened),failed:a(d.failed)}:{...d,id:a(d.id)}),c=Ut.parse({...e,variables:{...e.variables,...r.variables},screens:[...e.screens,...r.screens.map(d=>({...d,id:a(d.id)}))],inputs:[...e.inputs,...r.inputs.map(d=>({...d,screenId:a(d.screenId)}))],graph:{...e.graph,nodes:[...e.graph.nodes,...s]}}),u=0,l=0;for(let d of c.screens)d.type==="owned"&&(Ct(d.document,()=>{u++}),l+=d.document.actions.length);if(u>Qe.components||l>Qe.actions||gt(c)>Qe.documentBytes)throw new Error("Template exceeds the flow capacity");return c}function Wf(e){Ct(e,t=>{t.type==="stack"&&t.bind?(delete t.bind.plan,delete t.bind.coupon,delete t.bind.promotionCode,Object.keys(t.bind).length||delete t.bind):t.type==="plan_picker"&&(delete t.planIds,delete t.defaultPlan)})}function T0(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function pU(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function Qf(e){return T0(e)?e.intervalCount??1:1}function mU(e,t){return e.interval===t.interval&&Qf(e)===Qf(t)}function fU(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},o={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},a=e==="week"?`/${o[r]??o.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?a:`/${n} ${a.slice(1)}${r==="en"?"s":""}`}import{z as Ve}from"zod";var Zf=Ve.enum(["membership","trial","topup","manual","rollover","seat"]),Yf=Ve.enum(["scheduled","active","expired","revoked","unavailable"]),yU=Ve.strictObject({customerId:Ve.uuid().nullable(),entityId:Ve.uuid().nullable(),internal_feature_id:Ve.uuid().nullable(),reason:Zf.nullable(),status:Yf.nullable(),after:Ve.uuid().nullable(),limit:Ve.number().int().min(1).max(50)}),SU=Ve.strictObject({snapshotAt:Ve.iso.datetime({offset:!0}),rows:Ve.array(Ve.strictObject({id:Ve.uuid(),customerId:Ve.uuid(),fundingCustomerId:Ve.uuid(),entityId:Ve.uuid().nullable(),internal_feature_id:Ve.uuid(),key:Wi,name:Ve.string().min(1).max(120),kind:Ve.enum(["access","metered","credit"]),reason:Zf,status:Yf,unlimited:Ve.boolean(),granted:jt,available:jt,held:jt,spent:jt,revoked:jt,transferred:jt,startsAt:Ve.iso.datetime({offset:!0}).nullable(),expiresAt:Ve.iso.datetime({offset:!0}).nullable(),grantId:Ve.uuid().nullable(),membershipId:Ve.uuid().nullable(),seatPoolId:Ve.uuid().nullable()})).max(50),nextCursor:Ve.uuid().nullable()});import{z as Me}from"zod";var Jf=Me.string().regex(/^[a-f0-9]{64}$/),R0=Vu.omit({variations:!0,active:!0}).extend({changeId:Jf,variations:Me.array(Me.strictObject({urlRedirect:Me.string().max(2048)})).min(2).max(20)}),CU=Me.strictObject({environmentId:Me.uuid(),trackExposures:Me.boolean(),generation:Jf,experiments:Me.array(R0).max(100),savedGroups:Gu}),j0=Me.strictObject({eventUuid:Me.uuid(),timestamp:Me.iso.datetime({offset:!0}).optional(),deviceId:Me.string().min(1).max(128),sessionId:Me.string().min(1).max(128).optional(),url:Me.url().max(2048),pageTitle:Me.string().max(512).optional(),experimentKey:Me.string().min(1).max(255),variationKey:Me.string().min(1).max(64)}),PU=Me.strictObject({events:Me.array(j0).min(1).max(20)}),OU=Me.strictObject({inserted:Me.number().int().nonnegative(),duplicates:Me.number().int().nonnegative(),skipped:Me.number().int().nonnegative(),rejected:Me.array(Me.strictObject({index:Me.number().int().nonnegative(),reason:Me.string()}))});import{z as q}from"zod";var zf=q.strictObject({property:q.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/),datatype:q.enum(["boolean","string","number","enum","string[]","number[]","object","array","json"]),enumValues:q.array(q.string()).min(1).nullable(),format:q.enum(["","version","date","isoCountryCode"]),hashAttribute:q.boolean(),stored:q.boolean(),description:q.string().max(2e3),status:q.enum(["active","archived"])}).superRefine((e,t)=>{["parameters","answers","results","__proto__","constructor","prototype"].includes(e.property)&&t.addIssue({code:"custom",message:"Reserved attribute property"}),(e.datatype==="enum"!=(e.enumValues!==null)||e.hashAttribute&&!["string","number","enum"].includes(e.datatype))&&t.addIssue({code:"custom",message:"Hash attributes must be scalar strings or numbers; enums require values"})}),eh=q.strictObject({name:q.string().min(1).max(128),label:q.string().min(1).max(80),description:q.string().max(2e3),status:q.enum(["active","inactive"]),hashAttribute:q.string().min(1).max(128),seed:q.string().min(1).max(128)}),Nc={id:q.uuid(),revision:q.number().int().positive()},kU=q.strictObject({groups:q.array(q.strictObject({id:q.uuid(),name:q.string(),type:q.enum(["condition","list"])})),experiments:q.array(q.strictObject({...Nc,configuration:ei,archivedAt:q.iso.datetime({offset:!0}).nullable()})),namespaces:q.array(q.strictObject({...Nc,configuration:eh})),attributes:q.array(q.strictObject({...Nc,configuration:zf})),truncated:q.boolean()}),Fc={id:q.uuid().nullable(),revision:q.number().int().min(0)},DU=q.discriminatedUnion("resource",[q.strictObject({...Fc,resource:q.literal("experiment"),configuration:ei.safeExtend({archivedAt:q.iso.datetime({offset:!0}).nullable()})}),q.strictObject({...Fc,resource:q.literal("namespace"),configuration:eh}),q.strictObject({...Fc,resource:q.literal("attribute"),configuration:zf})]),NU=q.strictObject({operation:q.literal("evaluate"),attributes:wt,condition:An.optional(),features:vu,featureKey:q.string().min(1).max(128),customerId:q.uuid().nullable()}),FU=q.strictObject({experimentId:q.uuid(),participants:q.number().int().nonnegative(),cohorts:q.array(q.strictObject({variationKey:q.string().nullable(),participants:q.number().int().nonnegative()})),phases:q.array(q.strictObject({phaseIndex:q.number().int().nonnegative(),participants:q.number().int().nonnegative()})),stickyIdentities:q.number().int().nonnegative(),snapshotAt:q.iso.datetime()}),Xf=q.strictObject({resource:q.enum(["group","experiment","coupon"]),id:q.uuid()}),UU=q.strictObject({rows:q.array(Xf.extend({name:q.string(),status:q.string()})).max(50),total:q.number().int().nonnegative(),nextCursor:Xf.nullable()});var ua=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function k0(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!ua(n.condition,r.condition)||!ua(n.savedGroups,r.savedGroups))&&i.push("targeting"),r.coverage<n.coverage&&i.push("coverage"),r.namespace&&(!n.namespace||n.namespace.id!==r.namespace.id)&&i.push("namespace"),r.namespace&&n.namespace?.id===r.namespace.id&&n.namespace.ranges.some(([c,u])=>{let l=c;for(let[d,m]of[...r.namespace.ranges].sort((g,p)=>g[0]-p[0]))d<=l&&m>l&&(l=m);return l<u})&&i.push("namespaceRange"),(!ua(n.variationWeights,r.variationWeights)||!ua(e.variations.map(c=>c.key),t.variations.map(c=>c.key)))&&i.push("weights"),(e.disableStickyBucketing!==t.disableStickyBucketing||n.seed!==r.seed)&&i.push("identity");let o=i.some(c=>["namespace","namespaceRange","weights","identity"].includes(c)),a=!t.disableStickyBucketing,s=o||i.length>0&&!a?"new-phase":a?"same-phase-sticky":"same-phase-everyone";return{reasons:i,disableSamePhase:o,recommended:s,risk:i.length?o?"danger":"warning":"safe"}}function LU(e,t,n,r,i){let o=structuredClone(t),a=o.phases.at(-1),s=!o.disableStickyBucketing;if(n==="same-phase-sticky"&&!s||n==="new-phase-block-sticky"&&!s)throw Error("Sticky bucketing is required");if(k0(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");if(o.bucketVersion=e.bucketVersion+(s&&n!=="same-phase-sticky"?1:0),o.minBucketVersion=n==="new-phase-block-sticky"?o.bucketVersion:e.minBucketVersion,n.startsWith("new-phase")){o.phases=structuredClone(e.phases);let c=o.phases.at(-1);if(!c)throw new Error("Experiment requires a phase");c.dateEnded=r,o.phases.push({...a,name:a.name,reason:a.reason,dateStarted:r,dateEnded:null,seed:i})}return ei.parse(o)}import{z as D0}from"zod";var $U=D0.enum(["owner","admin","developer","sales","member"]),N0=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],th=N0.flatMap(e=>e==="analytics"?["analytics:read"]:[`${e}:read`,`${e}:write`]),nh={owner:th,admin:th,developer:["organisation:read","customers:write","features:write","plans:write","rewards:write","balances:write","billing:write","migrations:write","analytics:read","apiKeys:write","platform:write"],sales:["customers:write","features:read","plans:read","rewards:write","balances:write","billing:write","analytics:read"],member:["organisation:read","customers:read","features:read","plans:read","rewards:read","balances:read","billing:read","analytics:read","apiKeys:read","platform:read"]};function GU(e,t){if(!e||!Object.hasOwn(nh,e))return!1;let n=nh[e];return n.includes(t)||t.endsWith(":read")&&n.includes(t.replace(/:read$/,":write"))}var HU=["boolean","metered","credit_system","ai_credit_system"];function WU(e,t,n,r=!1){let i=[],o=(a,s)=>i.push({field:a,code:s});return e.type!==t.type&&(e.type==="credit_system"!=(t.type==="credit_system")&&o("type","type_switch_credit_system"),n.customerHistory&&o("type","attached_to_customer"),n.entityFeature&&o("type","used_as_entity_feature"),n.usagePrice&&o("type","has_usage_price"),n.creditSystems&&o("type","used_in_credit_system"),n.productEntitlements&&(e.type==="credit_system"||t.type==="credit_system")&&o("type","used_in_product_credit_system")),e.id!==t.id&&(r&&o("id","id_already_exists"),n.customerHistory&&o("id","attached_to_customer")),e.type!=="boolean"&&t.type!=="boolean"&&e.config?.usage_type!==t.config?.usage_type&&t.config?.usage_type&&(n.creditSystems&&o("usage_type","used_in_credit_system"),n.entityFeature&&o("usage_type","used_as_entity_feature"),n.customerHistory&&o("usage_type","attached_to_customer")),i}/*!
6
- * decimal.js v10.6.0
7
- * An arbitrary-precision Decimal type for JavaScript.
8
- * https://github.com/MikeMcl/decimal.js
9
- * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
10
- * MIT Licence
11
- */var Lr=9e15,Mn=1e9,Uc="0123456789abcdef",pa="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",ma="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Mc={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Lr,maxE:Lr,crypto:!1},ah,Sn,se=!0,ha="[DecimalError] ",Un=ha+"Invalid argument: ",sh=ha+"Precision limit exceeded",ch=ha+"crypto unavailable",uh="[object Decimal]",St=Math.floor,ze=Math.pow,F0=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,U0=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,M0=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,lh=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,en=1e7,te=7,B0=9007199254740991,L0=pa.length-1,Bc=ma.length-1,O={toStringTag:uh};O.absoluteValue=O.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),J(e)};O.ceil=function(){return J(new this.constructor(this),this.e+1,2)};O.clampedTo=O.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(Un+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};O.comparedTo=O.cmp=function(e){var t,n,r,i,o=this,a=o.d,s=(e=new o.constructor(e)).d,c=o.s,u=e.s;if(!a||!s)return!c||!u?NaN:c!==u?c:a===s?0:!a^c<0?1:-1;if(!a[0]||!s[0])return a[0]?c:s[0]?-u:0;if(c!==u)return c;if(o.e!==e.e)return o.e>e.e^c<0?1:-1;for(r=a.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(a[t]!==s[t])return a[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1};O.cosine=O.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())+te,r.rounding=1,n=q0(r,hh(r,n)),r.precision=e,r.rounding=t,J(Sn==2||Sn==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};O.cubeRoot=O.cbrt=function(){var e,t,n,r,i,o,a,s,c,u,l=this,d=l.constructor;if(!l.isFinite()||l.isZero())return new d(l);for(se=!1,o=l.s*ze(l.s*l,1/3),!o||Math.abs(o)==1/0?(n=pt(l.d),e=l.e,(o=(e-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=ze(n,1/3),e=St((e+1)/3)-(e%3==(e<0?-1:2)),o==1/0?n="5e"+e:(n=o.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new d(n),r.s=l.s):r=new d(o.toString()),a=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),u=c.plus(l),r=Be(u.plus(l).times(s),u.plus(c),a+2,1),pt(s.d).slice(0,a)===(n=pt(r.d)).slice(0,a))if(n=n.slice(a-3,a+1),n=="9999"||!i&&n=="4999"){if(!i&&(J(s,e+1,0),s.times(s).times(s).eq(l))){r=s;break}a+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(J(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return se=!0,J(r,e,d.rounding,t)};O.decimalPlaces=O.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-St(this.e/te))*te,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};O.dividedBy=O.div=function(e){return Be(this,new this.constructor(e))};O.dividedToIntegerBy=O.divToInt=function(e){var t=this,n=t.constructor;return J(Be(t,new n(e),0,1,1),n.precision,n.rounding)};O.equals=O.eq=function(e){return this.cmp(e)===0};O.floor=function(){return J(new this.constructor(this),this.e+1,3)};O.greaterThan=O.gt=function(e){return this.cmp(e)>0};O.greaterThanOrEqualTo=O.gte=function(e){var t=this.cmp(e);return t==1||t===0};O.hyperbolicCosine=O.cosh=function(){var e,t,n,r,i,o=this,a=o.constructor,s=new a(1);if(!o.isFinite())return new a(o.s?1/0:NaN);if(o.isZero())return s;n=a.precision,r=a.rounding,a.precision=n+Math.max(o.e,o.sd())+4,a.rounding=1,i=o.d.length,i<32?(e=Math.ceil(i/3),t=(1/ba(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),o=qr(a,1,o.times(t),new a(1),!0);for(var c,u=e,l=new a(8);u--;)c=o.times(o),o=s.minus(c.times(l.minus(c.times(l))));return J(o,a.precision=n,a.rounding=r,!0)};O.hyperbolicSine=O.sinh=function(){var e,t,n,r,i=this,o=i.constructor;if(!i.isFinite()||i.isZero())return new o(i);if(t=o.precision,n=o.rounding,o.precision=t+Math.max(i.e,i.sd())+4,o.rounding=1,r=i.d.length,r<3)i=qr(o,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/ba(5,e)),i=qr(o,2,i,i,!0);for(var a,s=new o(5),c=new o(16),u=new o(20);e--;)a=i.times(i),i=i.times(s.plus(a.times(c.times(a).plus(u))))}return o.precision=t,o.rounding=n,J(i,t,n,!0)};O.hyperbolicTangent=O.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,Be(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};O.inverseCosine=O.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()?pn(t,r,i):new t(0):new t(NaN):e.isZero()?pn(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))};O.inverseHyperbolicCosine=O.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,se=!1,n=n.times(n).minus(1).sqrt().plus(n),se=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};O.inverseHyperbolicSine=O.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,se=!1,n=n.times(n).plus(1).sqrt().plus(n),se=!0,r.precision=e,r.rounding=t,n.ln())};O.inverseHyperbolicTangent=O.atanh=function(){var e,t,n,r,i=this,o=i.constructor;return i.isFinite()?i.e>=0?new o(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=o.precision,t=o.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?J(new o(i),e,t,!0):(o.precision=n=r-i.e,i=Be(i.plus(1),new o(1).minus(i),n+e,1),o.precision=e+4,o.rounding=1,i=i.ln(),o.precision=e,o.rounding=t,i.times(.5))):new o(NaN)};O.inverseSine=O.asin=function(){var e,t,n,r,i=this,o=i.constructor;return i.isZero()?new o(i):(t=i.abs().cmp(1),n=o.precision,r=o.rounding,t!==-1?t===0?(e=pn(o,n+4,r).times(.5),e.s=i.s,e):new o(NaN):(o.precision=n+6,o.rounding=1,i=i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(),o.precision=n,o.rounding=r,i.times(2)))};O.inverseTangent=O.atan=function(){var e,t,n,r,i,o,a,s,c,u=this,l=u.constructor,d=l.precision,m=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&d+4<=Bc)return a=pn(l,d+4,m).times(.25),a.s=u.s,a}else{if(!u.s)return new l(NaN);if(d+4<=Bc)return a=pn(l,d+4,m).times(.5),a.s=u.s,a}for(l.precision=s=d+10,l.rounding=1,n=Math.min(28,s/te+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(se=!1,t=Math.ceil(s/te),r=1,c=u.times(u),a=new l(u),i=u;e!==-1;)if(i=i.times(c),o=a.minus(i.div(r+=2)),i=i.times(c),a=o.plus(i.div(r+=2)),a.d[t]!==void 0)for(e=t;a.d[e]===o.d[e]&&e--;);return n&&(a=a.times(2<<n-1)),se=!0,J(a,l.precision=d,l.rounding=m,!0)};O.isFinite=function(){return!!this.d};O.isInteger=O.isInt=function(){return!!this.d&&St(this.e/te)>this.d.length-2};O.isNaN=function(){return!this.s};O.isNegative=O.isNeg=function(){return this.s<0};O.isPositive=O.isPos=function(){return this.s>0};O.isZero=function(){return!!this.d&&this.d[0]===0};O.lessThan=O.lt=function(e){return this.cmp(e)<0};O.lessThanOrEqualTo=O.lte=function(e){return this.cmp(e)<1};O.logarithm=O.log=function(e){var t,n,r,i,o,a,s,c,u=this,l=u.constructor,d=l.precision,m=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)o=!0;else{for(i=n[0];i%10===0;)i/=10;o=i!==1}if(se=!1,s=d+g,a=Fn(u,s),r=t?fa(l,s+10):Fn(e,s),c=Be(a,r,s,1),qi(c.d,i=d,m))do if(s+=10,a=Fn(u,s),r=t?fa(l,s+10):Fn(e,s),c=Be(a,r,s,1),!o){+pt(c.d).slice(i+1,i+15)+1==1e14&&(c=J(c,d+1,0));break}while(qi(c.d,i+=10,m));return se=!0,J(c,d,m)};O.minus=O.sub=function(e){var t,n,r,i,o,a,s,c,u,l,d,m,g=this,p=g.constructor;if(e=new p(e),!g.d||!e.d)return!g.s||!e.s?e=new p(NaN):g.d?e.s=-e.s:e=new p(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,m=e.d,s=p.precision,c=p.rounding,!u[0]||!m[0]){if(m[0])e.s=-e.s;else if(u[0])e=new p(g);else return new p(c===3?-0:0);return se?J(e,s,c):e}if(n=St(e.e/te),l=St(g.e/te),u=u.slice(),o=l-n,o){for(d=o<0,d?(t=u,o=-o,a=m.length):(t=m,n=l,a=u.length),r=Math.max(Math.ceil(s/te),a)+2,o>r&&(o=r,t.length=1),t.reverse(),r=o;r--;)t.push(0);t.reverse()}else{for(r=u.length,a=m.length,d=r<a,d&&(a=r),r=0;r<a;r++)if(u[r]!=m[r]){d=u[r]<m[r];break}o=0}for(d&&(t=u,u=m,m=t,e.s=-e.s),a=u.length,r=m.length-a;r>0;--r)u[a++]=0;for(r=m.length;r>o;){if(u[--r]<m[r]){for(i=r;i&&u[--i]===0;)u[i]=en-1;--u[i],u[r]+=en}u[r]-=m[r]}for(;u[--a]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=ga(u,n),se?J(e,s,c):e):new p(c===3?-0:0)};O.modulo=O.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]?J(new r(n),r.precision,r.rounding):(se=!1,r.modulo==9?(t=Be(n,e.abs(),0,3,1),t.s*=e.s):t=Be(n,e,0,r.modulo,1),t=t.times(e),se=!0,n.minus(t))};O.naturalExponential=O.exp=function(){return Lc(this)};O.naturalLogarithm=O.ln=function(){return Fn(this)};O.negated=O.neg=function(){var e=new this.constructor(this);return e.s=-e.s,J(e)};O.plus=O.add=function(e){var t,n,r,i,o,a,s,c,u,l,d=this,m=d.constructor;if(e=new m(e),!d.d||!e.d)return!d.s||!e.s?e=new m(NaN):d.d||(e=new m(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=m.precision,c=m.rounding,!u[0]||!l[0])return l[0]||(e=new m(d)),se?J(e,s,c):e;if(o=St(d.e/te),r=St(e.e/te),u=u.slice(),i=o-r,i){for(i<0?(n=u,i=-i,a=l.length):(n=l,r=o,a=u.length),o=Math.ceil(s/te),a=o>a?o+1:a+1,i>a&&(i=a,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(a=u.length,i=l.length,a-i<0&&(i=a,n=l,l=u,u=n),t=0;i;)t=(u[--i]=u[i]+l[i]+t)/en|0,u[i]%=en;for(t&&(u.unshift(t),++r),a=u.length;u[--a]==0;)u.pop();return e.d=u,e.e=ga(u,r),se?J(e,s,c):e};O.precision=O.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Un+e);return n.d?(t=dh(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};O.round=function(){var e=this,t=e.constructor;return J(new t(e),e.e+1,t.rounding)};O.sine=O.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())+te,r.rounding=1,n=$0(r,hh(r,n)),r.precision=e,r.rounding=t,J(Sn>2?n.neg():n,e,t,!0)):new r(NaN)};O.squareRoot=O.sqrt=function(){var e,t,n,r,i,o,a=this,s=a.d,c=a.e,u=a.s,l=a.constructor;if(u!==1||!s||!s[0])return new l(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);for(se=!1,u=Math.sqrt(+a),u==0||u==1/0?(t=pt(s),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=St((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(o=r,r=o.plus(Be(a,o,n+2,1)).times(.5),pt(o.d).slice(0,n)===(t=pt(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(J(o,c+1,0),o.times(o).eq(a))){r=o;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(J(r,c+1,1),e=!r.times(r).eq(a));break}return se=!0,J(r,c,l.rounding,e)};O.tangent=O.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=Be(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,J(Sn==2||Sn==4?n.neg():n,e,t,!0)):new r(NaN)};O.times=O.mul=function(e){var t,n,r,i,o,a,s,c,u,l=this,d=l.constructor,m=l.d,g=(e=new d(e)).d;if(e.s*=l.s,!m||!m[0]||!g||!g[0])return new d(!e.s||m&&!m[0]&&!g||g&&!g[0]&&!m?NaN:!m||!g?e.s/0:e.s*0);for(n=St(l.e/te)+St(e.e/te),c=m.length,u=g.length,c<u&&(o=m,m=g,g=o,a=c,c=u,u=a),o=[],a=c+u,r=a;r--;)o.push(0);for(r=u;--r>=0;){for(t=0,i=c+r;i>r;)s=o[i]+g[r]*m[i-r-1]+t,o[i--]=s%en|0,t=s/en|0;o[i]=(o[i]+t)%en|0}for(;!o[--a];)o.pop();return t?++n:o.shift(),e.d=o,e.e=ga(o,n),se?J(e,d.precision,d.rounding):e};O.toBinary=function(e,t){return qc(this,2,e,t)};O.toDecimalPlaces=O.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Tt(e,0,Mn),t===void 0?t=r.rounding:Tt(t,0,8),J(n,e+n.e+1,t))};O.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=mn(r,!0):(Tt(e,0,Mn),t===void 0?t=i.rounding:Tt(t,0,8),r=J(new i(r),e+1,t),n=mn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};O.toFixed=function(e,t){var n,r,i=this,o=i.constructor;return e===void 0?n=mn(i):(Tt(e,0,Mn),t===void 0?t=o.rounding:Tt(t,0,8),r=J(new o(i),e+i.e+1,t),n=mn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};O.toFraction=function(e){var t,n,r,i,o,a,s,c,u,l,d,m,g=this,p=g.d,h=g.constructor;if(!p)return new h(g);if(u=n=new h(1),r=c=new h(0),t=new h(r),o=t.e=dh(p)-g.e-1,a=o%te,t.d[0]=ze(10,a<0?te+a:a),e==null)e=o>0?t:u;else{if(s=new h(e),!s.isInt()||s.lt(u))throw Error(Un+s);e=s.gt(t)?o>0?t:u:s}for(se=!1,s=new h(pt(p)),l=h.precision,h.precision=o=p.length*te*2;d=Be(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=Be(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,m=Be(u,r,o,1).minus(g).abs().cmp(Be(c,n,o,1).minus(g).abs())<1?[u,r]:[c,n],h.precision=l,se=!0,m};O.toHexadecimal=O.toHex=function(e,t){return qc(this,16,e,t)};O.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:Tt(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]?(se=!1,n=Be(n,e,0,t,1).times(e),se=!0,J(n)):(e.s=n.s,n=e),n};O.toNumber=function(){return+this};O.toOctal=function(e,t){return qc(this,8,e,t)};O.toPower=O.pow=function(e){var t,n,r,i,o,a,s=this,c=s.constructor,u=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(ze(+s,u));if(s=new c(s),s.eq(1))return s;if(r=c.precision,o=c.rounding,e.eq(1))return J(s,r,o);if(t=St(e.e/te),t>=e.d.length-1&&(n=u<0?-u:u)<=B0)return i=ph(c,s,n,r),e.s<0?new c(1).div(i):J(i,r,o);if(a=s.s,a<0){if(t<e.d.length-1)return new c(NaN);if((e.d[t]&1)==0&&(a=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=a,s}return n=ze(+s,u),t=n==0||!isFinite(n)?St(u*(Math.log("0."+pt(s.d))/Math.LN10+s.e+1)):new c(n+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?a/0:0):(se=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Lc(e.times(Fn(s,r+n)),r),i.d&&(i=J(i,r+5,1),qi(i.d,r,o)&&(t=r+10,i=J(Lc(e.times(Fn(s,t+n)),t),t+5,1),+pt(i.d).slice(r+1,r+15)+1==1e14&&(i=J(i,r+1,0)))),i.s=a,se=!0,c.rounding=o,J(i,r,o))};O.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=mn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Tt(e,1,Mn),t===void 0?t=i.rounding:Tt(t,0,8),r=J(new i(r),e,t),n=mn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};O.toSignificantDigits=O.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Tt(e,1,Mn),t===void 0?t=r.rounding:Tt(t,0,8)),J(new r(n),e,t)};O.toString=function(){var e=this,t=e.constructor,n=mn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};O.truncated=O.trunc=function(){return J(new this.constructor(this),this.e+1,1)};O.valueOf=O.toJSON=function(){var e=this,t=e.constructor,n=mn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function pt(e){var t,n,r,i=e.length-1,o="",a=e[0];if(i>0){for(o+=a,t=1;t<i;t++)r=e[t]+"",n=te-r.length,n&&(o+=Nn(n)),o+=r;a=e[t],r=a+"",n=te-r.length,n&&(o+=Nn(n))}else if(a===0)return"0";for(;a%10===0;)a/=10;return o+a}function Tt(e,t,n){if(e!==~~e||e<t||e>n)throw Error(Un+e)}function qi(e,t,n,r){var i,o,a,s;for(o=e[0];o>=10;o/=10)--t;return--t<0?(t+=te,i=0):(i=Math.ceil((t+1)/te),t%=te),o=ze(10,te-t),s=e[i]%o|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),a=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):a=(n<4&&s+1==o||n>3&&s+1==o/2)&&(e[i+1]/o/100|0)==ze(10,t-2)-1||(s==o/2||s==0)&&(e[i+1]/o/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),a=(r||n<4)&&s==9999||!r&&n>3&&s==4999):a=((r||n<4)&&s+1==o||!r&&n>3&&s+1==o/2)&&(e[i+1]/o/1e3|0)==ze(10,t-3)-1,a}function la(e,t,n){for(var r,i=[0],o,a=0,s=e.length;a<s;){for(o=i.length;o--;)i[o]*=t;for(i[0]+=Uc.indexOf(e.charAt(a++)),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 q0(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/ba(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=qr(e,1,t.times(i),new e(1));for(var o=n;o--;){var a=t.times(t);t=a.times(a).minus(a).times(8).plus(1)}return e.precision-=n,t}var Be=(function(){function e(r,i,o){var a,s=0,c=r.length;for(r=r.slice();c--;)a=r[c]*i+s,r[c]=a%o|0,s=a/o|0;return s&&r.unshift(s),r}function t(r,i,o,a){var s,c;if(o!=a)c=o>a?1:-1;else for(s=c=0;s<o;s++)if(r[s]!=i[s]){c=r[s]>i[s]?1:-1;break}return c}function n(r,i,o,a){for(var s=0;o--;)r[o]-=s,s=r[o]<i[o]?1:0,r[o]=s*a+r[o]-i[o];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,o,a,s,c){var u,l,d,m,g,p,h,y,A,S,j,I,v,$,G,we,Te,ae,V,Fe,Z=r.constructor,rt=r.s==i.s?1:-1,de=r.d,ie=i.d;if(!de||!de[0]||!ie||!ie[0])return new Z(!r.s||!i.s||(de?ie&&de[0]==ie[0]:!ie)?NaN:de&&de[0]==0||!ie?rt*0:rt/0);for(c?(g=1,l=r.e-i.e):(c=en,g=te,l=St(r.e/g)-St(i.e/g)),V=ie.length,Te=de.length,A=new Z(rt),S=A.d=[],d=0;ie[d]==(de[d]||0);d++);if(ie[d]>(de[d]||0)&&l--,o==null?($=o=Z.precision,a=Z.rounding):s?$=o+(r.e-i.e)+1:$=o,$<0)S.push(1),p=!0;else{if($=$/g+2|0,d=0,V==1){for(m=0,ie=ie[0],$++;(d<Te||m)&&$--;d++)G=m*c+(de[d]||0),S[d]=G/ie|0,m=G%ie|0;p=m||d<Te}else{for(m=c/(ie[0]+1)|0,m>1&&(ie=e(ie,m,c),de=e(de,m,c),V=ie.length,Te=de.length),we=V,j=de.slice(0,V),I=j.length;I<V;)j[I++]=0;Fe=ie.slice(),Fe.unshift(0),ae=ie[0],ie[1]>=c/2&&++ae;do m=0,u=t(ie,j,V,I),u<0?(v=j[0],V!=I&&(v=v*c+(j[1]||0)),m=v/ae|0,m>1?(m>=c&&(m=c-1),h=e(ie,m,c),y=h.length,I=j.length,u=t(h,j,y,I),u==1&&(m--,n(h,V<y?Fe:ie,y,c))):(m==0&&(u=m=1),h=ie.slice()),y=h.length,y<I&&h.unshift(0),n(j,h,I,c),u==-1&&(I=j.length,u=t(ie,j,V,I),u<1&&(m++,n(j,V<I?Fe:ie,I,c))),I=j.length):u===0&&(m++,j=[0]),S[d++]=m,u&&j[0]?j[I++]=de[we]||0:(j=[de[we]],I=1);while((we++<Te||j[0]!==void 0)&&$--);p=j[0]!==void 0}S[0]||S.shift()}if(g==1)A.e=l,ah=p;else{for(d=1,m=S[0];m>=10;m/=10)d++;A.e=d+l*g-1,J(A,s?o+A.e+1:o,a,p)}return A}})();function J(e,t,n,r){var i,o,a,s,c,u,l,d,m,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(o=t-i,o<0)o+=te,a=t,l=d[m=0],c=l/ze(10,i-a-1)%10|0;else if(m=Math.ceil((o+1)/te),s=d.length,m>=s)if(r){for(;s++<=m;)d.push(0);l=c=0,i=1,o%=te,a=o-te+1}else break e;else{for(l=s=d[m],i=1;s>=10;s/=10)i++;o%=te,a=o-te+i,c=a<0?0:l/ze(10,i-a-1)%10|0}if(r=r||t<0||d[m+1]!==void 0||(a<0?l:l%ze(10,i-a-1)),u=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(o>0?a>0?l/ze(10,i-a):0:d[m-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,u?(t-=e.e+1,d[0]=ze(10,(te-t%te)%te),e.e=-t||0):d[0]=e.e=0,e;if(o==0?(d.length=m,s=1,m--):(d.length=m+1,s=ze(10,te-o),d[m]=a>0?(l/ze(10,i-a)%ze(10,a)|0)*s:0),u)for(;;)if(m==0){for(o=1,a=d[0];a>=10;a/=10)o++;for(a=d[0]+=s,s=1;a>=10;a/=10)s++;o!=s&&(e.e++,d[0]==en&&(d[0]=1));break}else{if(d[m]+=s,d[m]!=en)break;d[m--]=0,s=1}for(o=d.length;d[--o]===0;)d.pop()}return se&&(e.e>g.maxE?(e.d=null,e.e=NaN):e.e<g.minE&&(e.e=0,e.d=[0])),e}function mn(e,t,n){if(!e.isFinite())return fh(e);var r,i=e.e,o=pt(e.d),a=o.length;return t?(n&&(r=n-a)>0?o=o.charAt(0)+"."+o.slice(1)+Nn(r):a>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(e.e<0?"e":"e+")+e.e):i<0?(o="0."+Nn(-i-1)+o,n&&(r=n-a)>0&&(o+=Nn(r))):i>=a?(o+=Nn(i+1-a),n&&(r=n-i-1)>0&&(o=o+"."+Nn(r))):((r=i+1)<a&&(o=o.slice(0,r)+"."+o.slice(r)),n&&(r=n-a)>0&&(i+1===a&&(o+="."),o+=Nn(r))),o}function ga(e,t){var n=e[0];for(t*=te;n>=10;n/=10)t++;return t}function fa(e,t,n){if(t>L0)throw se=!0,n&&(e.precision=n),Error(sh);return J(new e(pa),t,1,!0)}function pn(e,t,n){if(t>Bc)throw Error(sh);return J(new e(ma),t,n,!0)}function dh(e){var t=e.length-1,n=t*te+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 Nn(e){for(var t="";e--;)t+="0";return t}function ph(e,t,n,r){var i,o=new e(1),a=Math.ceil(r/te+4);for(se=!1;;){if(n%2&&(o=o.times(t),ih(o.d,a)&&(i=!0)),n=St(n/2),n===0){n=o.d.length-1,i&&o.d[n]===0&&++o.d[n];break}t=t.times(t),ih(t.d,a)}return se=!0,o}function rh(e){return e.d[e.d.length-1]&1}function mh(e,t,n){for(var r,i,o=new e(t[0]),a=0;++a<t.length;){if(i=new e(t[a]),!i.s){o=i;break}r=o.cmp(i),(r===n||r===0&&o.s===n)&&(o=i)}return o}function Lc(e,t){var n,r,i,o,a,s,c,u=0,l=0,d=0,m=e.constructor,g=m.rounding,p=m.precision;if(!e.d||!e.d[0]||e.e>17)return new m(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(se=!1,c=p):c=t,s=new m(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(ze(2,d))/Math.LN10*2+5|0,c+=r,n=o=a=new m(1),m.precision=c;;){if(o=J(o.times(e),c,1),n=n.times(++l),s=a.plus(Be(o,n,c,1)),pt(s.d).slice(0,c)===pt(a.d).slice(0,c)){for(i=d;i--;)a=J(a.times(a),c,1);if(t==null)if(u<3&&qi(a.d,c-r,g,u))m.precision=c+=10,n=o=s=new m(1),l=0,u++;else return J(a,m.precision=p,g,se=!0);else return m.precision=p,a}a=s}}function Fn(e,t){var n,r,i,o,a,s,c,u,l,d,m,g=1,p=10,h=e,y=h.d,A=h.constructor,S=A.rounding,j=A.precision;if(h.s<0||!y||!y[0]||!h.e&&y[0]==1&&y.length==1)return new A(y&&!y[0]?-1/0:h.s!=1?NaN:y?0:h);if(t==null?(se=!1,l=j):l=t,A.precision=l+=p,n=pt(y),r=n.charAt(0),Math.abs(o=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=pt(h.d),r=n.charAt(0),g++;o=h.e,r>1?(h=new A("0."+n),o++):h=new A(r+"."+n.slice(1))}else return u=fa(A,l+2,j).times(o+""),h=Fn(new A(r+"."+n.slice(1)),l-p).plus(u),A.precision=j,t==null?J(h,j,S,se=!0):h;for(d=h,c=a=h=Be(h.minus(1),h.plus(1),l,1),m=J(h.times(h),l,1),i=3;;){if(a=J(a.times(m),l,1),u=c.plus(Be(a,new A(i),l,1)),pt(u.d).slice(0,l)===pt(c.d).slice(0,l))if(c=c.times(2),o!==0&&(c=c.plus(fa(A,l+2,j).times(o+""))),c=Be(c,new A(g),l,1),t==null)if(qi(c.d,l-p,S,s))A.precision=l+=p,u=a=h=Be(d.minus(1),d.plus(1),l,1),m=J(h.times(h),l,1),i=s=1;else return J(c,A.precision=j,S,se=!0);else return A.precision=j,c;c=u,i+=2}}function fh(e){return String(e.s*e.s/0)}function da(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)%te,n<0&&(r+=te),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=te;r<i;)e.d.push(+t.slice(r,r+=te));t=t.slice(r),r=te-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),se&&(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 V0(e,t){var n,r,i,o,a,s,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),lh.test(t))return da(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(U0.test(t))n=16,t=t.toLowerCase();else if(F0.test(t))n=2;else if(M0.test(t))n=8;else throw Error(Un+t);for(o=t.search(/p/i),o>0?(c=+t.slice(o+1),t=t.substring(2,o)):t=t.slice(2),o=t.indexOf("."),a=o>=0,r=e.constructor,a&&(t=t.replace(".",""),s=t.length,o=s-o,i=ph(r,new r(n),o,o*2)),u=la(t,n,en),l=u.length-1,o=l;u[o]===0;--o)u.pop();return o<0?new r(e.s*0):(e.e=ga(u,l),e.d=u,se=!1,a&&(e=Be(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?ze(2,c):tn.pow(2,c))),se=!0,e)}function $0(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:qr(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/ba(5,n)),t=qr(e,2,t,t);for(var i,o=new e(5),a=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(o.plus(i.times(a.times(i).minus(s))));return t}function qr(e,t,n,r,i){var o,a,s,c,u=1,l=e.precision,d=Math.ceil(l/te);for(se=!1,c=n.times(n),s=new e(r);;){if(a=Be(s.times(c),new e(t++*t++),l,1),s=i?r.plus(a):r.minus(a),r=Be(a.times(c),new e(t++*t++),l,1),a=s.plus(r),a.d[d]!==void 0){for(o=d;a.d[o]===s.d[o]&&o--;);if(o==-1)break}o=s,s=r,r=a,a=o,u++}return se=!0,a.d.length=d+1,a}function ba(e,t){for(var n=e;--t;)n*=e;return n}function hh(e,t){var n,r=t.s<0,i=pn(e,e.precision,1),o=i.times(.5);if(t=t.abs(),t.lte(o))return Sn=r?4:1,t;if(n=t.divToInt(i),n.isZero())Sn=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(o))return Sn=rh(n)?r?2:3:r?4:1,t;Sn=rh(n)?r?1:4:r?3:2}return t.minus(i).abs()}function qc(e,t,n,r){var i,o,a,s,c,u,l,d,m,g=e.constructor,p=n!==void 0;if(p?(Tt(n,1,Mn),r===void 0?r=g.rounding:Tt(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())l=fh(e);else{for(l=mn(e),a=l.indexOf("."),p?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,a>=0&&(l=l.replace(".",""),m=new g(1),m.e=l.length-a,m.d=la(mn(m),10,i),m.e=m.d.length),d=la(l,10,i),o=c=d.length;d[--c]==0;)d.pop();if(!d[0])l=p?"0p+0":"0";else{if(a<0?o--:(e=new g(e),e.d=d,e.e=o,e=Be(e,m,n,r,0,i),d=e.d,o=e.e,u=ah),a=d[n],s=i/2,u=u||d[n+1]!==void 0,u=r<4?(a!==void 0||u)&&(r===0||r===(e.s<0?3:2)):a>s||a===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||(++o,d.unshift(1));for(c=d.length;!d[c-1];--c);for(a=0,l="";a<c;a++)l+=Uc.charAt(d[a]);if(p){if(c>1)if(t==16||t==8){for(a=t==16?4:3,--c;c%a;c++)l+="0";for(d=la(l,i,t),c=d.length;!d[c-1];--c);for(a=1,l="1.";a<c;a++)l+=Uc.charAt(d[a])}else l=l.charAt(0)+"."+l.slice(1);l=l+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)l="0"+l;l="0."+l}else if(++o>c)for(o-=c;o--;)l+="0";else o<c&&(l=l.slice(0,o)+"."+l.slice(o))}l=(t==16?"0x":t==2?"0b":t==8?"0o":"")+l}return e.s<0?"-"+l:l}function ih(e,t){if(e.length>t)return e.length=t,!0}function G0(e){return new this(e).abs()}function K0(e){return new this(e).acos()}function H0(e){return new this(e).acosh()}function W0(e,t){return new this(e).plus(t)}function Q0(e){return new this(e).asin()}function Z0(e){return new this(e).asinh()}function Y0(e){return new this(e).atan()}function J0(e){return new this(e).atanh()}function X0(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,o=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=pn(this,o,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?pn(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=pn(this,o,1).times(.5),n.s=e.s):t.s<0?(this.precision=o,this.rounding=1,n=this.atan(Be(e,t,o,1)),t=pn(this,o,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Be(e,t,o,1)),n}function z0(e){return new this(e).cbrt()}function ex(e){return J(e=new this(e),e.e+1,2)}function tx(e,t,n){return new this(e).clamp(t,n)}function nx(e){if(!e||typeof e!="object")throw Error(ha+"Object expected");var t,n,r,i=e.defaults===!0,o=["precision",1,Mn,"rounding",0,8,"toExpNeg",-Lr,0,"toExpPos",0,Lr,"maxE",0,Lr,"minE",-Lr,0,"modulo",0,9];for(t=0;t<o.length;t+=3)if(n=o[t],i&&(this[n]=Mc[n]),(r=e[n])!==void 0)if(St(r)===r&&r>=o[t+1]&&r<=o[t+2])this[n]=r;else throw Error(Un+n+": "+r);if(n="crypto",i&&(this[n]=Mc[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(ch);else this[n]=!1;else throw Error(Un+n+": "+r);return this}function rx(e){return new this(e).cos()}function ix(e){return new this(e).cosh()}function gh(e){var t,n,r;function i(o){var a,s,c,u=this;if(!(u instanceof i))return new i(o);if(u.constructor=i,oh(o)){u.s=o.s,se?!o.d||o.e>i.maxE?(u.e=NaN,u.d=null):o.e<i.minE?(u.e=0,u.d=[0]):(u.e=o.e,u.d=o.d.slice()):(u.e=o.e,u.d=o.d?o.d.slice():o.d);return}if(c=typeof o,c==="number"){if(o===0){u.s=1/o<0?-1:1,u.e=0,u.d=[0];return}if(o<0?(o=-o,u.s=-1):u.s=1,o===~~o&&o<1e7){for(a=0,s=o;s>=10;s/=10)a++;se?a>i.maxE?(u.e=NaN,u.d=null):a<i.minE?(u.e=0,u.d=[0]):(u.e=a,u.d=[o]):(u.e=a,u.d=[o]);return}if(o*0!==0){o||(u.s=NaN),u.e=NaN,u.d=null;return}return da(u,o.toString())}if(c==="string")return(s=o.charCodeAt(0))===45?(o=o.slice(1),u.s=-1):(s===43&&(o=o.slice(1)),u.s=1),lh.test(o)?da(u,o):V0(u,o);if(c==="bigint")return o<0?(o=-o,u.s=-1):u.s=1,da(u,o.toString());throw Error(Un+o)}if(i.prototype=O,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=nx,i.clone=gh,i.isDecimal=oh,i.abs=G0,i.acos=K0,i.acosh=H0,i.add=W0,i.asin=Q0,i.asinh=Z0,i.atan=Y0,i.atanh=J0,i.atan2=X0,i.cbrt=z0,i.ceil=ex,i.clamp=tx,i.cos=rx,i.cosh=ix,i.div=ox,i.exp=ax,i.floor=sx,i.hypot=cx,i.ln=ux,i.log=lx,i.log10=px,i.log2=dx,i.max=mx,i.min=fx,i.mod=hx,i.mul=gx,i.pow=bx,i.random=_x,i.round=yx,i.sign=Sx,i.sin=vx,i.sinh=xx,i.sqrt=Ix,i.sub=Ax,i.sum=wx,i.tan=Cx,i.tanh=Px,i.trunc=Ox,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 ox(e,t){return new this(e).div(t)}function ax(e){return new this(e).exp()}function sx(e){return J(e=new this(e),e.e+1,3)}function cx(){var e,t,n=new this(0);for(se=!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 se=!0,new this(1/0);n=t}return se=!0,n.sqrt()}function oh(e){return e instanceof tn||e&&e.toStringTag===uh||!1}function ux(e){return new this(e).ln()}function lx(e,t){return new this(e).log(t)}function dx(e){return new this(e).log(2)}function px(e){return new this(e).log(10)}function mx(){return mh(this,arguments,-1)}function fx(){return mh(this,arguments,1)}function hx(e,t){return new this(e).mod(t)}function gx(e,t){return new this(e).mul(t)}function bx(e,t){return new this(e).pow(t)}function _x(e){var t,n,r,i,o=0,a=new this(1),s=[];if(e===void 0?e=this.precision:Tt(e,1,Mn),r=Math.ceil(e/te),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));o<r;)i=t[o],i>=429e7?t[o]=crypto.getRandomValues(new Uint32Array(1))[0]:s[o++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);o<r;)i=t[o]+(t[o+1]<<8)+(t[o+2]<<16)+((t[o+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,o):(s.push(i%1e7),o+=4);o=r/4}else throw Error(ch);else for(;o<r;)s[o++]=Math.random()*1e7|0;for(r=s[--o],e%=te,r&&e&&(i=ze(10,te-e),s[o]=(r/i|0)*i);s[o]===0;o--)s.pop();if(o<0)n=0,s=[0];else{for(n=-1;s[0]===0;n-=te)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<te&&(n-=te-r)}return a.e=n,a.d=s,a}function yx(e){return J(e=new this(e),e.e+1,this.rounding)}function Sx(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function vx(e){return new this(e).sin()}function xx(e){return new this(e).sinh()}function Ix(e){return new this(e).sqrt()}function Ax(e,t){return new this(e).sub(t)}function wx(){var e=0,t=arguments,n=new this(t[e]);for(se=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return se=!0,J(n,this.precision,this.rounding)}function Cx(e){return new this(e).tan()}function Px(e){return new this(e).tanh()}function Ox(e){return J(e=new this(e),e.e+1,1)}O[Symbol.for("nodejs.util.inspect.custom")]=O.toString;O[Symbol.toStringTag]="Decimal";var tn=O.constructor=gh(Mc);pa=new tn(pa);ma=new tn(ma);var{PAYLOAD_BYTES:Ex}={PAYLOAD_BYTES:20},{KSUID_EPOCH:Tx}={KSUID_EPOCH:14e8},{getRandomBytes:Rx}={getRandomBytes:({size:t})=>{let n=new Uint8Array(t);return globalThis.crypto.getRandomValues(n),n}},{ALPHABET:jx}={ALPHABET:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},{ENCODED_LENGTH:kx}={ENCODED_LENGTH:27},{base62Encode:Dx}=(e=>({base62Encode:({bytes:n,padTo:r})=>{let i=[],o=new Uint8Array(n),a=!1;for(;!a;){a=!0;let s=0;for(let c=0;c<o.length;c++){let u=s*256+o[c];o[c]=Math.floor(u/62),s=u%62,o[c]!==0&&(a=!1)}i.push(s)}for(i.reverse();i.length<r;)i.unshift(0);return i.map(s=>e[s]).join("")}}))(jx),{generateKsuid:bh}=((e,t,n,r,i)=>({generateKsuid:({prefix:a=""}={})=>{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`${a}${l}`}}))(Ex,Tx,Rx,Dx,kx);var _h={randomSync:()=>({string:bh({})})};import{z as Ie}from"zod/v4";var Nx=202,Fx=502,Ux=400,Mx=409,Bx=100,Lx=201,qx=417;var Vx=403,$x=504,Gx=410,Kx=505,Hx=418,Wx=419,Qx=507,Zx=500,Yx=411,Jx=423,Xx=420,zx=405,eI=301,tI=302,nI=207,rI=300,iI=511,oI=204,aI=203,sI=406,cI=404,uI=501,lI=304,dI=200,pI=206,mI=402,fI=308,hI=412,gI=428,bI=102,_I=407,yI=431,SI=408,vI=413,xI=414,II=416,AI=205,wI=303,CI=503,PI=101,OI=307,EI=429,TI=401,RI=422,jI=415,kI=305,yh={ACCEPTED:Nx,BAD_GATEWAY:Fx,BAD_REQUEST:Ux,CONFLICT:Mx,CONTINUE:Bx,CREATED:Lx,EXPECTATION_FAILED:qx,FORBIDDEN:Vx,GATEWAY_TIMEOUT:$x,GONE:Gx,HTTP_VERSION_NOT_SUPPORTED:Kx,IM_A_TEAPOT:Hx,INSUFFICIENT_SPACE_ON_RESOURCE:Wx,INSUFFICIENT_STORAGE:Qx,INTERNAL_SERVER_ERROR:Zx,LENGTH_REQUIRED:Yx,LOCKED:Jx,METHOD_FAILURE:Xx,METHOD_NOT_ALLOWED:zx,MOVED_PERMANENTLY:eI,MOVED_TEMPORARILY:tI,MULTI_STATUS:nI,MULTIPLE_CHOICES:rI,NETWORK_AUTHENTICATION_REQUIRED:iI,NO_CONTENT:oI,NON_AUTHORITATIVE_INFORMATION:aI,NOT_ACCEPTABLE:sI,NOT_FOUND:cI,NOT_IMPLEMENTED:uI,NOT_MODIFIED:lI,OK:dI,PARTIAL_CONTENT:pI,PAYMENT_REQUIRED:mI,PERMANENT_REDIRECT:fI,PRECONDITION_FAILED:hI,PRECONDITION_REQUIRED:gI,PROCESSING:bI,PROXY_AUTHENTICATION_REQUIRED:_I,REQUEST_HEADER_FIELDS_TOO_LARGE:yI,REQUEST_TIMEOUT:SI,REQUEST_TOO_LONG:vI,REQUEST_URI_TOO_LONG:xI,REQUESTED_RANGE_NOT_SATISFIABLE:II,RESET_CONTENT:AI,SEE_OTHER:wI,SERVICE_UNAVAILABLE:CI,SWITCHING_PROTOCOLS:PI,TEMPORARY_REDIRECT:OI,TOO_MANY_REQUESTS:EI,UNAUTHORIZED:TI,UNPROCESSABLE_ENTITY:RI,UNSUPPORTED_MEDIA_TYPE:jI,USE_PROXY:kI};var Sh={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"},vh={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 DI(e){var t=Sh[e.toString()];if(!t)throw new Error("Status code does not exist: "+e);return t}function xh(e){var t=vh[e];if(!t)throw new Error("Reason phrase does not exist: "+e);return t}var Ih=DI;var Bn;(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"})(Bn||(Bn={}));var _a=function(){return _a=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},_a.apply(this,arguments)},aM=_a(_a({},yh),{getStatusCode:xh,getStatusText:Ih});var{generateId:Vr}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(_h),{BILLING_CONTROL_KEYS:ya}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:NI}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:Ah}={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:Qt}={nullish:t=>t==null},{FeatureType:vt}=(()=>{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:Sa}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:Vi}={Infinite:"inf"},{EntInterval:$r}=(()=>{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:vn}=(()=>{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:FI}={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:UI}={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[o,a]of r)(a.usage_tiers??[]).forEach((s,c)=>{c<n&&i[c].push({currency:o,amount:s.amount,...s.flat_amount!==void 0?{flat_amount:s.flat_amount}:{}})});return i}},{TierInfinite:Vc}={TierInfinite:"inf"},{FeatureUsageType:Ln}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:Gr}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Usage="usage"})(e||(e={})),{PriceType:e}})(),{BillingType:Kr}=(()=>{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:$i}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:qn}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:xn}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:Hr}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{InternalError:MI}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=500,data:o}){super(n),this.name="InternalError",this.code=r||"internal_error",this.statusCode=i,this.data=o}}return{InternalError:e}})(),{getItemFeatureType:wh}=((e,t)=>({getItemFeatureType:({item:r,features:i})=>{let o=i.find(a=>a.id===r.feature_id);if(o)return o.type===e.Boolean?t.Static:o.type===e.CreditSystem?t.SingleUse:o.config?.usage_type}}))(vt,xn),{billingControlsFromColumns:Ch}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(ya),{nullish:Wr}={nullish:t=>t==null},{RecaseError:Rt}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=400,data:o}){super(n),this.name="RecaseError",this.code=r||"invalid_request",this.statusCode=i,this.data=o}}return{RecaseError:e}})(),{ErrCode:Bt}={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:BI}=((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})}}))(Rt,Bt),{notNullish:Qr}=(e=>({notNullish:n=>!e(n)}))(Wr),{keyToTitle:Ph}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:LI}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:qI}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ApiFeatureType:VI}=(()=>{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:$c}=(()=>{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:Oh}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:$I}={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:GI}=(e=>({COMMON_SET:new Set(e)}))(Oh),{hasNoDuplicateCurrencies:Eh}={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:Th}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{TierBehavior:va}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:Zr}=(()=>{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:Gi}=(()=>{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:Gc}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:KI}=(()=>{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:HI}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:WI}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Rh}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ie),{flatCreditRateShape:jh}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(Ie),{CreditTierSchema:QI}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(Ie),{CreditMultiplierSchema:ZI}=((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"})}))(Ie,Rh),{MarkupEntrySchema:kh}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ie),{ModelMarkupsSchema:YI}=((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()}))(Ie,kh),{isFeaturePriceItem:Kc}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(Qr),{notNullish:ur}={notNullish:t=>t!=null},{isAiCreditSystem:Hc}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(vt),{VIOLATION_MESSAGES:JI}={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:XI}={sameSpecificity:(t,n)=>Object.keys(t.match).length===Object.keys(n.match).length&&(t.priority??null)===(n.priority??null)},{matchesCanCoexist:Dh}={matchesCanCoexist:(t,n)=>Object.entries(t).every(([r,i])=>{let o=Object.entries(n).find(([a])=>a===r)?.[1];return o===void 0||o===i})},{formatCreditMatch:zI}={formatCreditMatch:t=>Object.entries(t).map(([n,r])=>`${n}=${r}`).join(", ")},{validateMultiplierShape:eA}={validateMultiplierShape:({name:t,multiplier:n,invalidCreditSystem:r})=>{let i=n.factor!==void 0,o=n.add!==void 0;!i&&!o&&r(`Multiplier "${t}" needs a factor or an add.`);let a=Number(n.factor);i&&!(Number.isFinite(a)&&a>0)&&r(`Multiplier "${t}" factor must be greater than zero.`);let s=Number(n.add);o&&!Number.isFinite(s)&&r(`Multiplier "${t}" add must be a number.`),i&&(n.factor=a),o&&(n.add=s)}},{minimumCreditRateAmount:tA}={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:nA}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((o,a)=>{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(m=>e(m.match,u.match));(l||u===a)&&e(a.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(o,c)},new t(i))}))(Dh,tn),{validateCreditSystemSchemaReferences:rA}=((e,t,n,r)=>({validateCreditSystemSchemaReferences:({config:o,allFeatures:a,selfFeatureId:s})=>{let c=Array.isArray(o?.schema)?o.schema:[];if(c.length!==0)for(let u of c){let l=u.metered_feature_id;if(!l||l===s)continue;let d=a.find(m=>m.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})}}}}))(vt,Rt,Bt,Ln),{isPriceItem:Wc}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(Qr,Wr),{isFeatureItem:xa}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(Qr,Wr),{itemToBillingInterval:Vn}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(Qt,vn),{rolloverConfigToIssue:iA}={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:Ia}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(Qt,$r,xn),{itemToEntIntervalCount:Aa}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:Yr}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:wa}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(ur,Qt),{toKey:Nh}={toKey:t=>t.toLowerCase()},{priceOwnedStripePriceId:oA}=(e=>({priceOwnedStripePriceId:({price:n})=>{let r=n.config,i=r.stripe_prepaid_price_v2_id||r.stripe_price_id;return e(i)?null:i}}))(Qt),{UsageTierSchema:Qc}=((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()}))}))(Ie,Vi),{IgnoredFixedPriceMetadataSchema:aA}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(Ie),{hasCatalogCurrencies:sA}={hasCatalogCurrencies:t=>Object.keys(t??{}).length>0},{usageTiersToComparisonShape:cA}={usageTiersToComparisonShape:t=>t.map((n,r)=>({amount:n.amount,flat_amount:n.flat_amount??0,to:r===t.length-1?null:n.to}))},{normalizedAllocatedBillingBehavior:uA}=(e=>({normalizedAllocatedBillingBehavior:n=>n.allocated_billing_behavior??(n.should_prorate?e.Prorated:e.Arrear)}))(qn),{getResetUsage:Fh}=((e,t,n,r)=>({getResetUsage:({item:o,feature:a})=>{if(o.feature_id)return e(o.reset_usage_when_enabled)&&(t(o)||n(o))&&a?a?.config?.usage_type===r.Single:o.reset_usage_when_enabled}}))(Wr,xa,Kc,Ln),{hasUnlimitedAllowanceType:lA}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(Sa),{normalizedEntitlementInterval:Uh}=(e=>({normalizedEntitlementInterval:n=>n.interval??e.Lifetime}))($r),{normalizedEntitlementIntervalCount:dA}=((e,t)=>({normalizedEntitlementIntervalCount:r=>e(r)===t.Lifetime?1:r.interval_count??1}))(Uh,$r),{normalizeOptionalId:pA}={normalizeOptionalId:t=>t||null},{rolloversAreSame:mA}=(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}))(Gc),{deterministicStringify:Zc}=(()=>{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:fA}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:hA}={expiriesAreSame:(t,n)=>(t.expiry_duration??null)===(n.expiry_duration??null)&&(t.expiry_length??null)==(n.expiry_length??null)},{itemToFeature:Mh}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{isFeaturePriceItem:Jr}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(ur),{ProductErrorCode:gA}={ProductErrorCode:{ProductNotFound:"product_not_found",ProductAlreadyExists:"product_already_exists",InvalidProductItem:"invalid_product_item"}},{buildUsagePriceCurrencies:bA}=(e=>({buildUsagePriceCurrencies:({baseTiers:n,itemTiers:r,flatCurrencies:i})=>{if(r?.length){let o=[...new Set(r.flatMap(s=>(s.additional_currencies??[]).map(c=>e(c.currency))))];if(o.length===0)return;let a={};for(let s of o)a[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 a}if(i?.length&&n.length>0){let o={};for(let{currency:a,amount:s}of i)o[e(a)]={usage_tiers:[{to:n[0].to,amount:s}]};return o}}}))(Nh),{itemToFeature:_A}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{shouldProrate:yA}=((e,t)=>({shouldProrate:r=>r?r===e.ProrateNextCycle||r===e.ProrateImmediately||r===t.ProrateImmediately||r===t.ProrateNextCycle:!0}))(Zr,Gi),{getBillingType:SA}=((e,t,n,r)=>({getBillingType:o=>{if(o.type===e.Fixed&&o.interval===t.OneOff)return n.OneOff;if(o.type===e.Fixed)return n.FixedCycle;let a=o;return a.bill_when===r.InAdvance||a.bill_when===r.StartOfPeriod?n.UsageInAdvance:a.bill_when===r.EndOfPeriod&&a.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Gr,vn,Kr,$i),{stripeResourceFields:vA}={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:xA}={PREVIEW_STRIPE_PRICE_ID_PREFIX:"price_PREVIEW_"},{PREVIEW_STRIPE_PRODUCT_ID_PREFIX:IA}={PREVIEW_STRIPE_PRODUCT_ID_PREFIX:"prod_PREVIEW_"},{normalizeOptionalId:AA}={normalizeOptionalId:t=>t||null},{stripeProductOnlyFields:wA}={stripeProductOnlyFields:["stripe_product_id","stripe_meter_id"]},{copyField:CA}=(e=>({copyField:({fromConfig:n,toConfig:r,field:i})=>!e(r[i])||e(n[i])?!1:(r[i]=n[i],!0)}))(Qt),{stripeResourceFields:PA}={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:OA}={handleCustomProductItems:({newPrices:t,newEnts:n,updatedPrices:r,updatedEnts:i,samePrices:o,sameEnts:a,features:s})=>({prices:[...t,...r,...o],entitlements:[...n,...i,...a].map(c=>({...c,feature:s.find(u=>u.id===c.feature_id)})),customPrices:[...t,...r],customEnts:[...n,...i],features:s})},{validateLicenseBillingMode:EA}=((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})}}))(Rt,Bt),{PlanItemMatchPrecision:TA}=(()=>{var e;return(function(t){t.FeatureBillingMethodCadence="feature_billing_method_cadence",t.FeatureCadence="feature_cadence"})(e||(e={})),{PlanItemMatchPrecision:e}})(),{catalogPlanItemIdentity:RA}={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:jA}={applyPrice:(t,n)=>n===void 0?t:n===null?null:{...n}},{planItemMatchesFilter:kA}={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:DA}={isFreeNonResetEntitlement:t=>t.price==null&&t.reset==null},{toApiPlanItemPrice:NA}={toApiPlanItemPrice:t=>t?{...t,billing_units:t.billing_units??1,max_purchase:t.max_purchase??null}:null},{toApiPlanItemRollover:FA}={toApiPlanItemRollover:t=>{if(t)return{...t,max:t.max??null}}},{applyFreeTrial:UA}={applyFreeTrial:(t,n)=>{if(n===void 0)return t;if(n!==null)return{...n}}},{applyLicenseUpsert:MA}={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:Bh}=(()=>{var e;return(function(t){t.Identity="identity",t.IdentityAndIncluded="identity_and_included"})(e||(e={})),{PlanItemFilterPrecision:e}})(),{additionalCurrenciesCompatible:Yc}={additionalCurrenciesCompatible:(t,n)=>(t??[]).every(r=>{let i=(n??[]).find(o=>o.currency.toLowerCase()===r.currency.toLowerCase());return!i||(r.amount??null)===(i.amount??null)&&(r.flat_amount??null)===(i.flat_amount??null)})},{toBasePriceParams:BA}={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:LA}=(e=>({tiersEqual:(n,r)=>!n?.length&&!r?.length?!0:!n||!r||n.length!==r.length?!1:n.every((i,o)=>{let a=r[o];return i.to===a.to&&(i.amount??0)===(a.amount??0)&&(i.flat_amount??null)===(a.flat_amount??null)&&e(i.additional_currencies,a.additional_currencies)})}))(Yc),{rolloversEqual:qA}={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:VA}={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:$A}=(e=>({creditSchemaFingerprint:n=>e(Object.fromEntries((n??[]).map(r=>[r.metered_feature_id,{...r,billing_units:r.billing_units??1}])))}))(Zc),{toCreatePlanItemParams:GA}={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:KA}=(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 o=n.price?.interval??n.reset?.interval;o!==void 0&&(i.interval=o);let a=n.price?.interval_count??n.reset?.interval_count;return o!==void 0&&(i.interval_count=a??1),r===e.IdentityAndIncluded&&typeof n.included=="number"&&n.unlimited!==!0&&(n.reset!=null||n.price!=null)&&(i.included=n.included),i}}))(Bh),{FreeTrialDuration:HA}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{arraysEqual:WA}={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(o=>{let a=i.findIndex(s=>r(o,s));return a===-1?!1:(i.splice(a,1),!0)})}},{normalizeIntervalCount:QA}={normalizeIntervalCount:({interval:t,intervalCount:n})=>t?n??1:n??""},{hasLicenseCustomize:Lh}={hasLicenseCustomize:t=>t!=null&&(t.price!==void 0||t.add_items!==void 0||t.remove_items!==void 0)},{byLicensePlanId:ZA}={byLicensePlanId:(t,n)=>t.license_plan_id.localeCompare(n.license_plan_id)},{variantSettingKeys:YA}={variantSettingKeys:["name","description","group","add_on","config","billing_controls","metadata"]},{valuesEqual:JA}={valuesEqual:(t,n)=>JSON.stringify(t)===JSON.stringify(n)},{omitVariantOwnedSettings:fM}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:XA}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(Qt),{isPriceItem:Ca}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(ur,Qt),{isDefaultTrialV2:hM}=(e=>({isDefaultTrialV2:({freeTrial:n,items:r,isDefault:i})=>n?n.card_required===!1&&i&&!e({items:r}):!1}))(XA),{variantSettingsFields:zA}={variantSettingsFields:["description","group","is_add_on","is_default","config","billing_controls","metadata"]},{sortDeep:qh}=(()=>{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:e1}={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:t1}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:n1}={licenseParentTargetKey:({planId:t,version:n})=>`${t}@${n}`},{STRIPE_ZERO_DECIMAL_CURRENCIES:Vh}={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:r1}={STRIPE_THREE_DECIMAL_CURRENCIES:new Set(["bhd","jod","kwd","omr","tnd"])},{currencyInputDecimals:$h}=(e=>({currencyInputDecimals:n=>e.has((n??"usd").toLowerCase())?0:2}))(Vh),{entIntervalToValue:i1}=((e,t)=>({entIntervalToValue:(r,i)=>{if(!r)return new e(1e7);let a={[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(a).mul(i??1)}}))(tn,$r),{intervalToValue:o1}=(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)}))(vn),{normalizeIncludedUsage:Gh}={normalizeIncludedUsage:t=>t??0},{rolloversAreSame:Kh}={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:a1}=((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)}))(Zr,Gi),{itemToExplicitAllocatedBillingBehavior:s1}=((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)}))(ur,qn),{additionalCurrenciesAreSame:Jc}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let o=(c,u)=>c.currency.localeCompare(u.currency),a=[...r].sort(o),s=[...i].sort(o);return a.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:c1}={itemPricingTiers:t=>t.tiers?.length?t.tiers:t.price!=null?[{amount:t.price,to:"inf"}]:null},{priceItemsAreSame:u1}=((e,t,n)=>({priceItemsAreSame:({item1:i,item2:o,logDifferences:a=!1})=>{let s=i.price===o.price&&e({item:i})==e({item:o})&&t({item:i})==t({item:o})&&n(i.additional_currencies,o.additional_currencies);return!s&&a&&console.log(`Price items different: ${i.price}`),s}}))(Vn,Yr,Jc),{calculateProrationAmount:l1}=(e=>({calculateProrationAmount:({periodEnd:n,periodStart:r,now:i,amount:o,allowNegative:a=!1})=>{let s=new e(n).minus(i),c=new e(n).minus(r),u=s.div(c).mul(o);return u.lte(0)&&!a?0:u.toNumber()}}))(tn),{getResetUsage:d1}=((e,t,n,r)=>({getResetUsage:({item:o,feature:a})=>{if(o.feature_id)return e(o.reset_usage_when_enabled)&&(t(o)||n(o))&&a?a?.config?.usage_type===r.Single:o.reset_usage_when_enabled}}))(Qt,wa,Jr,Ln),{compareDetails:p1}={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(o=>o.condition)}},{compareConfig:m1}={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(o=>o.condition)}},{normalizeBillingControlsForCompare:f1}=(e=>({normalizeBillingControlsForCompare:n=>{if(!n)return;let r=n.spend_limits?.map(o=>{if(o.skip_overage_billing===!0)return o;let{skip_overage_billing:a,...s}=o;return s}),i=Object.fromEntries(e.flatMap(o=>{let a=o==="spend_limits"?r:n[o];return a==null||a.length===0?[]:[[o,a]]}));return Object.keys(i).length>0?i:void 0}}))(ya),{sortControls:h1}={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:g1}={compareMetadata:({newMetadata:t,curMetadata:n})=>{let r=i=>JSON.stringify(i??{},(o,a)=>a&&typeof a=="object"&&!Array.isArray(a)?Object.keys(a).sort().reduce((s,c)=>(s[c]=a[c],s),{}):a);return r(t)===r(n)}},{freeTrialsAreSame:b1}={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(o=>o.condition)}},{prodOptionsAreSame:_1}={prodOptionsAreSame:({curProduct:t,newProduct:n})=>t.is_default===n.is_default&&t.is_add_on===n.is_add_on},{PurchaseLimitIntervalEnum:y1}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(Ie,NI),{entToItemInterval:Hh}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))($r),{billingToItemInterval:Wh}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(vn),{isContUseFeature:Qh}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(Ln),{getBillingType:Xc}=((e,t,n,r)=>({getBillingType:o=>{if(o.type===e.Fixed&&o.interval===t.OneOff)return n.OneOff;if(o.type===e.Fixed)return n.FixedCycle;let a=o;return a.bill_when===r.InAdvance||a.bill_when===r.StartOfPeriod?n.UsageInAdvance:a.bill_when===r.EndOfPeriod&&a.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Gr,vn,Kr,$i),{isAllocatedPrice:Zh}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(Xc,Kr),{priceToEnt:zc}=(e=>{function t({price:n,entitlements:r,errorOnNotFound:i}){let o=r.filter(s=>s.id===n.entitlement_id),a=o.find(s=>s.internal_product_id===n.internal_product_id)??o[0];if(!a&&i)throw new e({message:`Entitlement not found for price ${n.id}`});return a}return{priceToEnt:t}})(MI),{isBooleanFeatureItem:Yh}=((e,t)=>({isBooleanFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)&&t(r.interval)&&t(r.included_usage)}))(Qr,Wr),{constructBooleanFeature:S1}=((e,t,n)=>({constructBooleanFeature:({featureId:i,orgId:o,env:a,name:s})=>({internal_id:e("fe"),org_id:o,env:a,created_at:Date.now(),id:i,name:s||t(i),type:n.Boolean,config:null,archived:!1,event_names:[],model_markups:null})}))(Vr,Ph,vt),{constructMeteredFeature:v1}=((e,t,n,r)=>({constructMeteredFeature:({featureId:o,name:a,orgId:s,env:c,usageType:u,eventNames:l=[]})=>({internal_id:e("fe"),org_id:s,env:c,created_at:Date.now(),id:o,name:a||t(o),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})}))(Vr,Ph,vt,LI),{ApiFeatureV0Schema:x1}=((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."})})}))(Ie,VI),{CURRENCY_CODES:I1}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Oh,$I,GI),{RolloverConfigSchema:A1}=((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()})}))(Ie,Gc),{EntitlementExpirySchema:w1}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(Ie,KI),{CreditDimensionNameSchema:C1}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ie,HI,WI),{CreditDimensionBaseSchema:P1}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(Ie,Rh),{graduatedCreditRateShape:Jh}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(Ie,QI),{ProviderMarkupsSchema:O1}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ie,kh),{isAnyCreditSystem:E1}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(vt,Hc),{findCreditTierViolations:T1}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(JI),{findAmbiguousCreditDimensions:R1}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),o=[];for(let[a,[s,c]]of i.entries())for(let[u,l]of i.slice(a+1))e(c,l)&&t(c.match,l.match)&&o.push({names:[s,u],example:{...c.match,...l.match}});return o}}))(XI,Dh),{validateMultipliersKeepRatesNonNegative:j1}=((e,t)=>({validateMultipliersKeepRatesNonNegative:({schemaItem:r,invalidCreditSystem:i})=>{let o=Object.values(r.multipliers??{}),a=[r,...Object.values(r.dimensions??{})],s=Math.min(...a.map(e));t({multipliers:o,cheapestRate:s}).lt(0)&&i(`Multipliers on ${r.metered_feature_id} can take a rate below zero.`)}}))(tA,nA),{buildFixedPriceCurrencies:k1}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:o}of n)r[e(i)]={amount:o};return r}}))(Nh),{PriceCurrencyConfigSchema:Xh}=((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()})}))(Ie,Qc),{baseCurrenciesAreCompatible:D1}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:o})=>(n??null)===(r??null)||e(i)!==e(o)}))(sA),{tiersAreSame:zh}=(e=>({tiersAreSame:(n,r)=>{if(n.length!==r.length)return!1;let i=e(n),o=e(r);return i.every((a,s)=>{let c=o[s];return a.amount===c?.amount&&a.flat_amount===c.flat_amount&&a.to===c.to})}}))(cA),{UsagePriceConfigSchema:N1}=((e,t,n,r,i,o)=>({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(o).optional()})}))(Ie,$i,Qc,vn,Xh,qn),{toFeature:F1}=((e,t,n,r,i,o,a)=>({toFeature:({item:c,orgId:u,internalFeatureId:l,internalProductId:d,isCustom:m,newVersion:g,feature:p,curEnt:h})=>{let y=p?.type===e.Boolean,A=t({item:c,feature:p}),S={id:c.entitlement_id||h?.id||n("ent"),org_id:u,created_at:c.created_at||Date.now(),is_custom:m,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:o({item:c}),interval_count:a({item:c}),carry_from_previous:!A,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(m||g)&&(S={...S,id:n("ent"),created_at:Date.now()}),{price:null,ent:S}}}))(vt,Fh,Vr,Vi,Sa,Ia,Aa),{creditDimensionRulesEqual:U1}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(Zc),{markupRecordsAreSame:M1}=(e=>({markupRecordsAreSame:(n,r)=>[...new Set([...Object.keys(n??{}),...Object.keys(r??{})])].every(i=>e.every(o=>(n?.[i]?.[o]??null)===(r?.[i]?.[o]??null)))}))(fA),{itemToUsageType:B1}=((e,t,n)=>({itemToUsageType:({item:i,features:o})=>{let a=e({item:i,features:o});return!a||!a.config?null:a.type===t.Boolean?n.Static:a.type===t.CreditSystem?n.SingleUse:a.config.usage_type}}))(Mh,vt,xn),{itemToUsageType:L1}=((e,t,n)=>({itemToUsageType:({item:i,features:o})=>{let a=e({item:i,features:o});return a?a.type==t.Boolean?n.Static:a.type==t.CreditSystem?n.SingleUse:a.config.usage_type:null}}))(_A,vt,xn),{isPreviewStripeId:q1}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(xA,IA),{findPairedEntitlement:V1}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(zc),{isConsumablePrice:$1}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(Xc,Kr),{validateLicenseLink:gM}=((e,t,n)=>({validateLicenseLink:({parentProduct:i,licenseProduct:o,prepaidOnly:a,licensePlanId:s})=>{if(a!==void 0&&e({prepaidOnly:a}),s&&o.archived)throw new t({message:`License plan ${s} is archived and cannot be linked.`,code:n.InvalidRequest,statusCode:400});if(o.base_internal_product_id)throw new t({message:`A variant cannot be used as a plan license (${s??o.id}).`,code:n.InvalidRequest});if(i&&o.id===i.id)throw new t({message:`A plan cannot be linked as a license to itself (${s??o.id}).`,code:n.InvalidRequest,statusCode:400})}}))(EA,Rt,Bt),{evaluateCatalogItemIdentity:G1}=(e=>({evaluateCatalogItemIdentity:({item:n,recipe:r=e})=>{let i=[];for(let o of r.components){let a;for(let c of o.paths){a=n;for(let u of c.split("."))a=a!==null&&typeof a=="object"?a[u]:void 0;if(a!=null)break}let s=o.defaultWhen&&i[o.defaultWhen.component]?o.defaultWhen.value:o.default;if(a!=null&&typeof a!="string"&&typeof a!="number")throw new Error("Catalog identity components must be strings or numbers");i.push(a??s)}return i}}))(RA),{removeItems:K1}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(o=>e({item:i,filter:o})))}))(kA),{toApiPlanItem:H1}=((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)})}))(NA,FA),{applyLicenses:W1}=(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)),o=new Map((r.upsert_licenses??[]).map(s=>[s.license_plan_id,s])),a=[];for(let s of n.licenses??[]){if(i.has(s.license_plan_id))continue;let c=o.get(s.license_plan_id);if(c){a.push(e({existing:s,upsert:c})),o.delete(s.license_plan_id);continue}a.push(s)}for(let s of r.upsert_licenses??[])o.has(s.license_plan_id)&&a.push(e({upsert:s}));return a}}))(MA),{pricesEqual:eg}=(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)}))(Yc),{itemPricesEqual:Q1}=((e,t,n)=>({itemPricesEqual:(i,o)=>{if(i==null&&o==null)return!0;if(i==null||o==null)return!1;let a=i.tiers?.length?i.tier_behavior??e.Graduated:null,s=o.tiers?.length?o.tier_behavior??e.Graduated:null;return(i.amount??null)===(o.amount??null)&&t(i.additional_currencies,o.additional_currencies)&&n(i.tiers,o.tiers)&&a===s&&i.interval===o.interval&&(i.interval_count??1)===(o.interval_count??1)&&(i.billing_units??1)===(o.billing_units??1)&&i.billing_method===o.billing_method&&(i.max_purchase??null)===(o.max_purchase??null)}}))(va,Yc,LA),{featureOverridesEqual:Z1}=((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??{})}))($A,Zc),{freeTrialsEqual:Y1}=(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")}))(HA),{planItemFiltersEqual:J1}=(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)}))(QA),{toUpsertLicense:X1}=(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}:{}})}))(Lh),{getVariantSettingsPatch:bM}=((e,t)=>({getVariantSettingsPatch:({from:r,to:i})=>{let o={};for(let a of e)t(r[a],i[a])||(o[a]=i[a]);return o}}))(YA,JA),{isOneOffProductV2:_M}=((e,t,n,r)=>({isOneOffProductV2:({items:o})=>{let a=o.filter(s=>e(s)||t(s));return a.length>0&&a.every(s=>n({item:s})===r.OneOff)}}))(Ca,Jr,Vn,vn),{canonicalizeBillingControls:z1}=(e=>({canonicalizeBillingControls:n=>{let r=n??{},i={};for(let o of Object.keys(r)){let a=r[o];Array.isArray(a)&&a.length===0||(i[o]=Array.isArray(a)?[...a].sort((s,c)=>String(s?.feature_id??"").localeCompare(String(c?.feature_id??""))):a)}return JSON.stringify(e(i))}}))(qh),{ProductConfigSchema:ew}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(Ie,e1),{shouldApplyVariantUpdates:yM}=(e=>({shouldApplyVariantUpdates:({oldBase:n,latestBase:r,propagateToVariants:i,variantUpdates:o,updates:a})=>i.length>0||o.length>0||n.internal_id!==r.internal_id?!0:e.some(s=>a[s]!==void 0)}))(t1),{resolveLicenseParentTargets:SM}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:o,childPlanId:a})=>{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 o){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 m=s.get(d);if(!m)throw new t({message:`Plan ${l.plan_id} v${l.version} does not offer ${a} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),u.push(m)}return u}}))(n1,Rt,Bt),{stripeMinorUnitFactor:Pa}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(Vh,r1),{entIntervalsSame:tw}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),o=e(r.interval,r.intervalCount);return i.eq(o)}}))(i1),{intervalsDifferent:nw}=((e,t)=>({intervalsDifferent:({intervalA:r,intervalB:i})=>{if(e(r)&&e(i))return!1;if(e(r)||e(i))return!0;let o=t(r.interval,r.intervalCount),a=t(i.interval,i.intervalCount);return o!==a}}))(Qt,o1),{allocatedBillingBehaviorAreSame:rw}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),o=e(r);return i===o}}))(s1),{tiersAreSame:iw}=(e=>({tiersAreSame:(n,r)=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every((i,o)=>i.amount===r[o].amount&&i.to===r[o].to&&(i.flat_amount??null)===(r[o].flat_amount??null)&&e(i.additional_currencies,r[o].additional_currencies))}))(Jc),{itemToPriceOrTiers:ow}=(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(o=>({...o,amount:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:o.amount}):o.amount}))}:{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.tiers[0].amount}):n.tiers[0].amount,tiers:void 0}}}))(l1),{normalizeBillingControls:aw}=((e,t,n)=>({normalizeBillingControls:i=>{let o=e(i);return JSON.stringify(t.flatMap(a=>{let s=o?.[a];return s?.length?[[a,n(s)]]:[]}))}}))(f1,ya,h1),{AutoTopupPurchaseLimitSchema:sw}=((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."})})}))(Ie,y1),{toFeatureItem:cw}=((e,t,n,r)=>({toFeatureItem:({ent:o})=>{if(o.feature.type===e.Boolean)return{feature_id:o.feature.id,entity_feature_id:o.entity_feature_id,entitlement_id:o.id};let a=o.rollover||o.feature_override?{rollover:o.rollover??void 0,feature_override:o.feature_override??void 0}:void 0;return{feature_id:o.feature.id,included_usage:o.allowance_type===t.Unlimited?n:o.allowance,interval:r({entInterval:o.interval}),interval_count:o.interval_count??1,entity_feature_id:o.entity_feature_id,pooled:o.pooled??!1,reset_usage_when_enabled:!o.carry_from_previous,config:a,entitlement_id:o.id,created_at:o.created_at}}}))(vt,Sa,Vi,Hh),{toPriceItem:uw}=((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}}}))(Wh,FI),{isPayPerUsePrice:tg}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(Xc,Kr),{createFeaturesFromItems:lw}=((e,t,n,r,i,o,a,s,c,u)=>({createFeaturesFromItems:({items:d,curFeatures:m,orgId:g,env:p})=>{let h=[];for(let y of d){if(!y.feature_id)continue;let A=m.find(S=>S.id===y.feature_id);if(A){if(e(y.feature_type))continue;if(y.feature_type===t.Static){if(y.feature_type===t.Static&&A.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!==A.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(o(y.feature_id),a(y)){let S=s({featureId:y.feature_id,orgId:g,env:p});h.push(S)}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 S=c({featureId:y.feature_id,orgId:g,env:p,usageType:y.feature_type===t.ContinuousUse?u.Continuous:u.Single});h.push(S)}}return{allFeatures:[...m,...h],newFeatures:h}}}))(Wr,xn,vt,Rt,Bt,BI,Yh,S1,v1,Ln),{SUPPORTED_SET:dw}=(e=>({SUPPORTED_SET:new Set(e)}))(I1),{CreditDimensionSchema:pw}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(Ie,P1,jh,Jh),{FeatureMarkupsOverrideSchema:mw}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(Ie,O1,YI),{validateCreditRate:ng}=(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 o=n.tiers??[];for(let s of o){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[a]=e(o.map(s=>s.to));a&&r(a.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}}))(T1),{validateDimensionsAreSeparable:fw}=((e,t)=>({validateDimensionsAreSeparable:({dimensions:r,invalidCreditSystem:i})=>{let[o]=e(r);if(!o)return;let[a,s]=o.names;i(`Dimensions "${a}" and "${s}" can both match the same event (${t(o.example)}). Give one more match keys or a priority.`)}}))(R1,zI),{validateCreditMultipliers:hw}=((e,t)=>({validateCreditMultipliers:({schemaItem:r,invalidCreditSystem:i})=>{for(let[o,a]of Object.entries(r.multipliers??{}))e({name:o,multiplier:a,invalidCreditSystem:i});t({schemaItem:r,invalidCreditSystem:i})}}))(eA,j1),{FixedPriceConfigSchema:gw}=((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})}))(Ie,vn,Xh,Qc,aA),{currenciesAreCompatible:bw}=(e=>({currenciesAreCompatible:(n,r)=>{let i=n??{},o=r??{};for(let a of Object.keys(i)){let s=o[a];if(!s)continue;let c=i[a];if((c?.amount??null)!==(s.amount??null)||!e(c?.usage_tiers??[],s.usage_tiers??[]))return!1}return!0}}))(zh),{creditSchemaItemsAreSame:_w}=(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,o)=>i.to===r.tiers?.[o]?.to&&i.credit_amount==r.tiers?.[o]?.credit_amount)}))(U1),{markupOverridesAreSame:yw}=(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)}))(M1),{resolveAllocatedBillingBehavior:Sw}=((e,t,n,r)=>({resolveAllocatedBillingBehavior:({item:o,curPrice:a})=>{if(e(o.config?.allocated_billing_behavior))return o.config.allocated_billing_behavior;if(e(o.config?.on_increase)||e(o.config?.on_decrease))return t.Prorated;if(a&&n({price:a})){let c=a.config;return e(c.allocated_billing_behavior)?c.allocated_billing_behavior:r(a)?t.Prorated:t.Arrear}return t.Arrear}}))(ur,qn,tg,Zh),{itemCanBeProrated:vw}=((e,t,n)=>({itemCanBeProrated:({item:i,features:o})=>{let a=e({item:i,features:o});return a===t.SingleUse&&i.usage_model===n.Prepaid?!0:a===t.ContinuousUse}}))(L1,xn,Hr),{priceHasPreviewStripeId:xw}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(o=>t({stripeId:i[o]}))}}))(vA,q1),{buildPlanItemKey:Iw}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let o=t({item:r});return i===e.FeatureCadence&&o.splice(1,1),o.join("|")}}))(TA,G1),{itemsEqual:rg}=((e,t,n,r)=>({itemsEqual:(o,a)=>o.feature_id===a.feature_id&&(o.entity_feature_id??null)===(a.entity_feature_id??null)&&(o.pooled??!1)===(a.pooled??!1)&&(o.included??0)===(a.included??0)&&(o.unlimited??!1)===(a.unlimited??!1)&&(o.reset?.interval??null)===(a.reset?.interval??null)&&(o.reset?.interval_count??1)===(a.reset?.interval_count??1)&&e(o.price,a.price)&&t(o.rollover,a.rollover)&&n(o.proration,a.proration)&&r(o.feature_override,a.feature_override)}))(Q1,qA,VA,Z1),{licenseCustomizesAreSame:Aw}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:o,right:a})=>{let s=o??{},c=a??{},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)}}))(eg,WA,rg,J1),{normalizeVariantSettingValue:ww}=((e,t,n)=>({normalizeVariantSettingValue:({field:i,value:o})=>{if(i==="group")return o||"";if(i==="description")return o||null;if(i==="billing_controls")return e(o);if(i==="config"){let a=t.safeParse(o??{});return JSON.stringify(n(a.success?a.data:o??{}))}return i==="metadata"?JSON.stringify(n(o??{})):o}}))(z1,ew,qh),{intervalsSame:Cw}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(nw),{sanitizeItems:Pw}=((e,t,n,r)=>({sanitizeItems:({items:o,features:a})=>o.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:a.find(l=>l.id===s.feature_id)}),...c};return u.config||(u.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),u})}))(ow,d1,Zr,Gi),{compareBillingControls:Ow}=(e=>({compareBillingControls:({newBillingControls:n,curBillingControls:r})=>e(n)===e(r)}))(aw),{AutoTopupSchema:Ew}=((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."})})}))(Ie,sw),{toFeaturePriceItem:Tw}=((e,t,n,r,i,o,a,s,c,u,l)=>({toFeaturePriceItem:({ent:m,price:g})=>{let p=g.config,h=e(p.currencies,p.usage_tiers.length),y=p.usage_tiers.map((j,I)=>({amount:j.amount,to:j.to===-1?t:j.to,flat_amount:j.flat_amount,...h?.[I]?.length?{additional_currencies:h[I]}:{}})),A={};return g.proration_config&&(A={...g.proration_config}),n({feature:m.feature})&&r({price:g})&&(A.allocated_billing_behavior=p.allocated_billing_behavior??(i(g)?o.Prorated:o.Arrear)),m.rollover&&(A.rollover=m.rollover),m.expiry_duration&&m.expiry_length!=null&&(A.expiry={duration:m.expiry_duration,length:m.expiry_length}),m.feature_override&&(A.feature_override=m.feature_override),p.threshold_billing&&(A.threshold_billing=p.threshold_billing),{feature_id:m.feature.id,feature_type:m.feature.config?.usage_type||a.SingleUse,included_usage:m.allowance,interval:s({entInterval:m.interval}),interval_count:m.interval_count??1,price_interval:c({billingInterval:p.interval}),price_interval_count:p.interval_count??1,price:null,tiers:y,base_currency:p.base_currency??void 0,billing_units:p.billing_units,tier_behavior:g.tier_behavior??null,entity_feature_id:m.entity_feature_id,pooled:m.pooled??!1,reset_usage_when_enabled:!m.carry_from_previous,usage_model:p.bill_when===u.StartOfPeriod||p.bill_when===u.InAdvance?l.Prepaid:l.PayPerUse,created_at:m.created_at,entitlement_id:m.id,price_id:g.id,price_config:g.config,config:Object.keys(A).length>0?A:void 0,usage_limit:m.usage_limit}}}))(UI,Vc,Qh,tg,Zh,qn,xn,Hh,Wh,$i,Hr),{isValidCurrencyCode:eu}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(dw),{CreditSchemaItemBaseSchema:ig}=((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()})}))(Ie,C1,pw,ZI),{GraduatedCreditSchemaItemSchema:Rw}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(ig,Jh),{validateCreditDimensionRules:jw}=((e,t,n)=>({validateCreditDimensionRules:({schemaItem:i,invalidCreditSystem:o})=>{let a=i.dimensions??{};for(let[s,c]of Object.entries(a))c.priority!==void 0&&!Number.isInteger(c.priority)&&o(`Dimension "${s}" priority must be an integer.`),e({rate:c,invalidCreditSystem:o});t({dimensions:a,invalidCreditSystem:o}),n({schemaItem:i,invalidCreditSystem:o})}}))(ng,fw,hw),{pricesAreSame:Oa}=((e,t,n,r,i,o,a,s)=>({pricesAreSame:(u,l,d=!1)=>{let m=u.config,g=l.config;if(m.type!==g.type)return!1;if(m.type===e.Fixed){let I=t.parse(m),v=t.parse(g),$={amount:I.amount!==v.amount,interval:I.interval!==v.interval,intervalCount:(I.interval_count??1)!==(v.interval_count??1),baseCurrency:!n({base1:I.base_currency,base2:v.base_currency,currencies1:I.currencies,currencies2:v.currencies}),currencies:!r(I.currencies,v.currencies)};return!Object.values($).some(Boolean)}let p=i.parse(m),h=i.parse(g),y={shouldProrate:(p.should_prorate??!1)!==(h.should_prorate??!1),allocatedBillingBehavior:o(p)!==o(h),billWhen:p.bill_when!==h.bill_when,billingUnits:(p.billing_units??1)!==(h.billing_units??1),thresholdBilling:p.threshold_billing?.threshold!==h.threshold_billing?.threshold,interval:p.interval!==h.interval,intervalCount:(p.interval_count??1)!==(h.interval_count??1),internalFeatureId:p.internal_feature_id!==h.internal_feature_id,featureId:p.feature_id!==h.feature_id,usageTiers:!a(p.usage_tiers,h.usage_tiers),baseCurrency:!n({base1:p.base_currency,base2:h.base_currency,currencies1:p.currencies,currencies2:h.currencies}),currencies:!r(p.currencies,h.currencies)},A=p.usage_tiers.length<=1&&h.usage_tiers.length<=1,S={onIncrease:u.proration_config?.on_increase!=l.proration_config?.on_increase,onDecrease:u.proration_config?.on_decrease!=l.proration_config?.on_decrease,tierBehavior:!A&&(u.tier_behavior??s.Graduated)!==(l.tier_behavior??s.Graduated)},j=Object.values(y).some(Boolean)||Object.values(S).some(Boolean);return j&&d&&console.log("Prices are different",{configDiffs:y,prorationDiffs:S}),!j}}))(Gr,gw,D1,bw,N1,uA,zh,va),{creditSchemasAreSame:kw}=(e=>({creditSchemasAreSame:({schema1:n,schema2:r})=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every(i=>{let o=r.find(a=>a.metered_feature_id===i.metered_feature_id);return o?e({left:i,right:o}):!1})}))(_w),{itemToAllocatedBillingBehavior:Dw}=((e,t,n,r,i,o,a,s,c)=>({itemToAllocatedBillingBehavior:({item:l,features:d,curPrice:m})=>{if(!(e({item:l,features:d})===t.ContinuousUse&&n(l)&&l.usage_model!==r.Prepaid))return null;let h=i({item:l,curPrice:m});if(h===o.Arrear){if(a(l.config?.on_increase)||a(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(a(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}}))(B1,xn,Jr,Hr,Sw,qn,ur,Rt,gA),{composeMatchKey:Ki}=(e=>({composeMatchKey:n=>e({item:n})}))(Iw),{applyItems:Nw}=((e,t,n,r)=>({applyItems:(o,a)=>{let s=[...o];if(a.remove_items&&(s=e(s,a.remove_items)),a.add_items){let c=new Set;for(let u of s)t(u)&&c.add(n(u));for(let u of a.add_items){let l=n(u);t(u)&&c.has(l)||(s.push(r(u)),t(u)&&c.add(l))}}return s}}))(K1,DA,Ki,H1),{dedupeItemsByMatchKey:Fw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Ki),{planLicensesAreSame:Uw}=(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)}}))(Aw),{dedupeItemsByMatchKey:Mw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Ki),{validateVariantSettingsUpdate:vM}=((e,t,n,r)=>({validateVariantSettingsUpdate:({allowVariantSettingsUpdate:o,fullProduct:a,currentProduct:s,updates:c})=>{if(o||a.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})}}))(zA,ww,Rt,Bt),{findSimilarItem:tu}=((e,t,n,r,i,o,a,s,c)=>({findSimilarItem:({item:l,items:d})=>e(l)?d.find(m=>e(m)&&m.feature_id===l.feature_id&&m.entity_feature_id==l.entity_feature_id&&t({intervalA:{interval:n({item:m}),intervalCount:r({item:m})},intervalB:{interval:n({item:l}),intervalCount:r({item:l})}})):i(l)?d.find(m=>i(m)&&m.feature_id===l.feature_id&&m.entity_feature_id==l.entity_feature_id&&o({intervalA:{interval:a({item:m}),intervalCount:s({item:m})},intervalB:{interval:a({item:l}),intervalCount:s({item:l})}})&&l.usage_model==m.usage_model):c(l)?d.find(m=>c(m)&&m.price==l.price&&a({item:m})==a({item:l})&&s({item:m})==s({item:l})):null}))(wa,tw,Ia,Aa,Jr,Cw,Vn,Yr,Ca),{stripAutoTopupCountsForStorage:Bw}=(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}))}))(Ew),{toProductItem:og}=((e,t,n,r)=>({toProductItem:({ent:o,price:a})=>e(a)?t({ent:o}):e(o)?n({price:a}):r({ent:o,price:a})}))(Qt,cw,uw,Tw),{CurrencyCodeSchema:ag}=((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')."})}))(Ie,eu),{AdditionalCurrencyPriceSchema:Lw}=((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."})})}))(Ie,ag),{FlatCreditSchemaItemSchema:qw}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(ig,jh),{validateCreditSystem:Vw}=((e,t,n,r,i,o,a,s)=>({validateCreditSystem:(u,l=e.CreditSystem)=>{let d=Array.isArray(u?.schema)?u.schema:[],m=S=>{throw new t({message:S,code:n.InvalidFeature,statusCode:r.BAD_REQUEST})};!i(l)&&d.length===0&&m("At least one metered feature is required for credit system"),i(l)&&d.length>0&&m("AI credit systems are leaf features and cannot define a schema. Model rates live in model_markups.");let g=d.map(S=>S.metered_feature_id),p=Array.from(new Set(g));g.length!==p.length&&m("Credit system contains multiple of the same metered_feature_id");let h={...u,schema:d,usage_type:o.Single},y=h.default_markup;if(y!=null){let S=Number(y);if(Number.isNaN(S)||S<-100)throw new t({message:"Default markup must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});h.default_markup=S}let A=h.provider_markups;if(A!=null)for(let[S,j]of Object.entries(A)){let I=Number(j?.markup);if(!S||Number.isNaN(I)||I<-100)throw new t({message:"Provider markups must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});j.markup=I}for(let S of h.schema){if(S.feature_amount!==void 0){let j=Number(S.feature_amount);(!Number.isFinite(j)||j<=0)&&m("Billing units must be greater than zero."),S.feature_amount=j}a({rate:S,invalidCreditSystem:m}),s({schemaItem:S,invalidCreditSystem:m})}return h}}))(vt,Rt,Bt,Bn,Hc,Ln,ng,jw),{stripePriceIdForInitializedPrice:sg}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:o,newPrice:a})=>{if(!e(i)&&(!o||i!==t({price:o})||n(o,a)))return i}}))(Qt,oA,Oa),{featureOverridesAreSame:nu}=((e,t)=>({featureOverridesAreSame:({override1:r,override2:i})=>e({schema1:r?.schema,schema2:i?.schema})&&t({markups1:r?.markups,markups2:i?.markups})}))(kw,yw),{applyDiff:cg}=((e,t,n,r)=>({applyDiff:({base:o,diff:a})=>{let s={price:e(o.price,a.price),items:t(o.items,a),free_trial:n(o.free_trial,a.free_trial)},c=r({base:o,diff:a});return c===void 0?s:{...s,licenses:c}}}))(jA,Nw,UA,W1),{diffPlanLicenses:$w}=((e,t,n,r)=>({diffPlanLicenses:({from:o,to:a,includeAdds:s=!1,includeRemoves:c=!1})=>{let u=new Map((o??[]).map(g=>[g.license_plan_id,g])),l=new Map((a??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of l.values()){let p=u.get(g.license_plan_id);!p&&!s||p&&e({left:p,right:g})||d.push(t({license:g,clearCustomize:p!=null&&n(p.customize)&&!n(g.customize)}))}let m=c?[...u.keys()].filter(g=>!l.has(g)).map(g=>({license_plan_id:g})):[];return{...d.length>0?{upsert_licenses:d.sort(r)}:{},...m.length>0?{remove_licenses:m.sort(r)}:{}}}}))(Uw,X1,Lh,ZA),{applyDiffToVariantPlan:xM}=((e,t)=>({applyDiffToVariantPlan:({plan:r,diff:i,settingsPatch:o={}})=>{let a=e({base:r,diff:i});return{...r,...a,...o,items:t(a.items)}}}))(cg,Mw),{mapToProductItems:ug}=((e,t,n,r)=>({mapToProductItems:({prices:o,entitlements:a,features:s})=>{let c=[];o??=[],a??=[];for(let u of a){let l=e({ent:u,prices:o}),d=t({ent:u,price:l});c.push(d)}for(let u of o)n({price:u,entitlements:a})||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}}))(Ah,og,zc,wh),{featureItemsAreSame:Gw}=((e,t,n)=>({featureItemsAreSame:({item1:i,item2:o,logDifferences:a=!1})=>{let s={feature_id:{condition:i.feature_id===o.feature_id,message:`Feature ID different: ${i.feature_id} != ${o.feature_id}`},included_usage:{condition:e(i.included_usage)==e(o.included_usage),message:`Included usage different: ${i.included_usage} != ${o.included_usage}`},interval:{condition:i.interval==o.interval,message:`Interval different: ${i.interval} != ${o.interval}`},interval_count:{condition:(i.interval_count||1)==(o.interval_count||1),message:`Interval count different: ${i.interval_count} != ${o.interval_count}`},entity_feature_id:{condition:i.entity_feature_id==o.entity_feature_id,message:`Entity feature ID different: ${i.entity_feature_id} != ${o.entity_feature_id}`},pooled:{condition:(i.pooled??!1)===(o.pooled??!1),message:`Pooled different: ${i.pooled} != ${o.pooled}`},reset_usage_when_enabled:{condition:(i.reset_usage_when_enabled??!1)===(o.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${i.reset_usage_when_enabled} !== ${o.reset_usage_when_enabled}`},rollover_config:{condition:t({rollover1:i.config?.rollover||void 0,rollover2:o.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(i.config?.rollover)} !== ${JSON.stringify(o.config?.rollover)}`},feature_override:{condition:n({override1:i.config?.feature_override,override2:o.config?.feature_override}),message:`Feature override different: ${JSON.stringify(i.config?.feature_override)} !== ${JSON.stringify(o.config?.feature_override)}`},threshold_billing:{condition:(i.config?.threshold_billing?.threshold??null)===(o.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(i.config?.threshold_billing)} !== ${JSON.stringify(o.config?.threshold_billing)}`}},c=Object.values(s).every(u=>u.condition);return!c&&a&&console.log("Feature items different:",Object.values(s).filter(u=>!u.condition).map(u=>u.message)),c}}))(Gh,Kh,nu),{featurePriceItemsAreSame:Kw}=((e,t,n,r,i,o,a,s,c,u)=>({featurePriceItemsAreSame:({item1:d,item2:m,logDifferences:g=!1})=>{let p={included_usage:{condition:e(d.included_usage)==e(m.included_usage),message:`Included usage different: ${d.included_usage} != ${m.included_usage}`},usage_limit:{condition:d.usage_limit==m.usage_limit,message:`Usage limit different: ${d.usage_limit} !== ${m.usage_limit}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(m.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${m.reset_usage_when_enabled}`},proration_config:{condition:t({config1:d.config||void 0,config2:m.config||void 0}),message:`Proration config different: ${JSON.stringify(d.config)} !== ${JSON.stringify(m.config)}`},allocated_billing_behavior:{condition:n({item1:d,item2:m}),message:`Allocated billing behavior different: ${d.config?.allocated_billing_behavior} !== ${m.config?.allocated_billing_behavior}`},rollover_config:{condition:r({rollover1:d.config?.rollover||void 0,rollover2:m.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(d.config?.rollover)} !== ${JSON.stringify(m.config?.rollover)}`},feature_override:{condition:i({override1:d.config?.feature_override,override2:m.config?.feature_override}),message:`Feature override different: ${JSON.stringify(d.config?.feature_override)} !== ${JSON.stringify(m.config?.feature_override)}`},threshold_billing:{condition:(d.config?.threshold_billing?.threshold??null)===(m.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(d.config?.threshold_billing)} !== ${JSON.stringify(m.config?.threshold_billing)}`},entity_feature_id:{condition:d.entity_feature_id==m.entity_feature_id,message:`Entity feature ID different: ${d.entity_feature_id} != ${m.entity_feature_id}`},pooled:{condition:(d.pooled??!1)===(m.pooled??!1),message:`Pooled different: ${d.pooled} != ${m.pooled}`}},h={feature_id:{condition:d.feature_id===m.feature_id,message:`Feature ID different: ${d.feature_id} != ${m.feature_id}`},interval:{condition:o({item:d})==o({item:m}),message:`Billing interval different: ${o({item:d})} != ${o({item:m})}`},interval_count:{condition:a({item:d})==a({item:m}),message:`Billing interval count different: ${a({item:d})} != ${a({item:m})}`},usage_model:{condition:d.usage_model===m.usage_model,message:`Usage model different: ${d.usage_model} != ${m.usage_model}`},pricing:{condition:s(c(d),c(m)),message:`Pricing different: ${JSON.stringify(c(d))} != ${JSON.stringify(c(m))}`},additional_currencies:{condition:u(d.additional_currencies,m.additional_currencies),message:"Additional currencies different"},tier_behavior:{condition:(c(d)?.length??0)<=1&&(c(m)?.length??0)<=1?!0:d.tier_behavior==m.tier_behavior,message:`Tiers type different: ${d.tier_behavior} != ${m.tier_behavior}`},billing_units:{condition:d.billing_units==m.billing_units,message:`Billing units different: ${d.billing_units} !== ${m.billing_units}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(m.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${m.reset_usage_when_enabled}`}},y=Object.values(h).every(S=>S.condition)&&Object.values(p).every(S=>S.condition),A=Object.values(h).some(S=>!S.condition);return!y&&g&&console.log("Feature price items different:",Object.values(p).filter(S=>!S.condition).map(S=>S.message),Object.values(h).filter(S=>!S.condition).map(S=>S.message)),{same:y,pricesChanged:A}}}))(Gh,a1,rw,Kh,nu,Vn,Yr,iw,c1,Jc),{pickBillingControlColumns:Hw}=((e,t)=>({pickBillingControlColumns:r=>{if(!r)return{};let i=Object.fromEntries(e.flatMap(o=>r[o]===void 0?[]:[[o,r[o]]]));return i.auto_topups!==void 0&&(i.auto_topups=t(i.auto_topups)),i}}))(ya,Bw),{mapToProductV2:IM}=((e,t,n,r,i)=>({mapToProductV2:({product:a,features:s})=>{let c=[];for(let l of a.entitlements){let d=e({ent:l,prices:a.prices});c.push(t({ent:l,price:d}))}for(let l of a.prices)n({price:l,entitlements:a.entitlements})||c.push(t({price:l}));s||(s=a.entitlements.map(l=>l.feature));for(let l of c)l.feature_type=r({item:l,features:s});return{internal_id:a.internal_id,id:a.id,name:a.name,description:a.description??null,is_add_on:a.is_add_on,is_default:a.is_default,version:a.version,version_slug:a.version_slug??null,active:a.active??!1,group:a.group||null,free_trial:a.free_trial,created_at:a.created_at,env:a.env,items:c,stripe_id:a.processor?.id||null,archived:a.archived||!1,config:a.config??void 0,billing_controls:i(a),metadata:a.metadata??{}}}}))(Ah,og,zc,wh,Ch),{AdditionalCurrencyTierSchema:Ww}=((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"]})}))(Ie,ag),{AdditionalCurrencyPriceArraySchema:Qw}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ie,Lw,Eh,Th),{CreditSchemaItemSchema:Zw}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(Ie,qw,Rw),{validateItemFeatureOverride:Yw}=((e,t,n,r,i,o,a,s,c)=>({validateItemFeatureOverride:({item:l,feature:d,features:m})=>{let g=l.config?.feature_override;if(!g)return;let p=y=>{throw new e({message:`${y} (feature: ${l.feature_id})`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})};if(!(d&&r(d.type))){p("feature_override is only supported on credit system items");return}if(g.schema&&d.type!==i.CreditSystem&&p("feature_override.credit_schema is not supported on AI credit system items"),g.markups&&!o(d.type)&&p("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let h={schema:g.schema,usage_type:a.Single};s(h,d.type),c({config:h,allFeatures:m});for(let y of g.schema)if(!m.find(S=>S.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})}}))(Rt,Bt,Bn,E1,vt,Hc,Ln,Vw,rA),{toPrice:Jw}=((e,t,n,r,i,o,a)=>({toPrice:({item:c,orgId:u,internalProductId:l,isCustom:d,newVersion:m,curPrice:g})=>{let p={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&&(p.currencies=h);let y=c.base_currency??(h?g?.config?.base_currency:void 0);y&&(p.base_currency=y);let A={id:c.price_id||g?.id||o("pr"),created_at:c.created_at||Date.now(),org_id:u,internal_product_id:l,is_custom:d,config:p,proration_config:null};return(d||m)&&(A={...A,id:o("pr"),created_at:Date.now()}),p.stripe_price_id=a({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:A}),{price:A,ent:null}}}))(Gr,Qr,Vn,Yr,k1,Vr,sg),{entsAreSame:ru}=((e,t,n,r,i,o,a)=>({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:!o({override1:c.feature_override,override2:u.feature_override}),expiry:!a(c,u)};return!Object.values(d).some(Boolean)}}))(lA,Uh,dA,pA,mA,nu,hA),{toFeatureAndPrice:Xw}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p,h,y,A,S,j,I,v,$,G,we,Te,ae,V)=>({toFeatureAndPrice:({item:Z,orgId:rt,internalFeatureId:de,internalProductId:ie,isCustom:Lt,curPrice:Ke,curEnt:qt,newVersion:In,features:Zt})=>{let fg=e({item:Z,feature:Zt.find(It=>It.id===Z.feature_id)}),Ra=t({item:Z,features:Zt,curPrice:Ke}),mu=Ra===n.Arrear,lr={id:Z.entitlement_id||qt?.id||r("ent"),org_id:rt,created_at:Z.created_at||Date.now(),is_custom:Lt,internal_product_id:ie,internal_feature_id:de,feature_id:Z.feature_id,allowance:Z.included_usage||0,allowance_type:i.Fixed,interval:o({item:Z}),interval_count:a({item:Z}),carry_from_previous:!fg,entity_feature_id:Z.entity_feature_id,pooled:Z.pooled??!1,usage_limit:Z.usage_limit||null,rollover:Z.config?.rollover,expiry_duration:Z.config?.expiry?.duration,expiry_length:Z.config?.expiry?.length,feature_override:Z.config?.feature_override};(!qt||Lt&&!s(qt,lr)||In)&&(lr={...lr,id:r("ent"),created_at:Date.now()});let hg=o({item:Z}),Xr={type:c.Usage,bill_when:Z.usage_model===u.Prepaid?l.StartOfPeriod:l.EndOfPeriod,billing_units:Z.billing_units||1,...Z.config?.threshold_billing?{threshold_billing:Z.config.threshold_billing}:{},should_prorate:hg===d.Lifetime&&!mu,...Ra?{allocated_billing_behavior:Ra}:{},internal_feature_id:de,feature_id:Z.feature_id,usage_tiers:m(Z.price)?[{amount:Z.price,to:g}]:Z.tiers?.map(It=>({to:It.to,amount:It.amount??0,...It.flat_amount!=null?{flat_amount:It.flat_amount}:{}})),interval:p({item:Z}),interval_count:h({item:Z}),stripe_price_id:void 0},fu=y({baseTiers:Xr.usage_tiers,itemTiers:Z.tiers,flatCurrencies:Z.additional_currencies});fu&&(Xr.currencies=fu,Xr.base_currency=Z.base_currency??Ke?.config?.base_currency??void 0);let gg=A({item:Z,features:Zt})&&!mu,hu=null;if(gg){let It=Z.config?.on_increase||S.ProrateImmediately,$n=Z.config?.on_decrease||j.Prorate;(I($n)||$n===j.Prorate)&&($n=It===S.ProrateImmediately||It===S.BillImmediately?j.ProrateImmediately:j.ProrateNextCycle),hu={on_increase:It,on_decrease:$n}}let fn={id:Z.price_id||Ke?.id||r("pr"),created_at:Z.created_at||Date.now(),org_id:rt,internal_product_id:ie,is_custom:Lt,config:Xr,entitlement_id:lr.id,proration_config:hu,tier_behavior:Z.tier_behavior??null},gu=v(fn.config);if((gu===$.UsageInArrear||gu===$.InArrearProrated)&&fn.config.interval===G.OneOff)throw new we({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${Z.feature_id})`,code:Te.InvalidPrice,statusCode:400});let bg=Ke&&!ae(Ke,fn,!0)||qt&&!s(qt,lr);if(Ke&&(bg||In)){let It=fn.config,$n=Ke.config;It.stripe_meter_id=$n.stripe_meter_id,It.stripe_product_id=$n.stripe_product_id,fn.config=It}return(Lt||In)&&(fn={...fn,id:r("pr"),created_at:Date.now()}),Xr.stripe_price_id=V({requestedStripePriceId:Z.stripe_price_id,currentPrice:Ke,newPrice:fn}),{price:fn,ent:lr}}}))(Fh,Dw,qn,Vr,Sa,Ia,Aa,ru,Gr,Hr,$i,$r,Qr,Vc,Vn,Yr,bA,vw,Zr,Gi,yA,SA,Kr,vn,Rt,Bt,Oa,sg),{getPriceStripeReuseLevel:zw}=((e,t,n,r,i,o)=>({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,m=c.config;if(d.feature_id!==m.feature_id)return"none";let g=r({price:s,entitlements:u}),p=r({price:c,entitlements:l});return!g&&!p?"stripeProductOnly":!g||!p||o(g.entity_feature_id)!==o(p.entity_feature_id)?"none":"stripeProductOnly"}}))(xw,Oa,Gr,V1,ru,AA),{applyLicenseCustomizeToBasePlan:AM}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:o})=>{let a=new Set((o.add_items??[]).map(u=>e(u))),s={...i,items:i.items.filter(u=>!a.has(e(u)))},c=t({base:s,diff:o});return{...s,...c,items:n(c.items)}}}))(Ki,cg,Fw),{diffPlanV1:eC}=((e,t,n,r,i,o,a,s,c)=>({diffPlanV1:({from:l,to:d,includeAdds:m=!1,includeRemoves:g=!1,filterPrecision:p=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(I=>[r(I),I])),A=new Map(d.items.map(I=>[r(I),I])),S=[];for(let I of d.items){let v=y.get(r(I));(!v||!i(v,I))&&S.push(o(I))}S.length>0&&(h.add_items=S);let j=[];for(let I of l.items){let v=A.get(r(I));(!v||!i(I,v))&&j.push(a({item:I,filterPrecision:p}))}if(j.length>0&&(h.remove_items=j),!s(l.free_trial,d.free_trial))if(d.free_trial==null)h.free_trial=null;else{let{on_end:I,...v}=d.free_trial;h.free_trial=I==null?v:{...v,on_end:I}}return Object.assign(h,c({from:l.licenses,to:d.licenses,includeAdds:m,includeRemoves:g})),h}}))(Bh,eg,BA,Ki,rg,GA,KA,Y1,$w),{currentItemsOf:lg}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))(ug),{itemsAreSame:dg}=((e,t,n,r,i,o,a,s)=>({itemsAreSame:({item1:u,item2:l,features:d,logDifferences:m=!1})=>{let g=!1,p=!1;if(e(u)){if(!e(l))return{same:!1,pricesChanged:!0};g=t({item1:u,item2:l,logDifferences:m}),p=!1}if(n(u)){if(!n(l))return{same:!1,pricesChanged:!0};let{same:h,pricesChanged:y}=r({item1:u,item2:l,logDifferences:m});g=h,i({item:u,features:d||[]})?.config?.usage_type===o.Continuous?p=!0:p=y}return a(u)&&(g=s({item1:u,item2:l,logDifferences:m}),g||(p=!0)),{same:g,pricesChanged:!g&&p}}}))(wa,Gw,Jr,Kw,Mh,Ln,Ca,u1),{productsAreSame:wM}=((e,t,n,r,i,o,a,s,c,u,l,d,m)=>({productsAreSame:({newProductV1:p,newProductV2:h,curProductV1:y,curProductV2:A,features:S})=>{if(!p&&!h)throw new Error("productsAreSame error: product1 not provided");if(!y&&!A)throw new Error("productsAreSame error: product2 not provided");let j=h?.items||e({prices:p?.prices||[],entitlements:p?.entitlements||[],features:S}),I=A?.items||e({prices:y?.prices||[],entitlements:y?.entitlements||[],features:S});j=t({items:j,features:S}),I=t({items:I,features:S});let v=!0,$=!1,G=!0,we=!0,Te=!0,ae=[],V=[];G=n({newProductV2:h,curProductV2:A}),we=r({newConfig:h?.config,curConfig:A?.config}),Te=i({newBillingControls:h?.billing_controls??(p?o(p):void 0),curBillingControls:A?.billing_controls??(y?o(y):void 0)});let Fe=a({newMetadata:h?.metadata,curMetadata:A?.metadata});j.length!==I.length&&(v=!1),j.length!==I.length&&(v=!1);for(let Ke of j){let qt=s({item:Ke,items:I});if(!qt){(c(Ke)||u(Ke))&&($=!0),v=!1,ae.push(Ke);continue}let{same:In,pricesChanged:Zt}=l({item1:Ke,item2:qt,features:S,logDifferences:!1});In||(v=!1,ae.push(Ke)),Zt&&($=!0)}for(let Ke of I)s({item:Ke,items:j})||(v=!1,(c(Ke)||u(Ke))&&($=!0),V.push(Ke));let Z=y?.free_trial||A?.free_trial,rt=p?.free_trial||h?.free_trial,de=d({ft1:Z,ft2:rt}),ie=m({curProduct:A||y,newProduct:h||p});return{itemsSame:v,freeTrialsSame:de,onlyEntsChanged:!$,newItems:ae,removedItems:V,detailsSame:G,optionsSame:ie,configSame:we,billingControlsSame:Te,metadataSame:Fe,same:v&&G&&de&&we&&Fe&&Te}}}))(ug,Pw,p1,m1,Ow,Ch,g1,tu,Jr,Ca,dg,b1,_1),{constructProduct:CM}=((e,t)=>({constructProduct:({productData:r,version:i=1,orgId:o,env:a,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:a,internal_id:e("prod"),org_id:o,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??{}})}))(Vr,Hw),{AdditionalCurrencyTierArraySchema:tC}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ie,Ww,Eh,Th),{FeatureConfigOverrideSchema:nC}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(Ie,Zw,mw),{itemToPriceAndEnt:rC}=((e,t,n,r,i,o,a,s,c,u)=>({itemToPriceAndEnt:({item:d,orgId:m,internalProductId:g,feature:p,curPrice:h,curEnt:y,isCustom:A,newVersion:S,features:j})=>{let I=null,v=null,$=null,G=null,we=null,Te=null;if(e(d)){let{price:ae}=t({item:d,orgId:m,internalProductId:g,isCustom:A,newVersion:S,curPrice:h});!h||S?I=ae:n(h,ae,!0)?we=h:$=ae}else if(r(d)){if(!p)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let ae=p?.type===a.Boolean,{ent:V}=s({item:d,orgId:m,internalFeatureId:p.internal_id,internalProductId:g,isCustom:A,newVersion:S,feature:p,curEnt:y});!y||S?v=V:c(y,V)?Te=y:G=V}else{if(!p)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let{price:ae,ent:V}=u({item:d,orgId:m,internalFeatureId:p.internal_id,internalProductId:g,isCustom:A,curPrice:h,curEnt:y,newVersion:S,features:j}),Fe=y&&c(y,V);!h||S?I=ae:!Fe||!n(h,ae,!1)?$=ae:we=h,!y||S?v=V:Fe?Te=y:G=V}return{newPrice:I,newEnt:v,updatedPrice:$,updatedEnt:G,samePrice:we,sameEnt:Te}}}))(Wc,Jw,Oa,xa,Rt,Bt,vt,F1,ru,Xw),{copyStripeResourcesToMatchingPrice:iC}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:a,candidatePrices:s,targetEntitlements:c,candidateEntitlements:u})=>{let l=s.map(A=>({candidatePrice:A,level:e({newPrice:a,candidatePrice:A,newEntitlements:c,candidateEntitlements:u})})),d=l.find(A=>A.level==="full"),g=(d??l.find(A=>A.level==="stripeProductOnly"))?.candidatePrice,p=d?.candidatePrice,h=a.config,y=[];if(g){let A=g.config;for(let S of t)S==="stripe_meter_id"&&(!n(a)||!n(g))||r({fromConfig:A,toConfig:h,field:S})&&y.push(S)}if(p){let A=p.config;for(let S of i)t.includes(S)||r({fromConfig:A,toConfig:h,field:S})&&y.push(S)}return{copiedFields:y}}}))(zw,wA,$1,CA,PA),{getApiPlanDiff:PM}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(eC),{backfillExistingItemIds:oC}=((e,t)=>({backfillExistingItemIds:({items:r,currentFullProduct:i,features:o})=>{let a=e({currentFullProduct:i,features:o});return r.map(s=>{if(s.entitlement_id||s.price_id)return s;let c=t({item:s,items:a});return c?{...s,...c.entitlement_id?{entitlement_id:c.entitlement_id}:{},...c.price_id?{price_id:c.price_id}:{}}:s})}}))(lg,tu),{PriceTierSchema:aC}=((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}))}))(Ie,Vc,tC),{ProductItemConfigSchema:sC}=((e,t,n,r,i,o,a)=>({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:o.nullish(),feature_override:a.nullish()})}))(Ie,qn,Zr,Gi,A1,w1,nC),{carryForwardStripeResources:cC}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:o})=>{for(let a of n)e({targetPrice:a,candidatePrices:i,targetEntitlements:r,candidateEntitlements:o})}}))(iC),{resolveInPlaceEdit:OM}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:o,items:a,currentFullProduct:s,features:c})=>{let u=e({items:a,currentFullProduct:s,features:c}),l=t({currentFullProduct:s,features:c}),d=[],m=[];for(let h of l){let y=n({item:h,items:u}),A=!y,S=y&&!r({item1:y,item2:h,features:c}).same;(A||S)&&(h.entitlement_id&&d.push(h.entitlement_id),h.price_id&&m.push(h.price_id))}let g=new Set([...d,...m]),p=u.map(h=>{let y=h.entitlement_id&&g.has(h.entitlement_id),A=h.price_id&&g.has(h.price_id);return y||A?{...h,entitlement_id:void 0,price_id:void 0}:h});return{retiredEntitlementIds:d,retiredPriceIds:m,items:p,curPrices:s.prices.filter(h=>!g.has(h.id)),curEnts:s.entitlements.filter(h=>!g.has(h.id))}}}))(oC,lg,tu,dg),{ProductItemSchema:uC}=((e,t,n,r,i,o,a,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(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(o).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(a).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(o).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})})}))(Ie,qI,xn,x1,Vi,$c,Hr,aC,Qw,va,sC),{validateProductItem:lC}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p,h,y,A,S,j)=>({validateProductItem:({item:v,features:$,multiCurrencyEnabled:G,validateRollover:we})=>{v=e.parse(v);let Te=$.find(de=>de.id===v.feature_id);if(t(v.feature_id)&&t(v.price)&&t(v.tiers))throw new n({message:"Either 'feature_id', 'price', or both should be set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let ae=v.pooled&&Te?.type===o.Boolean,V=a(v)||s(v.included_usage)&&v.included_usage!==0||s(v.interval)||s(v.config?.rollover);if(ae&&V)throw new n({message:"Pooled boolean items cannot include balance or pricing fields",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(c({item:v,feature:Te,features:$}),a(v)&&v.included_usage===u)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(v.pooled&&a(v)&&v.usage_model===l.PayPerUse)throw new n({message:"Pooled items cannot use usage-based pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(v.price)&&s(v.tiers))throw new n({message:"Either 'price' or 'tiers' should be set, not both",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let Fe=(v.additional_currencies?.length??0)>0||(v.tiers?.some(de=>(de.additional_currencies?.length??0)>0)??!1);if(Fe&&!G)throw new n({message:"Multi-currency is not enabled for this organization",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(Fe&&t(v.base_currency))throw new n({message:"'base_currency' is required when 'additional_currencies' are set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if((v.additional_currencies?.length??0)>0){if(s(v.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(v.price)&&v.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(v)&&v.price&&v.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(a(v)||m(v)){if(typeof v.included_usage!="number"&&v.included_usage!==u&&s(v.included_usage))throw new n({message:`Included usage for feature ${v.feature_id} must be a number or '${u}'`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(t(v.included_usage)&&(v.included_usage=0),typeof v.included_usage=="number"&&v.included_usage<0)throw new n({message:"Included usage must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(a(v)||d(v)){let de=g({item:v});if(String(de)===p.Day||String(de)===p.Minute||String(de)===p.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(a(v)&&t(v.usage_model))throw new n({message:`Usage model is required for priced features. Please select one for the feature ${v.feature_id}`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(a(v)&&v.tiers){if(v.included_usage===u)throw new n({message:`Included usage can't be '${u}' for tiered prices`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.billing_units&&v.billing_units<=0)throw new n({message:"Billing units must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.tier_behavior===h.VolumeBased&&v.tiers.length>1&&v.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(v.tiers.some(ie=>ie.flat_amount!=null&&ie.flat_amount>0)){if(v.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(v.tiers.length<=1)throw new n({message:"flat_amount is not supported on single-tier pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(v.tiers.some(ie=>ie.flat_amount!=null&&ie.flat_amount<0))throw new n({message:"flat_amount must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(v.usage_model===l.Prepaid&&v.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(v.config?.expiry&&Te&&(Te.type===o.Boolean||A({feature:Te})))throw new n({message:`expiry is only supported on consumable features (feature: ${v.feature_id})`,code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(!v.config?.rollover)return;let Z=v.config.rollover;if(Z.duration===S.Forever&&(Z.length=0),!we)return;if(v.included_usage===u)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let rt=j({rollover:Z});if(rt)throw new n({message:rt,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(Z.duration===S.Month&&(typeof Z.length!="number"||Z.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(v.usage_limit)&&v.usage_limit<=0)throw new n({message:"Usage limit must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}}))(uC,Qt,Rt,Bt,Bn,vt,Kc,ur,Yw,Vi,Hr,Wc,xa,Vn,$c,va,Zr,Qh,Gc,iA),{validateProductItems:dC}=((e,t,n,r,i,o,a,s,c,u,l,d,m,g,p)=>({validateProductItems:({newItems:y,features:A,orgId:S,env:j,multiCurrencyEnabled:I,validateRollover:v=!0})=>{let{allFeatures:$,newFeatures:G}=e({items:y,curFeatures:A,orgId:S,env:j});A=$;for(let ae=0;ae<y.length;ae++){t({item:y[ae],features:A,multiCurrencyEnabled:I,validateRollover:v});let V=A.find(Fe=>Fe.id===y[ae].feature_id);V&&V.type===n.Metered&&(y[ae].feature_type=V.config?.usage_type)}for(let ae=0;ae<y.length;ae++){let V=y[ae],Fe=r({item:V}),Z=i({item:V});if(o(V)&&y.find((ie,Lt)=>ie.feature_id===V.feature_id&&Lt!==ae&&V.entity_feature_id===ie.entity_feature_id))throw new a({message:`Feature ${V.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let rt=y.find((de,ie)=>de.feature_id===V.feature_id&&ie!==ae&&r({item:de})===Fe&&i({item:de})===Z&&de.entity_feature_id===V.entity_feature_id);if(rt){if(u(rt)&&u(V))throw new a({message:`You're trying to create two items for the same feature (${V.feature_id}) with the same interval. Please make them into one item.`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(V.usage_model&&V.usage_model===rt?.usage_model)throw new a({message:`You're trying to add the same feature (${V.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(V)&&y.find((ie,Lt)=>d({item:ie})===d({item:V})&&m({item:ie})===m({item:V})&&Lt!==ae))throw new a({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let we=y.some(ae=>(l(ae)||g(ae))&&String(d({item:ae}))===p.Week),Te=y.some(ae=>(l(ae)||g(ae))&&String(d({item:ae}))===p.Month);if(we&&Te)throw new a({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 a({message:"Can't have more than one price item in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});return{allFeatures:$,newFeatures:G}}}))(lw,lC,vt,Ia,Aa,Yh,Rt,Bt,Bn,xa,Wc,Vn,Yr,Kc,$c),{handleNewProductItems:EM}=((e,t,n,r,i)=>({handleNewProductItems:async({db:a,curPrices:s,curEnts:c,newItems:u,features:l,product:d,logger:m,isCustom:g,newVersion:p,saveToDb:h=!0,multiCurrencyEnabled:y})=>{if(!u)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:l};let{allFeatures:A,newFeatures:S}=e({newItems:u,features:l,orgId:d.org_id,env:d.env,multiCurrencyEnabled:y,validateRollover:!g});l=A;let j=[],I=[],v=[],$=[],G=s.filter(V=>{let Fe=u.find(Z=>Z.price_id===V.id);return Fe?t(Fe):!0}),we=c.filter(V=>!u.some(Fe=>Fe.entitlement_id===V.id)),Te=[],ae=[];for(let V of u){let Fe=l.find(Zt=>Zt.id===V.feature_id),Z=c.find(Zt=>Zt.id===V.entitlement_id),rt=s.find(Zt=>Zt.id===V.price_id),{newPrice:de,newEnt:ie,updatedPrice:Lt,updatedEnt:Ke,samePrice:qt,sameEnt:In}=n({item:V,orgId:d.org_id,internalProductId:d.internal_id,feature:Fe,curPrice:rt,curEnt:Z,isCustom:g,newVersion:p,features:l});de&&j.push(de),ie&&I.push(ie),Lt&&v.push(Lt),Ke&&$.push(Ke),qt&&Te.push(qt),In&&ae.push(In)}return r({targetPrices:[...j,...v],targetEntitlements:[...I,...$,...ae],candidatePrices:s,candidateEntitlements:c}),(g||p)&&h?{...i({newPrices:j,newEnts:I,updatedPrices:v,updatedEnts:$,samePrices:Te,sameEnts:ae,features:l}),samePrices:Te,sameEnts:ae,newFeatures:S,retiredPriceIds:G.map(V=>V.id),retiredEntitlementIds:we.map(V=>V.id)}:{prices:[...j,...v],entitlements:[...I,...$].map(V=>({...V,feature:l.find(Fe=>Fe.id===V.feature_id)})),customPrices:[],customEnts:[],features:l,samePrices:Te,sameEnts:ae,newFeatures:S,retiredPriceIds:G.map(V=>V.id),retiredEntitlementIds:we.map(V=>V.id)}}}))(dC,wa,rC,cC,OA);var pC=tn.clone({precision:40});function iu(e){if(!eu(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function ou(e){let t=new pC(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function kM(e,t){let n=iu(t),i=ou(e).toDecimalPlaces($h(n),tn.ROUND_HALF_CEIL).mul(Pa(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 DM(e,t){let n=iu(t),r=ou(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(Pa(n)).toString()}function NM(e,t){let n=ou(e).mul(Pa(iu(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()}import{z as fe}from"zod";var mC={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},au=fe.string().regex(/^[a-f0-9]{64}$/),su=fe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),fC=je.extend({environmentId:fe.uuid()}),pg=fe.strictObject({features:fe.array(fe.string()).max(500),experiments:fe.record(fe.uuid(),fe.array(fe.string()).max(20)),savedGroups:fe.array(fe.string()).max(1e3)}),hC=fe.strictObject({kind:fe.enum(["funnel","gb_features","gb_page_experiments"]),formatVersion:fe.number().int().positive(),url:fe.string().min(1).max(2048),sha256:au,byteLength:fe.number().int().positive().max(mC.maxArtifactBytes),generation:au.optional()}),gC=fe.strictObject({state:fe.enum(["active","paused","archived"]),controlRevision:su,evaluationMode:fe.enum(["local","remote"]),evaluationRevision:su,currentVersionId:fe.uuid(),versions:fe.record(fe.uuid(),fe.strictObject({artifact:fe.string(),dependencies:pg,definitionDigest:kr.optional(),couponDigests:fe.record(fe.uuid(),kr).optional()}))}),KM=fe.strictObject({kind:fe.literal("sdk_configuration"),schemaVersion:fe.literal(1),scope:fC,revision:su,generation:au,policy:fe.strictObject({refreshIntervalSeconds:fe.number().positive().max(15),maxControlAgeSeconds:fe.number().positive().max(60)}),gb:fe.strictObject({features:fe.string().nullable(),pageExperiments:fe.string().nullable()}),artifacts:fe.record(fe.string(),hC),funnels:fe.record(fe.uuid(),gC)}).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.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 cu(e){if(Array.isArray(e))return`[${e.map(cu).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)}:${cu(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function bC(e){return Qi(Zi(typeof e=="string"?new TextEncoder().encode(e):e))}function HM(e){return bC(cu(e))}function WM(e,t){for(let a of Object.values(e.references))if(a.type==="flag"&&(!Object.hasOwn(t.features,a.key)||t.remoteFeatures.includes(a.key))||a.type==="experiment"&&!Object.hasOwn(t.experiments,a.id)||a.type==="saved_group"&&!Object.hasOwn(t.savedGroups,a.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=na(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let a of e.graph.nodes){let s=a.type==="feature"?a.featureKey:a.type==="end"&&a.output?.type==="feature"?a.output.featureKey:a.type==="output"&&a.value.type==="feature"?a.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=a.type==="feature"?e.variables[a.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(m=>m.experiment.variations)])].some(d=>d===void 0||!Nt(u,d)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,o=a=>{for(let s of dr(a)){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"&&o(c.condition)}};for(let a of e.graph.nodes)if(a.type==="condition")for(let s of a.cases)o(s.condition);for(let a of Object.values(n.features))for(let s of a.rules??[]){o(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");o(c.condition)}for(let c of s.tracks??[])o(c.experiment.condition)}for(let a of Object.values(n.experiments)){o(a.condition);for(let s of a.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");o(s.condition)}}for(let a of e.graph.nodes)if(a.type==="split"){let s=n.experiments[a.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(!a.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return pg.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([a,s])=>[a,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function QM(e){return un.parse(e)}function e4(e){let t=e.screens.map(n=>n.type==="owned"?{...n,document:Yo(n.document)}:n);for(let n of e.inputs){let r=t.find(i=>i.id===n.screenId);if(r?.type==="owned"&&!oi(r.document,n.componentId))throw new Error(`Local Funnel input ${n.variable} targets hidden component ${n.componentId} on screen ${n.screenId}`)}return un.parse({...e,screens:t})}import{z as Le}from"zod";var lu=32,_C=522240;function du(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 yC=Le.strictObject({nodeId:Le.string().min(1).max(64),visit:Le.number().int().nonnegative(),revision:Le.number().int().nonnegative()}),uu=Le.record(Le.string(),he),SC=Le.strictObject({id:Le.uuid(),nodeId:Le.string().min(1).max(64),visit:Le.number().int().nonnegative(),input:Le.strictObject({schemaVersion:Nr.shape.schemaVersion,kind:Nr.shape.kind,selector:Nr.shape.selector,contract:Nr.shape.contract}),context:uu,removed:Le.array(Le.string()).max(100),attributes:uu,removedAttributes:Le.array(Le.string()).max(100),result:Sf,offeringVersionId:Le.uuid().nullable(),events:Le.strictObject({entered:Le.string().regex(/^[1-9][0-9]{0,18}$/),decision:Le.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),vC=Le.strictObject({schemaVersion:Le.literal(1),mode:Le.enum(["local","remote"]),versionId:Le.uuid(),generation:Le.number().int().positive(),base:yC,context:uu,steps:Le.array(SC).min(1).max(lu)}).refine(e=>gt(e)<=_C,"Segment exceeds its byte budget"),s4=(e,t,n)=>hf(e,t,`step:${n}`);function Ea(e){return Array.isArray(e)?e.some(t=>Ea(t)):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>(t==="hashAttribute"||t==="fallbackAttribute")&&n==="results"||Ea(n))}function c4(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,o={},a=[];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)&&(o[s]=c);a=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:o,removedAttributes:a}}function u4(e){let t=vC.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=Le.record(Le.string(),he).parse(n.attributes);for(let o of r.removedAttributes)delete i[o];n.attributes={...i,...r.attributes}}return{...r,input:Nr.parse({...r.input,context:structuredClone(n)})}})}var pu=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},Ta=(e,t)=>new pu(e,t),xC=e=>({experiments:e.experiments,features:e.features});function IC(e,t=Ta){let n=new Map(e.topology.nodes.map(a=>[a.id,a])),r=yu(e.growth.savedGroups),i=xC(e.growth);function o(a,s){if(!Object.hasOwn(e.growth.features,a))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return zr(a,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:o,evaluate(a,s){let c=n.get(a);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,l;if(c.type==="condition"){let m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=_c({id:c.id,name:c.id,type:"condition",cases:m.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=o(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=_c({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=o(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:a,port:u,target:d,...l===void 0?{}:{value:l}}}}}function AC(e,t,n,r=Ta){let i=Mr.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 o=IC(i,r),a=wt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:s,onFeatureUsage:c,onExperimentViewed:u}=n,l={attributes:a,...s?{saveStickyBucketAssignmentDoc:d=>s(structuredClone(d))}:{},...c?{onFeatureUsage:(d,m)=>c(d,structuredClone(m))}:{},...u?{onExperimentViewed:(d,m)=>u(structuredClone(d),structuredClone(m))}:{},features:o.features,savedGroups:o.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return o.evaluate(t,l)}function mg(e,t,n,r=Ta){let i=[],o=[],a=[],s=AC(e,t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(c){let u=i.findIndex(m=>m.next.attributeName===c.attributeName&&m.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&&o.push(he.parse({key:c.key,variationId:u.variationId,keyUsed:u.key,hashAttribute:u.hashAttribute,hashValue:u.hashValue}))},onFeatureUsage(c,u){a.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:o,features:a}}function S4(e,t,n,r=Ta){let i=n,o=new Map(t.graph.nodes.map(p=>[p.id,p])),a=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=e.evaluationMode==="local"&&Ea(e.growth),l=n.nodeId,d=n.visit,m=!1;for(let p=0;p<lu;p++){let h=o.get(l);if(!h||!du(h))break;if(d>=t.execution.maxTransitions)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");let y={attributes:h.type==="condition"?Go({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:a,savedGroups:{}}):{...i.attributes,parameters:n.parameters,answers:n.answers,results:a},sticky:s},A,S;if(["condition","feature","split"].includes(h.type)||h.type==="offering"&&h.configuration.source==="feature")A=mg(e,h.id,y,r),h.type==="offering"&&(A.value={type:"offering_version",id:String(A.value)}),h.type==="condition"?S=A.port==="default"?h.default:h.cases[Number(A.port.slice(5))]?.target:h.type==="split"?S=A.port==="notParticipating"?h.notParticipating:h.routes[A.port]:(h.type==="feature"||h.type==="offering")&&(S=h.next);else if(A={port:"next",sticky:[],exposures:[],features:[]},(h.type==="entry"||h.type==="coupon"||h.type==="coupons")&&(S=h.next),h.type==="offering"&&h.configuration.source==="fixed"&&(A.value={type:"offering_version",id:h.configuration.versionId},S=h.next),h.type==="end"||h.type==="output"){let I=h.type==="end"?h.output:h.value;if(A=I?.type==="feature"?mg(e,h.id,y,r):{...A,port:"value",value:I?.type==="literal"?I.value:I?.type==="variable"?sr({source:"variable",key:I.key,...I.path?{path:I.path}:{}},{declarations:t.variables,answers:n.answers,results:a,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},I&&(A.value===void 0||!Nt(t.outputSchema,A.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let j=[...c,{nodeId:l,result:A}];if(gt({steps:j})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:l,result:A}),h.type==="feature"||h.type==="offering"||h.type==="coupon"||h.type==="coupons"){let I=h.type==="coupons"?h.couponIds.map($=>({type:"reward",id:$})):h.type==="coupon"?{type:"reward",id:h.couponId}:A.value;if(I===void 0)throw r("INVALID_RESPONSE","Node output is missing");let v=or(h,{value:I});ac(t.variables,h,v),Object.assign(a,v)}for(let I of A.sticky)s[`${I.next.attributeName}||${I.next.attributeValue}`]=structuredClone(I.next);if(h.type==="end"||h.type==="output"){m=!0;break}if(!S)throw r("INVALID_RESPONSE","Local pure exit is unavailable");if(l=S,d++,u&&["feature","offering","coupon","coupons"].includes(h.type))break}let g=o.get(l);return{steps:c,...!m&&g&&!du(g)?{boundary:{nodeId:l,visit:d}}:{}}}import{z as wC}from"zod";var w4=wC.strictObject({document:un,configuration:Mr.options[0]});var CC=["checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","readSubscriptionOperation","readSubscriptionUpdate","readPaymentSetup","readRefund","readBillingControls","listBillingInvoices","readSeats","quoteBalance","readUsage","readBalanceSource","listBalanceGrants","readUsageAnalytics","readCreditAnalytics","readUsageBatch","listOffers"];function P4(e){return e.type==="external_page"||e.type==="wait"||e.type==="action"&&!(e.action.type==="api"&&CC.includes(e.action.operation))||e.type==="output"&&e.value.type==="bundle"}export{h_ as a,$l as b,is as c,Hl as d,go as e,__ as f,os as g,y_ as h,Wl as i,as as j,HC as k,S_ as l,Ql as m,WC as n,Zl as o,QC as p,di as q,cs as r,bo as s,eP as t,Jl as u,x_ as v,I_ as w,tP as x,us as y,ls as z,ds as A,ps as B,w_ as C,C_ as D,zl as E,P_ as F,pP as G,on as H,SP as I,ed as J,vP as K,td as L,O_ as M,nd as N,xP as O,IP as P,E_ as Q,rd as R,ms as S,AP as T,wP as U,EP as V,T_ as W,R_ as X,ad as Y,NP as Z,gr as _,Jt as $,sd as aa,j_ as ba,cd as ca,FP as da,UP as ea,MP as fa,BP as ga,LP as ha,qP as ia,pi as ja,_o as ka,md as la,gs as ma,br as na,D_ as oa,N_ as pa,F_ as qa,U_ as ra,Cn as sa,fd as ta,hd as ua,gd as va,bd as wa,yo as xa,_d as ya,yd as za,Sd as Aa,vd as Ba,B_ as Ca,xd as Da,L_ as Ea,q_ as Fa,V_ as Ga,Id as Ha,bs as Ia,$_ as Ja,fi as Ka,Ad as La,wd as Ma,Cd as Na,G_ as Oa,Pd as Pa,Od as Qa,gi as Ra,bi as Sa,Wn as Ta,So as Ua,ys as Va,K_ as Wa,Td as Xa,Rd as Ya,_i as Za,vo as _a,jd as $a,aO as ab,sO as bb,cO as cb,uO as db,H_ as eb,lO as fb,dO as gb,vs as hb,hO as ib,gO as jb,Dd as kb,W_ as lb,_O as mb,kd as nb,Q_ as ob,Fd as pb,Is as qb,Y_ as rb,yO as sb,Qn as tb,SO as ub,vO as vb,J_ as wb,X_ as xb,z_ as yb,ey as zb,wO as Ab,CO as Bb,Ud as Cb,As as Db,DO as Eb,NO as Fb,ty as Gb,BO as Hb,LO as Ib,ny as Jb,Vd as Kb,ws as Lb,$d as Mb,Gd as Nb,Kd as Ob,ry as Pb,Hd as Qb,Cs as Rb,Wd as Sb,zO as Tb,Qd as Ub,eE as Vb,tE as Wb,Yd as Xb,Jd as Yb,Es as Zb,oy as _b,Xd as $b,aE as ac,ay as bc,sy as cc,En as dc,ep as ec,cy as fc,uy as gc,Ts as hc,Rs as ic,Tn as jc,Ey as kc,js as lc,yr as mc,yp as nc,Jn as oc,iS as pc,oS as qc,vp as rc,vi as sc,Sr as tc,Io as uc,xp as vc,Ip as wc,ks as xc,aS as yc,sS as zc,cS as Ac,Ap as Bc,Ds as Cc,wp as Dc,Cp as Ec,Pp as Fc,Ao as Gc,EE as Hc,TE as Ic,Op as Jc,wo as Kc,uS as Lc,Ii as Mc,Co as Nc,Ep as Oc,dS as Pc,Fs as Qc,FE as Rc,Rp as Sc,jp as Tc,pS as Uc,Us as Vc,Dp as Wc,Np as Xc,Oo as Yc,Eo as Zc,mS as _c,fS as $c,hS as ad,Fp as bd,Up as cd,Mp as dd,Bp as ed,Lp as fd,qp as gd,Vp as hd,$p as id,qs as jd,gS as kd,bS as ld,Ai as md,_S as nd,SS as od,vS as pd,wi as qd,YE as rd,To as sd,Ls as td,xS as ud,Kp as vd,Hp as wd,IS as xd,JE as yd,XE as zd,Wp as Ad,AS as Bd,zE as Cd,wS as Dd,vr as Ed,Qp as Fd,aT as Gd,Zp as Hd,_n as Id,PS as Jd,jo as Kd,ko as Ld,TS as Md,RS as Nd,Yp as Od,bT as Pd,_T as Qd,yT as Rd,ST as Sd,Jp as Td,Do as Ud,zp as Vd,Vs as Wd,em as Xd,tm as Yd,nm as Zd,im as _d,rm as $d,$s as ae,jS as be,MT as ce,kS as de,om as ee,DS as fe,tr as ge,am as he,cm as ie,um as je,lm as ke,dm as le,pm as me,NS as ne,mm as oe,FS as pe,US as qe,MS as re,BS as se,gm as te,Hs as ue,_m as ve,LS as we,qS as xe,XT as ye,zT as ze,eR as Ae,Sm as Be,vm as Ce,xm as De,Im as Ee,Am as Fe,wm as Ge,tR as He,nR as Ie,$S as Je,GS as Ke,rR as Le,iR as Me,sn as Ne,Ws as Oe,KS as Pe,Pi as Qe,HS as Re,sR as Se,Pm as Te,Om as Ue,cR as Ve,Em as We,Tm as Xe,Qs as Ye,Zs as Ze,ZS as _e,YS as $e,JS as af,uR as bf,Ys as cf,Ar as df,Uo as ef,jm as ff,wr as gf,Cr as hf,nr as if,rr as jf,Pr as kf,km as lf,XS as mf,zS as nf,Js as of,Dm as pf,Nm as qf,Fm as rf,Xs as sf,Um as tf,zs as uf,bR as vf,_R as wf,ec as xf,ev as yf,Mm as zf,tv as Af,Bm as Bf,Lm as Cf,qm as Df,tc as Ef,nv as Ff,Vm as Gf,PR as Hf,$m as If,nc as Jf,Gm as Kf,Oi as Lf,Km as Mf,OR as Nf,rv as Of,hj as Pf,D as Qf,iv as Rf,ov as Sf,av as Tf,gj as Uf,k as Vf,bj as Wf,Qe as Xf,Qm as Yf,Bo as Zf,xj as _f,Ij as $f,gt as ag,Ym as bg,Zm as cg,qo as dg,Cj as eg,Jm as fg,jj as gg,cv as hg,uv as ig,kj as jg,Dj as kg,Xm as lg,lv as mg,Uj as ng,dv as og,zm as pg,ef as qg,pv as rg,Mj as sg,Bj as tg,Lj as ug,qj as vg,mv as wg,Gj as xg,Kj as yg,Qj as zg,Zj as Ag,nf as Bg,zj as Cg,ek as Dg,Er as Eg,Tr as Fg,hv as Gg,$o as Hg,Nt as Ig,ir as Jg,or as Kg,ac as Lg,ki as Mg,Go as Ng,sc as Og,Di as Pg,Gt as Qg,cn as Rg,Rr as Sg,sr as Tg,rf as Ug,Ho as Vg,cc as Wg,gv as Xg,af as Yg,sf as Zg,cf as _g,gk as $g,bk as ah,_k as bh,yk as ch,Sk as dh,bv as eh,vk as fh,uc as gh,Ni as hh,Wo as ih,uf as jh,lc as kh,Qo as lh,lf as mh,Fi as nh,_v as oh,dc as ph,Dk as qh,Nk as rh,Fk as sh,df as th,yv as uh,Vk as vh,$k as wh,Gk as xh,Sv as yh,vv as zh,pc as Ah,Qk as Bh,xv as Ch,Iv as Dh,ff as Eh,eD as Fh,mc as Gh,fc as Hh,Cv as Ih,hc as Jh,gc as Kh,jr as Lh,Pv as Mh,Ov as Nh,mD as Oh,Ui as Ph,_c as Qh,hf as Rh,kr as Sh,gf as Th,TD as Uh,RD as Vh,Tv as Wh,Rv as Xh,Yo as Yh,Jo as Zh,yc as _h,Sc as $h,LD as ai,qD as bi,yf as ci,QD as di,xc as ei,Ic as fi,Nr as gi,Sf as hi,ZD as ii,YD as ji,jv as ki,Ut as li,kv as mi,Dv as ni,Cc as oi,un as pi,hN as qi,gN as ri,Nv as si,Fv as ti,Mi as ui,Uv as vi,Mv as wi,wN as xi,CN as yi,PN as zi,Pc as Ai,Bv as Bi,Lv as Ci,Oc as Di,If as Ei,VN as Fi,HN as Gi,Af as Hi,eF as Ii,tF as Ji,Cf as Ki,Mr as Li,$v as Mi,Gv as Ni,Kv as Oi,mF as Pi,Of as Qi,Hv as Ri,Ec as Si,Tc as Ti,Rc as Ui,Wv as Vi,Qv as Wi,CF as Xi,PF as Yi,OF as Zi,EF as _i,jF as $i,NF as aj,Tf as bj,BF as cj,LF as dj,Zv as ej,Yv as fj,Jv as gj,Xv as hj,zv as ij,e0 as jj,GF as kj,t0 as lj,KF as mj,HF as nj,YF as oj,n0 as pj,r0 as qj,ra as rj,i0 as sj,o0 as tj,zF as uj,i2 as vj,o2 as wj,a2 as xj,a0 as yj,s2 as zj,d2 as Aj,p2 as Bj,v0 as Cj,x0 as Dj,I0 as Ej,w2 as Fj,$f as Gj,A0 as Hj,O2 as Ij,Gf as Jj,k2 as Kj,D2 as Lj,B2 as Mj,L2 as Nj,w0 as Oj,G2 as Pj,K2 as Qj,Kf as Rj,Hf as Sj,X2 as Tj,z2 as Uj,P0 as Vj,uU as Wj,E0 as Xj,lU as Yj,T0 as Zj,pU as _j,Qf as $j,mU as ak,fU as bk,Zf as ck,Yf as dk,yU as ek,SU as fk,R0 as gk,CU as hk,j0 as ik,PU as jk,OU as kk,zf as lk,eh as mk,kU as nk,DU as ok,NU as pk,FU as qk,Xf as rk,UU as sk,k0 as tk,LU as uk,$U as vk,N0 as wk,nh as xk,GU as yk,HU as zk,WU as Ak,kM as Bk,DM as Ck,NM as Dk,mC as Ek,fC as Fk,pg as Gk,hC as Hk,gC as Ik,KM as Jk,cu as Kk,bC as Lk,HM as Mk,WM as Nk,QM as Ok,e4 as Pk,lu as Qk,_C as Rk,du as Sk,yC as Tk,SC as Uk,vC as Vk,s4 as Wk,Ea as Xk,c4 as Yk,u4 as Zk,pu as _k,IC as $k,AC as al,mg as bl,S4 as cl,w4 as dl,CC as el,P4 as fl};