@tinkerlandai/indiana-sdk 0.3.1 → 0.5.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 (39) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +18 -13
  3. package/README.zh-CN.md +7 -4
  4. package/THIRD_PARTY_NOTICES.md +27 -0
  5. package/dist/ai-usage-BzydP8eN.d.ts +11085 -0
  6. package/dist/chunk-3OSMEG44.js +17 -0
  7. package/dist/chunk-GA6X57BO.js +1 -0
  8. package/dist/chunk-GTBD4BJ4.js +11 -0
  9. package/dist/chunk-QUW4UOKZ.js +4 -0
  10. package/dist/chunk-RMFH5TWV.js +1 -0
  11. package/dist/chunk-YNUVRZRQ.js +1 -0
  12. package/dist/chunk-ZT523F45.js +1 -0
  13. package/dist/funnel-runtime-host-RZRB2CY6.js +1 -0
  14. package/dist/{funnel-runtime-start-CQhy2kx1.d.ts → funnel-runtime-start-JHA9ES24.d.ts} +68 -29
  15. package/dist/index.d.ts +109 -53
  16. package/dist/index.js +1 -1
  17. package/dist/native-shell.js +1 -1
  18. package/dist/openrouter.d.ts +3 -2
  19. package/dist/openrouter.js +1 -1
  20. package/dist/page.d.ts +13 -12
  21. package/dist/page.js +1 -4
  22. package/dist/{paywall-Y3FIG43H.js → paywall-MYBEOVTQ.js} +1 -1
  23. package/dist/popup.d.ts +254 -1
  24. package/dist/popup.js +8 -7
  25. package/dist/{screen-Keau_Qa2.d.ts → screen-16d-xADb.d.ts} +354 -463
  26. package/dist/server.d.ts +4 -3
  27. package/dist/server.js +1 -1
  28. package/dist/src-E2GXK6WA.js +1 -0
  29. package/dist/visual-editor-agent-FDCV3BXP.js +1 -0
  30. package/dist/visual.d.ts +38 -0
  31. package/dist/visual.js +1 -0
  32. package/package.json +8 -2
  33. package/dist/ai-usage-D_mBF5Gp.d.ts +0 -9942
  34. package/dist/chunk-CRJJ4EA2.js +0 -1
  35. package/dist/chunk-D37O6FAW.js +0 -11
  36. package/dist/chunk-G5ZGWOLJ.js +0 -1
  37. package/dist/chunk-MJG7X7LM.js +0 -17
  38. package/dist/funnel-runtime-host-X7AGEGHN.js +0 -1
  39. package/dist/src-RZJKF6LQ.js +0 -1
@@ -0,0 +1,11 @@
1
+ import{E as xu,F as vu,I as Iu,J as fn,a as _u,b as $e,g as yu,l as Ke,m as pn,n as Nn,o as Fo,p as ia,t as Su,v as si}from"./chunk-3OSMEG44.js";import{z as rn}from"zod";import{z as A}from"zod/v4";import{z as Rg}from"zod/v4";var Au=Rg.registry();var{AppEnv:aa}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:Pu}={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:kg}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:jg}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(A),{ResetInterval:ci}=(()=>{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:Ng}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:Dg}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:Ug}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:Fg}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:Mg}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(A),{BALANCE_BASES:Lg}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:Cu}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:Mo}=(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."})})}))(A),{ProductMetadataSchema:Ar}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(A),{findDuplicate:Bg}={findDuplicate:t=>{let n=new Set;for(let r of t){if(n.has(r))return r;n.add(r)}}},{BillingInterval:Dn}=(()=>{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:Lo}=(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')."})})}))(A),{withSpecDefault:ui}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Au),{COMMON:wu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:qg}={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:Vg}=(e=>({COMMON_SET:new Set(e)}))(wu),{hasNoDuplicateCurrencies:Ou}={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:Eu}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:Bo}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(A),{Infinite:oa}={Infinite:"inf"},{TierBehavior:li}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:sa}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Tu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:$g}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:ca}=(()=>{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:ua}=(()=>{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:qo}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:Ru}=(()=>{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:Gg}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Hg}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Vo}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(A),{ApiCreditTierSchema:ku}=(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."})})}))(A),{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:ju}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(A),{ModelMarkupsSchema:$o}=((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()}))(A,ju),{additionalCurrencyPlanItemIssues:Nu}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let n=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&n.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let r=t.tiers;if(r&&r.length>0){let i=o=>(o.additional_currencies??[]).map(s=>s.currency.toLowerCase()),a=new Set(r.flatMap(i));a.size>0&&(r.every(s=>{let c=new Set(i(s));return c.size===a.size&&[...a].every(u=>c.has(u))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:Go}=((e,t,n,r,i)=>({PlanItemFilterSchema:e.object({feature_id:e.string().optional().meta({description:"Match items linked to this feature."}),billing_method:e.enum(t).optional().meta({description:"Match items with this billing method (prepaid or usage_based)."}),interval:e.union([e.enum(n),e.enum(r)]).optional().meta({description:"Match items with this interval. Accepts either a BillingInterval (price-side) or a ResetInterval (reset-side, includes day/hour/minute) so price-less items keyed by reset.interval can be disambiguated."}),interval_count:e.number().int().positive().optional().meta({description:"Match items with this interval_count. Disambiguates between items that share an interval but differ in count."}),included:i.optional().meta({description:"Match items whose grant equals this included usage. Omitted is a wildcard."})}).refine(o=>o.feature_id!==void 0||o.billing_method!==void 0||o.interval!==void 0||o.interval_count!==void 0,{message:"PlanItemFilter must have at least one field set."}).meta({title:"PlanItemFilter",description:"Filter for matching plan items. All provided fields must match (AND)."})}))(A,sa,Dn,ci,Bo),{UpdatePlanItemParamsV1Schema:Wg}=((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})}))(A,Go,ci),{FreeTrialDuration:di}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:Qg}=((e,t)=>({laneParam:({schema:r,description:i})=>e({schema:t.array(r).optional(),defaultValue:[],description:i})}))(ui,A),{findDuplicateInControls:Zg}={findDuplicateInControls:({controlKey:t,controls:n,rule:r})=>{let i=new Set;for(let[a,o]of n.entries()){let s=r.identityOf(o);if(s!==void 0){if(i.has(s))return{code:"custom",message:r.message,input:o[r.field],path:[t,a,r.field]};i.add(s)}}}},{featureIdIdentity:zg}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:Du}={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:Yg}=((e,t)=>({usageAlertIdentity:r=>[r.feature_id??"",r.basis??e,t(r.filter),r.threshold_type,r.threshold].join("|")}))(Cu,Du),{RemovePlanLicenseSchema:Jg}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(A),{ApiStripePriceProcessorSchema:Xg}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(A),{ApiFeatureType:eb}=(()=>{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:tb}=(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."})})}))(A),{ApiRevenueCatProductSchema:nb}=(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."})})}))(A),{TrialOnEnd:la}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:rb}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:ib}=(()=>{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:ab}=(()=>{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:ob}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(A),{UsageWindowScopeSchema:sb}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(A),{EntInterval:Uu}=(()=>{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:cb}=(()=>{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:ub}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(A),{FreeTrialSchema:lb}=((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()})}))(A,di,la),{BillingType:db}=(()=>{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:Ho}=((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()}))}))(A,oa),{IgnoredFixedPriceMetadataSchema:mb}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(A),{BillWhen:pb}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Fu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:fb}=((e,t,n)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(n).default(n.ProrateImmediately)})}))(A,ca,ua),{AllowanceType:hb}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Mu}=((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()})}))(A,qo),{CreditDimensionBaseSchema:gb}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(A,Vo),{flatCreditRateShape:Lu}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(A),{CreditTierSchema:bb}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(A),{CreditMultiplierSchema:_b}=((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"})}))(A,Vo),{idRegex:da}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Bu}={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:yb}=(()=>{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:xb}=(()=>{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:vb}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:Ib}={TierInfinite:"inf"},{CreateFreeTrialSchema:qu}=((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()})}))(A,di,la),{ProductConfigParamsSchema:Ko}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(A,ui,Pu),{CREATE_PRODUCT_EXAMPLE:Ab}={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."})})}))(A,di,la),{CreateProductSchema:Tw}=(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("")})}))(A),{isUsageLimitBasisAlert:Cb}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:Vu}=(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()})}))(A),{RewardType:$u}=(()=>{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:Gu}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:Hu}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(A,Gu),{RewardTriggerEvent:wb}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:Ob}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:ma}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(A,Pu),{PurchaseLimitIntervalEnum:Eb}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(A,kg),{DbSpendLimitSchema:Wo}=((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"]})}))(A,jg),{USAGE_LIMIT_INTERVALS:Tb}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(ci),{UsageLimitAnchorSchema:Ku}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(A,Ng),{UsageLimitFilterValueSchema:Rb}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(A,Ug),{USAGE_ALERT_BASES:kb}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(Lg),{licensePatchIssues:jb}=(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"]}]}}))(Bg),{BasePriceSchema:Nb}=((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."})})}))(A,Dn,Lo),{CURRENCY_CODES:Db}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(wu,qg,Vg),{AllocatedBillingFieldSchema:Wu}=((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'."})}))(A,Tu),{EntitlementExpirySchema:pa}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(A,Ru),{CreditDimensionNameSchema:Qu}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(A,Gg,Hg),{ApiCreditMatchSchema:Zu}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Vo),{findCreditTierViolations:Ub}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Kg),{ApiCreditMultiplierSchema:Fb}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(A,Zu),{ProviderMarkupsSchema:zu}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(A,ju),{planItemParamsIssues:Mb}=((e,t,n,r,i)=>({planItemParamsIssues:o=>{let s=[],c=o.reset?.interval,u=o.price?.interval,l=o.reset?.interval_count??1,d=o.price?.interval_count??1;if(c&&u&&(String(c)!==String(u)||l!==d)&&o.price?.billing_method!==e.Prepaid&&s.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:o}),o.threshold_billing&&(!o.price||o.unlimited)&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing}),o.expiry&&(o.price?.billing_method===e.Prepaid&&String(o.price.interval)===String(t.OneOff)||s.push({message:"expiry is only supported on one-off prepaid items. Recurring items are already bounded by their reset cadence.",input:o.expiry}),o.entity_feature_id&&s.push({message:"expiry is not supported on entity-scoped items; each entity's balance would have to expire on its own clock.",input:o.expiry}),o.pooled&&s.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:o.expiry}),o.expiry.length<=0&&s.push({message:"expiry.length must be greater than 0",input:o.expiry})),o.price){o.threshold_billing&&o.price.billing_method!==e.UsageBased&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing});let{amount:g,tiers:p}=o.price;o.threshold_billing&&p?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:o.threshold_billing});let h=o.price.billing_method===e.UsageBased&&o.price.allocated_billing===n.ProratedLegacy;o.proration&&o.price.billing_method!==e.Prepaid&&!h&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:o.proration});let x=typeof g=="number",I=Array.isArray(p)&&p.length>0;x||I?x&&I&&s.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:o.price}):s.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:o.price})}if(o.price?.tiers){let g=o.price.tiers.some(p=>p.flat_amount&&p.flat_amount>0);g&&o.price.tier_behavior!==r.VolumeBased&&s.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:o.price}),g&&o.price.tiers.length<=1&&s.push({message:"flat_amount is not supported on single-tier pricing.",input:o.price}),o.price.tiers.some(p=>p.flat_amount!=null&&p.flat_amount<0)&&s.push({message:"flat_amount must be 0 or greater.",input:o.price}),o.price?.tier_behavior===r.VolumeBased&&o.price?.billing_method!==e.Prepaid&&s.push({message:"volume-based pricing is only supported for prepaid features.",input:o.price}),o.price?.tiers.length===0?s.push({message:"tiers cannot be empty.",input:o.price}):o.included&&typeof o.price?.tiers[0].to=="number"&&o.price?.tiers[0].to<=o.included&&s.push({message:"tiers[0].to must be greater than included.",input:o.price})}for(let g of i(o.price))s.push({message:g,input:o.price});return s}}))(sa,Dn,Tu,li,Nu),{FreeTrialParamsV1Schema:Qo}=((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."})}))(A,di,ui),{duplicateCheck:Lb}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(Zg),{usageLimitIdentity:Zo}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(Du),{ApiPriceProcessorsSchema:Yu}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(A,Xg),{ApiFeatureV0Schema:Ju}=((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."})})}))(A,eb),{ApiRevenueCatPlanProcessorSchema:Bb}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(A,nb),{ApiFreeTrialV2Schema:qb}=((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."})})}))(A,di,la),{CustomerEligibilitySchema:Vb}=((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})})}))(A,rb,ib,ab),{UsageWindowLimitSchema:Rw}=((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()})}))(A,ob,sb,Uu,Ku),{FeatureSchema:$b}=((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()})}))(A,aa,cb,$o,ub),{PriceCurrencyConfigSchema:Xu}=((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()})}))(A,Ho),{UsagePriceConfigSchema:Gb}=((e,t,n,r,i,a)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(a).optional()})}))(A,pb,Ho,Dn,Xu,Fu),{graduatedCreditRateShape:el}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(A,bb),{FeatureMarkupsOverrideSchema:Hb}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(A,zu,$o),{usageAlertTargetLimitIdentity:Kb}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(Zo),{DiscountConfigSchema:tl}=((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()})}))(A,Gu),{RewardEntitlementSchema:nl}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(A,pa),{UpdateRewardSchema:kw}=((e,t,n,r,i,a)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(n).optional(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(a).nullish()})}))(A,Vu,$u,tl,Hu,nl),{CreateRewardProgram:jw}=((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)})}))(A,wb,Ob),{AutoTopupPurchaseLimitSchema:rl}=((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."})})}))(A,Eb),{UsageLimitFilterSchema:il}=((e,t,n,r)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),n).meta({description:"Event property equality conditions. A usage event counts toward this cap only when every listed property matches (AND)."}).check(a=>{let o=Object.keys(a.value).length;(o<1||o>r)&&a.issues.push({code:"custom",message:`filter.properties must have between 1 and ${r} keys`,input:a.value})})})}))(A,Dg,Rb,Fg),{UsageAlertBasisSchema:Wb}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(A,kb),{refineCustomizePlanV1Schema:al}=(e=>({refineCustomizePlanV1Schema:(n,{includeItems:r=!0,includeFreeTrial:i=!0,includeUpdateItems:a=!0,includeLicenses:o=!0}={})=>{let s=["price",r&&"items","add_items","remove_items",a&&"update_items",i&&"free_trial","billing_controls",o&&"upsert_licenses",o&&"remove_licenses"].filter(Boolean),c=u=>u==="update_items"?"deprecated update_items":u;return n.refine(u=>s.some(l=>u[l]!==void 0),{message:`When using customize, at least one of ${s.map(c).join(", ")} must be provided`}).superRefine((u,l)=>{if(o)for(let d of e({upsertLicenses:u.upsert_licenses}))l.addIssue({code:"custom",...d})}).refine(u=>!(u.items!==void 0&&(u.add_items!==void 0||u.remove_items!==void 0||a&&u.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",a?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(jb),{SUPPORTED_SET:Qb}=(e=>({SUPPORTED_SET:new Set(e)}))(Db),{ApiCreditDimensionBaseSchema:Zb}=((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."})})}))(A,Zu),{refineGraduatedTiers:ol}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(Ub),{ApiFeatureMarkupsOverrideSchema:zb}=((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."})})}))(A,zu,$o),{AutoTopupPurchaseLimitParamsSchema:Yb}=((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."})})}))(rl,A),{DUPLICATE_CHECKS:Jb}=((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"})]}))(Lb,zg,Zo,Yg),{ApiPlanProcessorsSchema:Xb}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(A,tb,Bb),{FixedPriceConfigSchema:e_}=((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})}))(A,Dn,Xu,Ho,mb),{CreditDimensionSchema:t_}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(A,gb,Lu,el),{filterUnresolvableUsageLimitAlerts:n_}=((e,t,n)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:a})=>{let o=new Set(a.flatMap(s=>(s??[]).map(e)));return i.flatMap((s,c)=>t(s)&&!o.has(n(s))?[{index:c,usageAlert:s}]:[])}}))(Zo,Cb,Kb),{CreateRewardSchema:Nw}=((e,t,n,r,i,a)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(n).nullish(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(a).nullish()}).refine(s=>s.type!==n.FeatureGrant?!0:s.entitlements&&s.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(s=>s.type!==n.FeatureGrant?!0:s.promo_codes.some(c=>c.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(A,Vu,$u,tl,Hu,nl),{AutoTopupSchema:zo}=((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."})})}))(A,rl),{DbUsageLimitSchema:Yo}=((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."})})}))(A,Tb,Ku,il),{DbUsageAlertSchema:Jo}=((e,t,n,r,i)=>({DbUsageAlertSchema:e.object({feature_id:e.string().optional().meta({description:"The feature ID this alert applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage alert is enabled."}),threshold:e.number().min(0).meta({description:"The threshold value that triggers the alert. For usage or remaining, this is an absolute count. For usage_percentage or remaining_percentage, this is a percentage (0-100)."}),threshold_type:t.meta({description:"Whether the threshold is an absolute count or a percentage of the usage allowance or remaining balance."}),basis:n.default(r).meta({description:"What 100% means. balance: every grant on the feature. included: the plan allowance only. recurring: grants that reset. usage_limit: the cap of the usage limit with the same feature and filter."}),filter:i.optional().meta({description:"Only valid with basis usage_limit. Points the alert at the usage limit carrying the same filter."}),name:e.string().optional().meta({description:"Optional user-defined label to distinguish multiple alerts on the same feature."})}).check(o=>{let{feature_id:s,threshold_type:c,threshold:u,basis:l,filter:d}=o.value;c==="remaining_percentage"&&u>100&&o.issues.push({code:"custom",input:u,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),l==="usage_limit"&&!s&&o.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&l!=="usage_limit"&&o.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(A,Mg,Wb,Cu,il),{isValidCurrencyCode:r_}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Qb),{ApiCreditDimensionSchema:i_}=((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()])}))(A,Zb,ku,ol),{AutoTopupParamsSchema:a_}=((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."})})}))(zo,Yb),{findDuplicateBillingControlIssue:o_}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(Jb),{CustomerBillingControlsSchema:Xo}=((e,t,n,r,i,a)=>({CustomerBillingControlsSchema:e.object({auto_topups:e.array(t).optional().meta({description:"List of auto top-up configurations per feature."}),spend_limits:e.array(n).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(r).optional().meta({description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:e.array(i).optional().meta({description:"List of usage alert configurations per feature."}),overage_allowed:e.array(a).optional().meta({description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})})}))(A,zo,Wo,Yo,Jo,Mo),{PriceSchema:s_}=((e,t,n,r,i,a)=>({PriceSchema:e.object({id:e.string(),internal_product_id:e.string().nullable(),org_id:e.string().optional(),created_at:e.number().optional(),billing_type:e.nativeEnum(t).nullish(),tier_behavior:e.nativeEnum(n).nullish(),is_custom:e.boolean().optional(),config:r.or(i),entitlement_id:e.string().nullish(),proration_config:a.nullable()})}))(A,db,li,e_,Gb,fb),{CreditSchemaItemBaseSchema:sl}=((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()})}))(A,Qu,t_,_b),{GraduatedCreditSchemaItemSchema:c_}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(sl,el),{UpdateProductSchema:Dw}=((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()})}))(A,ma,Xo),{DbBillingControlsSchema:u_}=((e,t,n,r,i,a)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(n).nullish(),usage_limits:e.array(r).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(a).nullish()})}))(A,zo,Wo,Yo,Jo,Mo),{CurrencyCodeSchema:cl}=((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')."})}))(A,r_),{AdditionalCurrencyTierSchema:l_}=((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"]})}))(A,cl),{ApiCreditSchemaItemBaseSchema:ul}=((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."})})}))(A,Qu,i_,Fb),{ApiFlatCreditSchemaItemSchema:d_}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(ul,A),{rejectDuplicateBillingControls:m_}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(o_),{FlatCreditSchemaItemSchema:p_}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(sl,Lu),{ProductSchema:f_}=((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(()=>({}))})}))(A,aa,ma,u_,Ar),{AdditionalCurrencyPriceSchema:h_}=((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."})})}))(A,cl),{AdditionalCurrencyTierArraySchema:ll}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(A,l_,Ou,Eu),{ApiGraduatedCreditSchemaItemSchema:g_}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(ul,A,ku,ol),{CustomerBillingControlsParamsSchema:fa}=((e,t,n,r,i,a,o,s)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:n,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:r,description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:t({schema:i,description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:t({schema:a,description:"List of usage alert configurations per feature."}),overage_allowed:t({schema:o,description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})}).check(s)}))(A,Qg,a_,Wo,Yo,Jo,Mo,m_),{CreditSchemaItemSchema:b_}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(A,p_,c_),{PriceTierSchema:__}=((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}))}))(A,Ib,ll),{PlanBillingControlsParamsSchema:y_}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(r=>{let i=t({usageAlerts:r.value.usage_alerts??[],usageLimitLists:[r.value.usage_limits??[]]});for(let{index:a,usageAlert:o}of i)r.issues.push({code:"custom",message:`No usage limit on this plan matches the usage_limit alert for feature ${o.feature_id}`,input:o,path:["usage_alerts",a,"basis"]})})}))(fa,n_),{AdditionalCurrencyPriceArraySchema:mi}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(A,h_,Ou,Eu),{ApiUsageTierWithCurrenciesSchema:dl}=((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()}))}))(A,oa,ll),{ApiCreditSchemaItemSchema:S_}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(A,g_,d_),{FeatureConfigOverrideSchema:ml}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(A,b_,Hb),{ProductItemConfigSchema:x_}=((e,t,n,r,i,a,o)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:a.nullish(),feature_override:o.nullish()})}))(A,Fu,ca,ua,Mu,pa,ml),{BasePriceParamsSchema:ha}=((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."})}))(Nb,ui,A,mi),{PlanItemPriceParamsSchema:v_}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(A,mi,dl,li,Dn,sa,Wu),{ApiFeatureOverrideSchema:pl}=((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."})})}))(A,S_,zb),{ApiPlanItemV1Schema:I_}=((e,t,n,r,i,a,o,s,c,u,l,d,m,g,p,h,x)=>({ApiPlanItemV1Schema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature this item configures."}),feature:t.optional().meta({description:"The full feature object if expanded."}),included:e.number().meta({description:"Number of free units included. For consumable features, balance resets to this number each interval."}),unlimited:e.boolean().meta({description:"Whether the customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"The interval at which the feature balance resets (e.g. 'month', 'year'). For consumable features, usage resets to 0 and included units are restored."}),interval_count:e.number().optional().meta({description:"Number of intervals between resets. Defaults to 1."})}).nullable().meta({description:"Reset configuration for consumable features. Null for non-consumable features like seats where usage persists across billing cycles."}),price:e.object({amount:e.number().optional().meta({description:"Price per billing_units after included usage is consumed. Mutually exclusive with tiers."}),additional_currencies:r.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers' (tiered prices carry per-currency amounts on each tier)."}),tiers:e.array(i).optional().meta({description:"Tiered pricing configuration. Each tier's 'to' INCLUDES the included amount. Either 'tiers' or 'amount' is required."}),tier_behavior:e.enum(a).optional(),interval:e.enum(o).meta({description:"Billing interval for this price. For consumable features, should match reset.interval."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().meta({description:"Number of units per price increment. Usage is rounded UP to the nearest billing_units when billed (e.g. billing_units=100 means 101 usage rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:c,max_purchase:e.number().nullable().meta({description:"Maximum units a customer can purchase beyond included. E.g. if included=100 and max_purchase=300, customer can use up to 400 total before usage is capped. Null for no limit."}),processors:u.optional().meta({description:"Payment processors this item price is connected to. Omitted when unset."})}).nullable().meta({description:"Pricing configuration for usage beyond included units. Null if feature is entirely free."}),display:l.optional().meta({description:"Display text for showing this item in pricing pages."}),rollover:e.object({max:e.number().nullable().meta({description:"Maximum rollover units. Null for unlimited rollover."}),max_percentage:e.number().nullable().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(d).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover configuration for unused units. If set, unused included units roll over to the next period."}),proration:e.object({on_increase:e.enum(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(v=>{let j=v.value.reset?.interval,T=v.value.price?.interval,P=v.value.reset?.interval_count??1,_e=v.value.price?.interval_count??1;if(j&&T&&(String(j)!==String(T)||P!==_e)&&v.value.price?.billing_method!==s.Prepaid&&v.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:v.value}),v.value!==void 0&&v.value.price!==void 0&&v.value.price!==null){v.value.price.amount&&v.value.price.tiers&&v.value.price.tiers.length>0&&v.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:v.value});for(let Ze of x(v.value.price))v.issues.push({code:"custom",message:Ze,input:v.value.price})}})}))(A,Ju,ci,mi,dl,li,Dn,sa,Wu,Yu,Lo,qo,ca,ua,pa,pl,Nu),{EntitlementSchema:A_}=((e,t,n,r,i,a)=>({EntitlementSchema:e.object({id:e.string(),created_at:e.number(),internal_feature_id:e.string(),internal_product_id:e.string().nullable(),internal_reward_id:e.string().nullish(),is_custom:e.boolean().default(!1),allowance_type:e.nativeEnum(t).optional().nullable(),allowance:e.number().nullish(),interval:e.nativeEnum(n).optional().nullable(),interval_count:e.number().default(1),carry_from_previous:e.boolean().default(!1).optional(),entity_feature_id:e.string().nullish(),pooled:e.boolean().default(!1).optional(),org_id:e.string().optional(),feature_id:e.string().optional(),usage_limit:e.number().nullable().optional().default(null),expiry_duration:e.nativeEnum(r).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:a.nullish()})}))(A,hb,Uu,Ru,Mu,ml),{ProductItemSchema:fl}=((e,t,n,r,i,a,o,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(A,yb,Sb,Ju,oa,xb,vb,__,mi,li,x_),{ProductV2Schema:hl}=((e,t,n,r,i,a,o)=>({ProductV2Schema:e.object({internal_id:e.string().nullish(),id:e.string(),name:e.string(),description:e.string().nullish(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number().default(1),version_slug:e.string().nullable().optional(),active:e.boolean().optional(),group:e.string().nullable(),env:e.nativeEnum(t),free_trial:n.nullish(),items:e.array(r),created_at:e.number(),stripe_id:e.string().nullish(),archived:e.boolean().default(!1).nullish(),base_internal_product_id:e.string().nullish(),base_id:e.string().nullish(),config:i.partial().optional(),billing_controls:a.optional(),metadata:o.optional()})}))(A,aa,Pb,fl,ma,Xo,Ar),{PlanItemParamsObjectSchema:P_}=((e,t,n,r,i,a,o,s,c,u,l)=>({PlanItemParamsObjectSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature to configure."}),included:t.optional().meta({description:"Number of free units included. Balance resets to this each interval for consumable features."}),unlimited:e.boolean().optional().meta({description:"If true, customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:r({schema:e.number().optional(),defaultValue:1,description:"Number of intervals between resets. Defaults to 1."})}).optional().meta({description:"Reset configuration for consumable features. Omit for non-consumable features like seats."}),price:i.optional().meta({description:a}),proration:e.object({on_increase:e.enum(o).meta({description:"Billing behavior when quantity increases mid-cycle."}),on_decrease:e.enum(s).meta({description:"Credit behavior when quantity decreases mid-cycle."})}).optional().meta({description:"Proration settings for prepaid features. Controls mid-cycle quantity change billing."}),rollover:e.object({max:e.number().optional().meta({description:"Max rollover units. Omit for unlimited rollover."}),max_percentage:e.number().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(c).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover config for unused units. If set, unused included units carry over."}),expiry:u.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:l.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})})}))(A,Bo,ci,ui,v_,$g,ca,ua,qo,pa,pl),{FullProductWithoutLicensesSchema:Uw}=((e,t,n,r,i,a)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(n),entitlements:t.array(r.extend({feature:i})),free_trial:a.nullish(),free_trials:t.array(a).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(f_,A,s_,A_,$b,lb),{CreateProductItemParamsSchema:gl}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))(fl,Bo,A,oa),{CreatePlanItemParamsV1Schema:es}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(r=>{for(let{message:i,input:a}of t(r.value))r.issues.push({code:"custom",message:i,input:a})}).meta({title:"PlanItem",description:"Configuration for a feature item in a plan, including usage limits, pricing, and rollover settings."})}))(P_,Mb),{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()})}))(A,ha,es,Go),{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()})}))(A,bl),{UpdateProductV2ParamsSchema:Fw}=((e,t,n,r,i,a,o,s,c)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:n.id}),name:e.string().refine(l=>l.length>0,{message:"name must be a non-empty string"}).optional().meta({description:n.name}),is_add_on:e.boolean().optional().meta({description:n.is_add_on}),is_default:e.boolean().optional().meta({description:n.is_default}),base_plan_id:e.string().nonempty().regex(t).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."}),description:e.string().nullish().optional().meta({description:n.description}),group:e.string().nonempty().nullable().optional().meta({description:n.group}),archived:e.boolean().optional().meta({description:n.archived}),items:e.array(r).optional(),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata})})}))(A,da,Bu,gl,ts,qu,Ko,fa,Ar),{CreatePlanParamsV1Schema:C_}=((e,t,n,r,i,a,o,s,c)=>({CreatePlanParamsV1Schema:e.object({id:e.string().nonempty().regex(t).meta({description:"Unique identifier for the plan."}),group:e.string().default("").meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),name:e.string().nonempty().meta({description:"Display name of the plan."}),description:e.string().nullable().default(null).meta({description:"Optional description of the plan."}),add_on:e.boolean().default(!1).meta({description:"If true, this plan can be attached alongside other plans. Otherwise, attaching replaces existing plans in the same group."}),auto_enable:e.boolean().default(!1).meta({description:"If true, plan is automatically attached when a customer is created. Use for free tiers."}),price:n.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(r).optional().meta({description:"Feature configurations for this plan. Each item defines included units, pricing, and reset behavior."}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.optional().meta({description:"Free trial configuration. Customers can try this plan before being charged."}),config:o.optional().meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:"Arbitrary key-value metadata defined by you for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Shared across all versions of the plan."}),create_in_stripe:e.boolean().default(!0).meta({internal:!0})})}))(A,da,ha,es,ts,Qo,Ko,y_,Ar),{UpdatePlanParamsV1Schema:Mw}=((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."})})}))(C_,A,ha,Qo,da),{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()})}))(A,bl),{CreateProductV2ParamsSchema:Lw}=((e,t,n,r,i,a,o,s,c,u)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:n.id}),name:e.string().refine(d=>d.length>0,{message:"name must be a non-empty string"}).meta({description:n.name}),description:e.string().nullish().meta({description:n.description}),is_add_on:e.boolean().default(!1).meta({description:n.is_add_on}),is_default:e.boolean().default(!1).meta({description:n.is_default}),group:e.string().nullable().default("").meta({description:n.group}),items:e.array(r).optional().meta({description:n.items}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().default(null).meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata}),create_in_stripe:e.boolean().optional().meta({internal:!0}),archived:e.boolean().optional().meta({internal:!0}),base_internal_product_id:e.string().nullable().optional().meta({internal:!0})}).meta({examples:[u]})}))(A,da,Bu,gl,ts,qu,Ko,fa,Ar,Ab),{CustomizePlanV1BaseSchema:_l}=((e,t,n,r,i,a,o,s,c)=>({CustomizePlanV1BaseSchema:e.object({price:t.nullable().optional().meta({description:"Override the base price of the plan. Pass null to remove the base price."}),items:e.array(n).optional().meta({description:"Override the items in the plan (PUT-style \u2014 replaces all existing items). Mutually exclusive with add_items / remove_items / deprecated update_items."}),add_items:e.array(n).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(r).optional().meta({description:"Filters selecting items to remove from the plan."}),update_items:e.array(i).optional().meta({description:"Deprecated. Use remove_items and add_items to replace matched plan items.",internal:!0,deprecated:!0}),free_trial:a.nullable().optional().meta({description:"Override the plan's default free trial. Pass an object to set a custom trial, or null to remove the trial entirely."}),billing_controls:o.optional().meta({description:"Override the plan's billing controls (auto top-ups, spend limits, usage limits, usage alerts, overage allowed) for this customer."}),upsert_licenses:e.array(s).optional().meta({description:"License links to add or override for this customer, keyed by license_plan_id. Omitted fields inherit the plan catalog link (included defaults to 1 when the license is not in the catalog). A bare entry restores the license to pure catalog inheritance."}),remove_licenses:e.array(c).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(A,ha,es,Go,Wg,Qo,fa,ns,Jg),{VariantCustomizeSchema:w_}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(al,_l),{DiffedCustomizePlanV1Schema:Bw}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(al,_l),{ApiPlanV1Schema:qw}=((e,t,n,r,i,a,o,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(a).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:o.optional().meta({description:"Payment processors this plan is connected to. Omitted when unset."}),free_trial:s.optional().meta({description:"Free trial configuration. If set, new customers can try this plan before being charged."}),created_at:e.number().meta({description:"Unix timestamp (ms) when the plan was created."}),env:e.enum(c).meta({description:"Environment this plan belongs to ('sandbox' or 'live')."}),archived:e.boolean().meta({description:"Whether the plan is archived. Archived plans cannot be attached to new customers."}),config:u.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:l.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility: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."})})}))(A,mi,Dn,Lo,Yu,I_,Xb,qb,aa,ma,Xo,Ar,Vb,w_);import{z as w}from"zod";var O_=w.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),xl=w.enum(["single_use","continuous_use"]),rs=w.record(w.string(),w.union([w.string(),w.number(),w.boolean()]).transform(String).pipe(w.string())),yl=w.string().min(1).max(64).refine(e=>!e.includes("::")),vl={credit_amount:w.number(),tier_behavior:w.never().optional(),tiers:w.never().optional()},Il={credit_amount:w.never().optional(),tier_behavior:w.literal("graduated"),tiers:w.array(w.strictObject({to:w.union([w.number(),w.literal("inf")]),credit_amount:w.number()}))},E_=w.union([w.strictObject({match:rs,priority:w.number().int().optional(),...vl}),w.strictObject({match:rs,priority:w.number().int().optional(),...Il})]),T_=w.strictObject({match:rs,factor:w.number().positive().optional(),add:w.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Sl={metered_feature_id:w.string(),feature_amount:w.number().optional(),dimensions:w.record(yl,E_).optional(),multipliers:w.record(yl,T_).optional()},is=w.union([w.strictObject({...Sl,...vl}),w.strictObject({...Sl,...Il})]),ba=w.number().min(-100),Al=w.record(w.string(),w.strictObject({markup:ba})).nullish(),_a=w.record(w.string().regex(/.+\/.+/),w.strictObject({markup:ba.optional(),input_cost:w.number().min(0).optional(),output_cost:w.number().min(0).optional()})).nullish(),R_=w.strictObject({default_markup:ba.optional(),provider_markups:Al,model_markups:_a}),as=w.strictObject({schema:w.array(is).optional(),markups:R_.optional()}),k_=w.strictObject({filters:w.array(w.strictObject({property:w.string(),operator:w.string(),value:w.array(w.string())})),aggregate:w.strictObject({type:w.string(),property:w.string().nullable()}),usage_type:xl}),Pl=w.strictObject({schema:w.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:w.boolean().optional(),usage_type:xl.default("single_use").overwrite(()=>"single_use"),default_markup:ba.optional(),provider_markups:Al}),os=Pl.safeExtend({schema:w.array(is).length(0)}),ga={id:O_,name:w.string().min(1),display:w.strictObject({singular:w.string().optional(),plural:w.string().optional()}).nullish(),event_names:w.array(w.string()).default([]),model_markups:_a,stripe_meter:w.strictObject({id:w.string(),event_name:w.string()}).nullish(),stripe_product_id:w.string().nullish()},ss=e=>w.discriminatedUnion("type",[w.strictObject({...ga,...e,type:w.literal("boolean"),config:w.null()}),w.strictObject({...ga,...e,type:w.literal("metered"),config:k_}),w.strictObject({...ga,...e,type:w.literal("credit_system"),config:Pl}),w.strictObject({...ga,...e,type:w.literal("ai_credit_system"),config:os})]),Gw=ss({}),j_=w.strictObject({id:w.boolean(),type:w.boolean(),usage_type:w.boolean()}),N_={internal_id:w.uuid(),org_id:w.uuid(),created_at:w.number(),env:w.enum(["sandbox","live"]),archived:w.boolean(),project_id:w.uuid(),environment_id:w.uuid(),revision:w.number().int().nonnegative(),update_rules:j_},Cl=ss(N_),Hw=w.strictObject({rows:w.array(Cl).max(200),nextCursor:w.uuid().nullable()}),wl=w.strictObject({features:w.array(Cl).max(500),limited:w.boolean()}),Kw=w.union([ss({action:w.literal("save"),internal_id:w.uuid().nullable(),revision:w.number().int().nonnegative()}),w.strictObject({action:w.enum(["archive","restore","delete"]),internal_id:w.uuid(),revision:w.number().int().nonnegative()})]);import{z as Pr}from"zod";var Ol=Pr.number().int().min(0).max(1e8),pi=Pr.strictObject({kind:Pr.enum(["graduated","volume"]),tiers:Pr.array(Pr.strictObject({upTo:Pr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ol,flatAmountMinor:Ol.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?pi.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function ya(e){return cs({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as k}from"zod";import{z as G}from"zod";import{z as hn}from"zod";import{z as D_}from"zod";var Un=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],Q=D_.enum(Un);function nr(e){let t=Q.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function Yw(e,t){let n=nr(t),r=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!r?.[1]||(r[2]?.length??0)>n)throw new Error("Amount has invalid currency precision");let i=BigInt(r[1])*BigInt(10**n)+BigInt((r[2]??"").padEnd(n,"0")||"0");if(i>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Amount exceeds the supported range");return Number(i)}function Jw(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=nr(t),r=String(e).padStart(n+1,"0");return n?`${r.slice(0,-n)}.${r.slice(-n)}`:r}function El(e,t,n="en",r={}){let i=Q.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**nr(i))}import{z as Pn}from"zod";var nO={plans:Un,creditPacks:Un,paidSeats:Un,postpaid:Un},Tl=Pn.partialRecord(Pn.enum(Un),Pn.number().int().min(1).max(1e8)),U_=Pn.strictObject({currency:Pn.enum(Un),automaticTax:Pn.boolean()}),F_=Pn.strictObject({projectId:Pn.uuid(),environmentId:Pn.uuid()}),rO=F_.extend({settings:U_});var M_=hn.string().regex(/^[a-z][a-z0-9_]{0,63}$/),Rl=hn.number().int().min(0).max(1e4),us=hn.object({key:M_,featureId:hn.uuid(),planVersionId:hn.uuid(),includedQuantity:Rl,maximumQuantity:Rl,unitAmountCents:hn.number().int().min(0).max(1e8),currency:Q,currencyOptions:Tl.optional(),stripePriceId:hn.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:hn.array(hn.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:hn.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 pt}from"zod";import{z as We}from"zod";var ut=We.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Y=We.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Sa=We.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),ls=Y.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),kl=We.string().min(1).max(64),en=We.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),jl=We.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Xe=We.record(kl,We.union([We.string().max(120),We.number().finite(),We.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),Nl=We.record(kl,We.union([We.string().max(120),We.number().finite(),We.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Cr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},Dl=We.array(We.object({upTo:ls.nullable(),cost:Y}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Cr(t.upTo)>Cr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),L_=We.object({key:jl,match:Nl,priority:We.number().int().default(0),cost:Y.optional(),tiers:Dl.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),B_=We.object({key:jl,match:Nl,factor:ls.optional(),add:Sa.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),q_=We.object({units:ls.default("1"),cost:Y,tiers:Dl.optional(),dimensions:We.array(L_).max(12).optional(),multipliers:We.array(B_).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(o=>o.key)).size!==n.length||new Set(r.map(o=>o.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[o,s]of n.entries())for(let c of n.slice(o+1))Object.keys(s.match).length===Object.keys(c.match).length&&s.priority===c.priority&&!Object.keys(s.match).some(u=>c.match[u]!==void 0&&c.match[u]!==s.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(o=>o.cost),...n.flatMap(o=>[...o.cost===void 0?[]:[o.cost],...(o.tiers??[]).map(s=>s.cost)])],a=Cr(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((p,h)=>s&1<<h);if(c.some((p,h)=>c.slice(h+1).some(x=>Object.keys(p.match).some(I=>x.match[I]!==void 0&&x.match[I]!==p.match[I]))))continue;let u=Cr(o),l=BigInt("1"),d=BigInt("0");for(let[p,h]of r.entries())s&1<<p&&(u*=Cr(h.factor??"1"),l*=BigInt("1000000"),d+=Cr(h.add??"0"));let m=(u+d*l)*BigInt("1000000"),g=l*a;(m<BigInt("0")||m%g!==BigInt("0")||m/g>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),lO=q_.safeExtend({featureKey:en});var ds=pt.object({days:pt.number().int().min(1).max(730),cardRequired:pt.boolean(),featureAllowances:pt.record(pt.uuid(),pt.number().int().min(0).max(1e9)),creditAmounts:pt.record(pt.uuid(),Y)}).strict(),ms=pt.object({id:pt.uuid(),planVersionId:pt.uuid(),slot:pt.string(),cardRequired:pt.boolean(),status:pt.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:pt.iso.datetime().nullable(),endsAt:pt.iso.datetime().nullable(),createdAt:pt.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(),V_=Ce.enum(["immediate","end_of_cycle"]),$_=Ce.enum(["attach","change","cancel","resume","cancel_change"]),Ul=Ce.object({id:Ce.uuid(),subscriptionId:Ce.uuid().nullable(),targetPlanVersionId:Ce.uuid().nullable(),action:$_,timing:V_,status:Ce.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:Ce.iso.datetime().nullable(),createdAt:Ce.iso.datetime()}),G_=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:Ul.nullable(),trial:ms.nullable().optional()}),bO=Ce.object({customerId:Ce.uuid(),evaluatedAt:Ce.iso.datetime(),holdings:Ce.array(G_),changes:Ce.array(Ul),trials:Ce.array(ms).optional()});var gn=G.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"),PO=G.record(G.string().min(1).max(80),G.union([G.string().max(500),G.number().finite(),G.boolean(),G.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),Fl=G.object({key:gn,name:G.string().trim().min(1).max(80),description:G.string().trim().max(240),type:G.enum(["boolean","metered"]),usageType:G.enum(["consumable","non_consumable"]).optional()}),CO=Fl.extend({...$e.shape,id:G.string().min(1),archived:G.boolean(),createdAt:G.iso.datetime()}),Ml=G.object({amountCents:G.number().int().min(0).max(1e8),currency:Q,interval:G.enum(["free","month","year"]),currencyOptions:G.partialRecord(Q,G.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"),H_=G.object({featureId:G.string().min(1),allowance:G.number().int().min(0).max(1e9).nullable(),pooled:G.boolean().optional()}),Ll=G.object({name:G.string().trim().min(1).max(80),description:G.string().trim().max(240),price:Ml,membership:ps.optional(),trial:ds.nullable().optional(),licenses:G.array(us).max(20).optional(),items:G.array(H_).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")}),wO=G.object({key:gn,config:Ll}),OO=$e.extend({id:G.string().min(1),key:gn,draft:Ll,status:G.enum(["draft","published","archived"]),publishedVersionId:G.string().nullable(),isDefault:G.boolean(),updatedAt:G.iso.datetime()}),K_=Fl.pick({key:!0,name:!0,type:!0}).extend({featureId:G.string(),allowance:G.number().int().min(0).max(1e9).nullable(),pooled:G.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"),Bl=$e.extend({id:G.string().min(1),planId:G.string().min(1),variant:G.object({basePlanId:G.uuid(),baseVersionId:G.uuid()}).nullable(),version:G.number().int().positive(),name:G.string(),description:G.string(),price:Ml,membership:ps.optional(),trial:ds.nullable().optional(),licenses:G.array(us).optional(),items:G.array(K_),publishedAt:G.iso.datetime()}).strict(),fs=G.object({startsAt:G.iso.datetime(),endsAt:G.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"),EO=$e.extend({id:G.string(),customerId:G.string(),planVersionId:G.string(),assignedAt:G.iso.datetime(),source:G.literal("demo"),validity:fs.nullable().default(null),used:G.record(G.string(),G.number().int().min(0))}),TO=$e.extend({id:G.string(),customerId:G.string(),at:G.iso.datetime(),message:G.string()});import{z as b}from"zod";import{z as se}from"zod";import{z as W_}from"zod";var Vl=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,tn=W_.string().max(16).regex(Vl,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");function rr(e){if(typeof e!="string")return null;try{let t=Intl.getCanonicalLocales(e.trim().replaceAll("_","-"))[0];if(!t)return null;let{language:n,script:r,region:i}=new Intl.Locale(t),a=[n,r,i].filter(Boolean).join("-");return Vl.test(a)?a:null}catch{return null}}var Q_=new Set(["TW","HK","MO"]);function ql(e){let[t,n,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let i=n?.length===4?n:void 0,a=n?.length===4?r:n;return i?`zh-${i}`:a&&Q_.has(a)?"zh-Hant":"zh-Hans"}function xa(e,t,n){let r=t.map(i=>({code:tn.parse(i),normalized:i}));for(let i of e){let a=rr(i);if(!a)continue;let o=r.find(l=>l.normalized===a);if(o)return o.code;let s=ql(a),c=r.filter(l=>ql(l.normalized)===s),u=c.find(l=>!l.normalized.includes("-")||l.normalized===s)??c[0];if(u)return u.code}return n}var Z_=[{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u53F0\u7063\uFF09"},{code:"zh-HK",label:"\u7E41\u9AD4\u4E2D\u6587\uFF08\u9999\u6E2F\uFF09"},{code:"en",label:"English"},{code:"ja",label:"\u65E5\u672C\u8A9E"},{code:"ko",label:"\uD55C\uAD6D\uC5B4"},{code:"es",label:"Espa\xF1ol"},{code:"fr",label:"Fran\xE7ais"},{code:"de",label:"Deutsch"},{code:"pt-BR",label:"Portugu\xEAs (Brasil)"},{code:"it",label:"Italiano"},{code:"ru",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"vi",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"th",label:"\u0E44\u0E17\u0E22"},{code:"id",label:"Bahasa Indonesia"},{code:"ar",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629"}];function jO(e){return Z_.find(t=>t.code===e)?.label??e}var $l={"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"}},FO=["zh-CN","zh-TW","zh-HK","en","ja","ko","es","fr","de","pt-BR","it","ru","vi","th","id","ar"];function hs(e){let t=rr(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",i=$l[r];return i?{locale:t,copy:i}:{locale:"en",copy:$l.en}}function z_(e,t,n="zh-CN"){let r=nr(t);return El(e,t,hs(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function Y_(e,t="zh-CN"){let n=hs(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e.percentOff/100):z_(e.amountOffCents,e.currency,n)}var Gl={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 Hl(e,t="zh-CN",n="month"){let r=hs(t),i=Y_(e.discount,r.locale),a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",o=r.locale.split("-")[0]??"en",s=o==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":o,c=e.duration.type==="repeating"&&n!=="month"?Gl[s]??Gl.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],u=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return c.replace("{discount}",i).replace("{months}",a).replace("{period}",u)}var $O=se.enum(["draft","active","paused","archived"]),wr=se.discriminatedUnion("type",[se.object({type:se.literal("percent"),percentOff:se.number().int().min(1).max(100)}).strict(),se.object({type:se.literal("amount"),amountOffCents:se.number().int().min(1).max(1e8),currency:Q}).strict()]),nn=se.discriminatedUnion("type",[se.object({type:se.literal("once")}).strict(),se.object({type:se.literal("repeating"),months:se.number().int().min(1).max(36)}).strict(),se.object({type:se.literal("forever")}).strict()]),Kl=se.discriminatedUnion("type",[se.object({type:se.literal("all")}).strict(),se.object({type:se.literal("plans"),planIds:se.array(se.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),J_=se.strictObject({firstPurchaseOnly:se.boolean(),condition:Nn}),Wl=se.object({name:se.string().trim().min(1).max(80),description:se.string().max(500),discount:wr,duration:nn,appliesTo:Kl,eligibility:J_,startsAt:se.iso.datetime().nullable(),endsAt:se.iso.datetime().nullable(),totalLimit:se.number().int().min(1).max(1e6).nullable(),perCustomerLimit:se.number().int().min(1).max(10),grantWindowHours:se.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"]}),GO=se.object({code:se.string().trim().transform(e=>e.toUpperCase()).pipe(se.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:se.number().int().min(1).max(1e6).nullable(),expiresAt:se.iso.datetime().nullable(),firstPurchaseOnly:se.boolean(),minimumAmountCents:se.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:Q.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function HO(){return{name:"\u65B0\u4F18\u60E0\u5238",description:"",discount:{type:"percent",percentOff:20},duration:{type:"once"},appliesTo:{type:"all"},eligibility:{firstPurchaseOnly:!1,condition:{}},startsAt:null,endsAt:null,totalLimit:null,perCustomerLimit:1,grantWindowHours:72}}var gs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function KO(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return gs(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),gs(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),gs(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 X_=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function WO(e,t="zh-CN"){return Hl(e,t)}function QO(e){return X_(e)}function ZO(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var fi=se.object({id:se.uuid(),couponId:se.uuid(),status:se.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:se.iso.datetime(),expiresAt:se.iso.datetime(),coupon:se.object({name:se.string(),discount:wr,duration:nn,appliesTo:Kl}).strict()}).strict(),va=se.enum(["inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Jl=b.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),bs=b.string().regex(/^(0|[1-9]\d{0,14})$/),Or=b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),ey=b.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),hi=ey,Cn=Y.refine(e=>/[1-9]/.test(e)),xt=b.iso.datetime({offset:!0}),ir=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"))},ty=b.array(b.object({upTo:Cn.nullable(),unitAmountMinor:Jl,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&&ir(t.upTo)>ir(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),ny=b.discriminatedUnion("kind",[b.object({kind:b.literal("flat"),units:Cn,unitAmountMinor:Jl}).strict(),b.object({kind:b.enum(["graduated","volume"]),units:Cn,tiers:ty}).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"),ry=b.strictObject({interval:b.enum(["month","year"]),count:b.number().int().min(1).max(12),anchor:b.enum(["membership","calendar"])}),Fn=b.object({currency:Q,pricing:ny,billingCycle:ry.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function Xl(e){return e.pricing.kind==="flat"&&ir(e.pricing.units)>0n&&ir(e.pricing.unitAmountMinor)===ir(e.pricing.units)*BigInt(10**nr(e.currency))}var Ql={requestId:b.uuid(),productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:Q},ed=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)}),td=b.discriminatedUnion("kind",[b.object({...Ql,kind:b.literal("auto_topup"),threshold:Sa,quantity:Cn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:ed.optional()}).strict(),b.object({...Ql,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:hi,maxOutstandingMinor:hi}).strict()]),Zl={productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:Q},nd=b.discriminatedUnion("kind",[b.object({...Zl,kind:b.literal("auto_topup"),threshold:Sa,quantity:Cn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:ed.optional(),purchaseAmountMinor:hi,purchaseUnits:Cn}).strict(),b.object({...Zl,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:hi,maxOutstandingMinor:hi,cashPrice:Fn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Ia=b.object({id:b.uuid(),terms:nd,status:b.enum(["prepared","active","revoked","blocked"]),createdAt:xt,acceptedAt:xt.nullable(),effectiveAt:xt.nullable(),revokedAt:xt.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"),rd=b.object({authorizationId:b.uuid(),terms:nd,setupUrl:b.url().nullable()}).strict(),id=b.object({authorizationId:b.uuid(),accepted:b.literal(!0)}).strict(),ad=b.object({authorizationId:b.uuid(),requestId:b.uuid()}).strict(),od=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:Xe.optional(),limit:Y.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(Cn).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&&ir(t)>ir(i)}),"Notification thresholds must increase"),iy=od.safeExtend({requestId:b.uuid()}),zl={control:b.literal("overage"),requestId:b.uuid(),internal_feature_id:b.uuid(),entityId:b.uuid().nullable()},ay=b.discriminatedUnion("action",[b.strictObject({...zl,action:b.literal("set"),allowed:b.boolean().nullable(),overageLimit:Y.nullable(),skipOverageBilling:b.boolean()}),b.strictObject({...zl,action:b.literal("remove")})]),sd=b.union([iy,ay]),oy=b.strictObject({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),allowed:b.boolean().nullable(),overageLimit:Y.nullable(),skipOverageBilling:b.boolean(),interval:b.enum(["day","week","month","year"]),startsAt:xt,endsAt:xt,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()}),sy=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:Xe.optional(),startsAt:xt,endsAt:xt,used:ut,reserved:ut,limit:Y.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(Cn).max(8).optional(),notifiedAbsoluteThresholds:b.array(Cn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Y.safeParse(e.used).success&&Y.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),cy=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:xt.nullable(),attemptCount:b.number().int().nonnegative(),failedAttemptCount:b.number().int().nonnegative(),suspendedAt:xt.nullable(),nextAttemptAt:xt.nullable(),failureReason:b.string().min(1).max(240).nullable()}).strict(),cd=b.object({internal_feature_id:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),_s=b.object({authorizations:b.array(Ia).max(100),limits:b.array(od).max(100),overages:b.array(oy).max(100).optional(),windows:b.array(sy).max(200),autoTopups:b.array(cy).max(100),limited:b.boolean()}).strict(),uy=b.object({id:b.uuid(),internal_feature_id:b.uuid(),productVersionId:b.uuid(),authorizationId:b.uuid(),entityId:b.uuid().nullable(),units:Y,amountMinor:Or,cashPrice:Fn}).strict(),gi=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:Q,startsAt:xt.nullable(),endsAt:xt.nullable(),amountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:bs,paidAmountMinor:bs,refundedAmountMinor:bs,createdAt:xt,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:xt.nullable()}).strict().nullable(),lines:b.array(uy).max(100),linesLimited:b.boolean()}).strict(),ud=b.object({invoiceId:b.uuid(),accepted:b.literal(!0)}).strict(),ld=b.object({after:b.uuid().nullable(),limit:b.number().int().min(1).max(100)}).strict(),dd=b.object({rows:b.array(gi).max(100),nextCursor:b.uuid().nullable()}).strict(),Yl=b.strictObject({id:b.string(),coupon:b.string(),start:b.number().nonnegative(),end:b.number().nullable()}),ly=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(Yl).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:Yl.optional()})).max(20)})).max(100)}),md=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")}),pd=b.strictObject({membershipId:b.uuid(),operationId:b.uuid(),status:b.enum(["pending","effective"]),execution:ly.nullable(),grants:b.array(b.strictObject({id:b.uuid(),couponId:b.uuid(),name:b.string(),discount:wr,duration:nn,startedAt:xt.nullable()})).max(20)});import{z as bi}from"zod";var _i=bi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),yi=bi.number().int().min(1).max(1e3),ar=bi.object({cap:Y.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:bi.number().positive().max(1e4).nullable(),cycles:bi.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var ys={key:gn,name:k.string().trim().min(1).max(80),description:k.string().trim().max(240)},fd=Y.refine(e=>/[1-9]/.test(e)),Aa=k.array(k.object({currency:Q,amountMinor:k.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"),Ss=k.strictObject({units:fd,prices:k.array(k.strictObject({currency:Q,amountMinor:k.number().int().min(0).max(1e8),pricing:pi.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:k.number().int().min(0).max(1e4),maximumQuantity:k.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"),dy=k.discriminatedUnion("kind",[k.object({kind:k.literal("access"),internal_feature_id:k.uuid()}).strict(),k.object({kind:k.literal("metered"),internal_feature_id:k.uuid(),usageUnit:k.enum(["count","micro_usd"]),amount:Y.nullable(),reset:_i,resetCount:yi,pooled:k.boolean(),rollover:ar.nullable().optional(),cashPrice:Fn.nullable().optional(),prepaidPrice:Ss.optional(),feature_override:as.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"),k.object({kind:k.literal("credit"),internal_feature_id:k.uuid(),amount:Y,reset:_i,resetCount:yi,rollover:ar.nullable(),pooled:k.boolean(),feature_override:as.nullish(),cashPrice:Fn.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&Xl(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")]),xs=k.array(dy).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),hd=k.object({days:k.number().int().min(1).max(730),cardRequired:k.boolean(),allowances:xs}).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"),gd=k.object({key:gn,internal_feature_id:k.uuid(),productVersionId:k.uuid(),includedQuantity:k.number().int().min(0).max(1e4),maximumQuantity:k.number().int().min(0).max(1e4),prices:Aa,pooled_internal_feature_ids:k.array(k.uuid()).max(100),requireAssignment:k.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"),Si=k.discriminatedUnion("kind",[k.object({...ys,kind:k.literal("membership"),groupId:k.uuid(),membershipType:k.enum(["main","addon"]),interval:k.enum(["free","week","month","year","one_time"]),intervalCount:k.number().int().min(1).max(156).optional(),prices:Aa,allowances:xs,trial:hd.nullable(),licenses:k.array(gd).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"),k.object({...ys,kind:k.literal("topup"),interval:k.literal("one_time"),prices:Aa,internal_feature_id:k.uuid(),amount:fd,expiresDays:k.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),Pa=k.object({interval:k.enum(["free","week","month","year","one_time"]).optional(),intervalCount:k.number().int().min(1).max(156).nullable().optional(),prices:Aa.optional(),allowances:k.object({upsert:xs,remove:k.array(k.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:hd.nullable().optional(),licenses:k.array(gd).max(20).optional()}).strict(),bd=k.object({...ys,kind:k.literal("variant"),baseProductVersionId:k.uuid(),overrides:Pa}).strict(),fE=k.union([Si,bd]);function hE(e,t){let n=bd.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...a}=n.overrides,o=new Map(e.allowances.map(c=>[c.internal_feature_id,c]));for(let c of r?.remove??[])if(!o.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])o.delete(c.internal_feature_id);for(let c of r?.upsert??[])o.set(c.internal_feature_id,c);let s={...structuredClone(e),...structuredClone(a),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...o.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),Si.parse(s)}function gE(e,t){if(e.kind!=="membership"||t.kind!=="membership"||e.groupId!==t.groupId||e.membershipType!==t.membershipType)throw new Error("Variant group and membership type must match the base");let n={};for(let s of["interval","intervalCount","prices","trial","licenses"])(s==="intervalCount"&&["week","month","year"].includes(t.interval)?(e.intervalCount??1)===(t.intervalCount??1):JSON.stringify(e[s])===JSON.stringify(t[s]))||Object.assign(n,{[s]:s==="intervalCount"&&t[s]===void 0?null:structuredClone(t[s])});let r=new Map(e.allowances.map(s=>[s.internal_feature_id,s])),i=new Set(t.allowances.map(s=>s.internal_feature_id)),a=t.allowances.filter(s=>JSON.stringify(r.get(s.internal_feature_id))!==JSON.stringify(s)),o=e.allowances.filter(s=>!i.has(s.internal_feature_id)).map(s=>s.internal_feature_id);return(a.length||o.length)&&(n.allowances={upsert:a,remove:o}),Pa.parse(n)}var bE=k.object({products:k.array(k.object({id:k.uuid(),productId:k.string().min(1),name:k.string(),kind:k.enum(["membership","topup"]),version:k.number().int().positive()}).strict()).max(500),limited:k.boolean()}).strict(),my=hl.and(k.object({internal_id:k.uuid(),revision:k.number().int().nonnegative(),licenses:k.array(ns)})),_E=k.strictObject({rows:k.array(my).max(200),nextCursor:k.uuid().nullable()}),yE=k.object({groups:k.array(k.object({id:k.uuid(),name:k.string(),defaultProductVersionId:k.uuid().nullable()}).strict()).max(500),features:wl.shape.features,products:k.array(k.object({id:k.uuid(),productId:k.uuid(),version:k.number().int().positive(),configuration:Si,baseProductVersionId:k.uuid().nullable()}).strict()).max(500),limited:k.boolean()}).strict();function vs(e,t,n){let r=o=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(o))throw new Error("Invalid quantity");let[s,c=""]=o.split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return BigInt(s)*1000000n+BigInt(c.padEnd(6,"0"))};if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let i=r(e)+r(t)*BigInt(n);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let a=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(a?"."+a:"")}var IE=rn.object({requestId:rn.uuid(),baseProductVersionId:rn.uuid(),name:rn.string().trim().min(1).max(80),description:rn.string().trim().max(240),overrides:Pa}).strict(),AE=rn.object({productId:rn.uuid(),productVersionId:rn.uuid(),bindingStatus:rn.enum(["ready","requires_binding"]),missingCurrencies:rn.array(rn.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();import{z as at}from"zod";var xi=at.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),wE=at.enum([...xi.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),OE=at.enum([...xi.options,"stale_revision"]),py=at.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),fy=at.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),_d={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};function EE(e){return[400,405,415,422].includes(e)?"INVALID_REQUEST":e===401?"UNAUTHENTICATED":e===403?"FORBIDDEN":e===404?"NOT_FOUND":[409,412,425].includes(e)?"CONFLICT":e===413?"PAYLOAD_TOO_LARGE":e===429?"RATE_LIMITED":e===501?"NOT_CONFIGURED":[408,502,503,504].includes(e)?"SERVICE_UNAVAILABLE":"INTERNAL_ERROR"}function hy(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(["TIMEOUT","NETWORK_ERROR","HTTP_ERROR","INVALID_RESPONSE","INVALID_SERVER_RESPONSE"].includes(e))return{retryable:!1,recovery:"recover_operation"};if(e==="NOT_IDENTIFIED"||e==="INVALID_TOKEN")return{retryable:!1,recovery:"authenticate"};if(["INVALID_URL","INVALID_TIMEOUT","SERVER_ONLY","AMBIGUOUS_AUTHENTICATION"].includes(e))return{retryable:!1,recovery:"fix_request"};if(e==="PROTOCOL_MISMATCH")return{retryable:!1,recovery:"upgrade_sdk"};if(e==="IDENTITY_CHANGED")return{retryable:!1,recovery:"reload_state"};if(e==="CAPABILITY_UNAVAILABLE")return{retryable:!1,recovery:"check_availability"};let n=xi.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:_d[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function TE(e,t){let n=xi.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):_d[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function gy(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var yd=at.object({retryable:at.boolean(),recovery:py,reason:fy.optional(),retryAfterSeconds:at.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),by=at.object({requestId:at.uuid().optional(),error:at.object({code:at.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:at.string(),...yd.partial().shape})}),RE=at.object({error:by.shape.error.extend({requestId:at.uuid().optional()})}),kE=at.object({error:at.string(),code:at.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:at.uuid(),...yd.shape});function jE(e,t,n={}){let r=hy(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?gy(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var xd="X-Indiana-Protocol",_y="X-Indiana-SDK-Version",DE="X-Indiana-Supported-Protocols",Sd={stableSupportMonths:12,retirementNoticeDays:180,documentation:"/docs/release-notes#support-policy"},yy={current:"0.5",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:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]}]},vd=/^(?:0\.(?:0|[1-9]\d*)|[1-9]\d*)$/,Sy=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function Id(e){let t=Sy.exec(e);return!t?.[1]||!t[2]?null:t[1]==="0"?`0.${t[2]}`:t[1]}var As=e=>/^[1-9]\d*$/.test(e);function xy(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 Is=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 UE(e){let t=[],n=new Set;for(let r of e.releases){let i=r.protocol;(!vd.test(i)||n.has(i))&&t.push(`Invalid/duplicate protocol ${i}`),n.add(i),(r.firstReleasedAt===null?i!==e.current:!Is(r.firstReleasedAt))&&t.push(`${i}: invalid first release date`),r.noticePublishedAt!==null&&!Is(r.noticePublishedAt)&&t.push(`${i}: invalid notice date`),r.sunsetAt!==null&&!Is(r.sunsetAt)&&t.push(`${i}: invalid sunset date`),r.noticePublishedAt&&(!r.firstReleasedAt||Date.parse(r.noticePublishedAt)<Date.parse(r.firstReleasedAt))&&t.push(`${i}: notice predates release`),r.noticeUrl!==null&&!/^(?:https:\/\/[^\s<>]+|\/docs\/[\w/#.-]+)$/.test(r.noticeUrl)&&t.push(`${i}: invalid notice URL`),r.firstReleasedAt&&!r.baselines.length&&t.push(`${i}: missing published SDK baseline`),!r.firstReleasedAt&&r.baselines.length&&t.push(`${i}: unpublished current protocol cannot claim published baselines`);let a=new Set;for(let o of r.baselines)(Id(o.version)!==i||a.has(o.version))&&t.push(`${i}: invalid/duplicate baseline ${o.version}`),a.add(o.version),(!/^sha512-[A-Za-z0-9+/]{86}==$/.test(o.integrity)||!/^[a-f0-9]{64}$/.test(o.sha256))&&t.push(`${i}: unpinned baseline ${o.version}`);if(As(i)&&r.sunsetAt!==null){let o=e.releases.filter(s=>s.firstReleasedAt!==null&&As(s.protocol)&&Number(s.protocol)>Number(i)).sort((s,c)=>Date.parse(s.firstReleasedAt)-Date.parse(c.firstReleasedAt))[0];o?Date.parse(r.sunsetAt)<xy(o.firstReleasedAt,Sd.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)<Sd.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 or=class extends Error{constructor(n,r,i=400){super(r);this.code=n;this.status=i}code;status};function FE(e,t=yy,n=Date.now()){let r=e.get(xd)??t.unversioned;if(!vd.test(r))throw new or("INVALID_PROTOCOL_VERSION","Invalid Indiana protocol version");let i=t.releases.find(o=>o.protocol===r);if(!i)throw new or("UNSUPPORTED_PROTOCOL_VERSION","Indiana protocol version is not supported");if(!As(r)&&r!==t.current)throw new or("UNSUPPORTED_PROTOCOL_VERSION","Only the current pre-1.0 Indiana protocol is supported");if(i.sunsetAt&&n>=Date.parse(i.sunsetAt))throw new or("PROTOCOL_RETIRED","Indiana protocol version has retired; follow the published migration notice",410);let a=e.get(_y);if(a!==null&&Id(a)!==r)throw new or("INVALID_PROTOCOL_VERSION","SDK version and protocol version do not match");return i}function ME(e,t=Date.now()){let n={[xd]: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 Ge}from"zod";var vy=Ge.object({minAccountAgeDays:Ge.number().int().min(0).max(3650),paymentStatus:Ge.enum(["all","unpaid","paid"])}),Iy=Ge.object({percentOff:Ge.number().int().min(1).max(100),redemptionWindowHours:Ge.number().int().min(1).max(2160)}),Ay=Ge.object({title:Ge.string().trim().min(1).max(80),description:Ge.string().trim().min(1).max(240),buttonLabel:Ge.string().trim().min(1).max(30)}),Py=Ge.object({name:Ge.string().trim().min(1).max(80),audience:vy,offer:Iy,popup:Ay}),VE=Py.extend({id:Ge.string().min(1),projectId:Ge.string().min(1),environment:_u,status:Ge.enum(["draft","active","paused"]),updatedAt:Ge.iso.datetime()}),$E=$e.extend({id:Ge.string().min(1),externalUserId:Ge.string().min(1),name:Ge.string().min(1),email:Ge.union([Ge.email(),Ge.literal("")]),createdAt:Ge.iso.datetime(),paymentStatus:Ge.enum(["unpaid","paid"]),stripeCustomerId:Ge.string().nullable()});import{z as Mn}from"zod";var Ad=Mn.strictObject({itemKey:Mn.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:Mn.uuid(),includedAmount:Mn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Mn.number().int().min(0).max(1e4),terms:Ss,pricing:pi.optional(),unitAmountMinor:Mn.number().int().min(0).max(1e8),productId:Mn.string().min(1).max(255).nullable(),priceId:Mn.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),ya({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 Ps=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(),YE=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:Si}).strict()),connections:H.array(H.object({id:H.uuid(),accountId:H.string()}).strict()),bindings:H.array(Ps),seatBindings:H.array(Ps.extend({key:H.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:H.array(Ps.extend({internal_feature_id:H.uuid()}).strict()),limited:H.boolean()}).strict(),JE=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 be}from"zod";var Pd=be.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Cd=be.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),vi=be.enum(["apple","google"]),Cy=be.strictObject({id:be.uuid(),productVersionId:be.uuid(),priceId:be.uuid(),connectionId:vi,provider:vi,namespace:be.string().min(1).max(255),currency:Q,productId:Pd,basePlanId:Cd.nullable(),enabled:be.boolean()}),nT=be.strictObject({productId:be.uuid(),publicId:be.string().min(1),name:be.string().min(1).max(80),environment:be.enum(["sandbox","live"]),versions:be.array(be.strictObject({id:be.uuid(),version:be.number().int().positive(),prices:be.array(be.strictObject({id:be.uuid(),currency:Q,amount:be.number().nonnegative(),interval:be.string().nullable()})).max(50),recurring:be.boolean()})).max(100),connections:be.array(be.strictObject({id:vi,provider:vi,applicationId:be.string().min(1).max(255)})).max(2),bindings:be.array(Cy).max(500),limited:be.boolean()}),rT=be.discriminatedUnion("action",[be.strictObject({action:be.literal("bind"),requestId:be.uuid(),productId:be.uuid(),productVersionId:be.uuid(),priceId:be.uuid(),connectionId:vi,storeProductId:Pd,basePlanId:Cd.nullable()}),be.strictObject({action:be.literal("disable"),productId:be.uuid(),bindingId:be.uuid()})]);import{z as $}from"zod";var sr=Y.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Ii=$.string().min(1).max(120),Ca=$.enum(["cap","overflow"]),Ut=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Ai=e=>{try{return e()}catch{return!1}},Pi=$.discriminatedUnion("operation",[$.object({operation:$.literal("quote"),overageBehavior:Ca.optional(),internal_feature_id:$.uuid(),entityId:$.uuid().optional(),quantity:sr,properties:Xe}).strict(),$.object({operation:$.literal("consume"),overageBehavior:Ca.optional(),occurredAt:$.iso.datetime({offset:!0}).optional(),internal_feature_id:$.uuid(),entityId:$.uuid().optional(),quantity:Y,properties:Xe,idempotencyKey:Ii}).strict(),$.object({operation:$.literal("reserve"),occurredAt:$.iso.datetime({offset:!0}).optional(),internal_feature_id:$.uuid(),entityId:$.uuid().optional(),quantity:sr,properties:Xe,idempotencyKey:Ii,expiresInSeconds:$.number().int().min(1).max(86400)}).strict(),$.object({operation:$.literal("confirm"),operationId:$.uuid(),quantity:sr,properties:Xe.optional(),idempotencyKey:Ii}).strict(),$.object({operation:$.literal("refund"),operationId:$.uuid(),quantity:sr,idempotencyKey:Ii}).strict(),$.object({operation:$.literal("release"),operationId:$.uuid(),idempotencyKey:Ii}).strict()]),Cs=$.object({internal_credit_feature_id:$.uuid().nullable(),internal_metered_feature_id:$.uuid(),dimension:$.string().min(1).max(64),counterKey:$.string().min(1).max(240),cycleStart:$.iso.datetime({offset:!0}),unitCost:Y,units:sr,amount:ut,tier:$.number().int().min(1).max(12).nullable()}).strict(),cr=$.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function wd(e,t){let n=e.reduce((r,i)=>r+Ut(i.units,12),0n)-Ut(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var Od=$.discriminatedUnion("funding",[$.strictObject({funding:$.literal("balance"),sourceId:$.uuid(),rolloverId:$.uuid().nullable(),units:cr.refine(e=>/[1-9]/.test(e)),amount:ut}),$.strictObject({funding:$.literal("unbilled"),units:cr.refine(e=>/[1-9]/.test(e))}),$.object({funding:$.literal("prepaid"),sourceId:$.uuid(),units:sr,amount:ut,pricing:$.array(Cs).min(1).max(12)}).strict().refine(e=>Ai(()=>e.pricing.reduce((t,n)=>t+Ut(n.units,6),0n)===Ut(e.units,6)&&e.pricing.reduce((t,n)=>t+Ut(n.amount,12),0n)===Ut(e.amount,12)&&e.pricing.every(t=>Ut(t.unitCost,6)*Ut(t.units,6)===Ut(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),$.object({funding:$.literal("postpaid"),invoiceLineId:$.uuid().nullable(),units:sr,authorizationId:$.uuid()}).strict()]),wa=$.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Ed=$.object({allowed:$.boolean(),internal_feature_id:$.uuid(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:Ca.optional(),reason:wa.nullable(),allocations:$.array(Od).max(500)}).strict().refine(e=>Ai(()=>e.allowed?e.reason===null&&wd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Ai(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&Ut(e.requestedQuantity,6)>=Ut(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Ci=$.object({id:$.uuid(),internal_feature_id:$.uuid(),kind:$.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:$.uuid().nullable(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:Ca.optional(),accepted:$.boolean(),reason:$.enum([...wa.options,"expired"]).nullable(),createdAt:$.iso.datetime({offset:!0}),reservationStatus:$.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:$.iso.datetime({offset:!0}).nullable(),allocations:$.array(Od).max(500)}).strict().refine(e=>Ai(()=>e.accepted?e.reason===null&&wd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Ai(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&Ut(e.requestedQuantity,6)>=Ut(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as Se}from"zod";var ur=Se.iso.datetime({offset:!0}),Td=Y.refine(e=>/[1-9]/.test(e)),Rd=Se.strictObject({interval:_i.exclude(["lifetime"]),count:yi}),wy=Se.strictObject({action:Se.literal("create"),requestId:Se.uuid(),internal_feature_id:Se.uuid(),entityId:Se.uuid().nullable(),amount:Td.nullable(),expiresAt:ur.nullable(),reset:Rd.nullable(),rollover:ar.nullable(),nextResetAt:ur.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"),kd=Se.discriminatedUnion("action",[wy,Se.strictObject({action:Se.literal("update"),requestId:Se.uuid(),grantId:Se.uuid(),revision:Se.number().int().nonnegative(),amount:Td.nullable(),expiresAt:ur.nullable(),rollover:ar.nullable(),nextResetAt:ur.nullable()}),Se.strictObject({action:Se.enum(["add","subtract","set_remaining"]),requestId:Se.uuid(),grantId:Se.uuid(),revision:Se.number().int().nonnegative(),amount:Y}),Se.strictObject({action:Se.literal("revoke"),requestId:Se.uuid(),grantId:Se.uuid(),revision:Se.number().int().nonnegative()})]),ws=Se.strictObject({id:Se.uuid(),internal_feature_id:Se.uuid(),entityId:Se.uuid().nullable(),amount:Y.nullable(),reset:Rd.nullable(),rollover:ar.nullable(),nextResetAt:ur.nullable(),startsAt:ur,expiresAt:ur.nullable(),revision:Se.number().int().nonnegative(),revoked:Se.boolean(),available:ut,held:ut,spent:ut}),jd=Se.strictObject({customerId:Se.uuid(),after:Se.uuid().nullable(),limit:Se.number().int().min(1).max(100)}),Nd=Se.strictObject({rows:Se.array(ws).max(100),nextCursor:Se.uuid().nullable()});import{z as K}from"zod";var bn=K.iso.datetime({offset:!0}),Dd=K.strictObject({invoiceId:K.uuid(),after:K.string().min(1).max(180).nullable(),limit:K.number().int().min(1).max(100)}),Oy=K.strictObject({kind:K.literal("product"),key:K.string(),productVersionId:K.uuid(),productName:K.string(),itemKey:K.string(),entityId:K.uuid().nullable(),quantity:K.number().int().positive(),subtotalMinor:K.string().regex(/^-?\d+$/),discountMinor:K.string().regex(/^\d+$/),taxMinor:K.string().regex(/^-?\d+$/).nullable(),totalMinor:K.string().regex(/^-?\d+$/),startsAt:bn.nullable(),endsAt:bn.nullable(),providerLineId:K.string().nullable(),providerItemId:K.string()}),Ud=K.strictObject({invoice:gi,items:K.array(K.discriminatedUnion("kind",[Oy,K.strictObject({kind:K.literal("invoice_credit"),key:K.string(),internal_feature_id:K.uuid(),internal_credit_feature_id:K.uuid(),name:K.string(),units:Y,reserved:Y,amountMinor:Or,grossAmountMinor:Or,creditsAppliedMinor:Or,properties:Xe,cashPrice:Fn,providerItemId:K.string().nullable(),creditProviderItemId:K.string().nullable()}),K.strictObject({kind:K.literal("usage"),key:K.string(),internal_feature_id:K.uuid(),name:K.string(),units:Y,reserved:Y,amountMinor:Or,cashPrice:Fn})])).max(100),nextCursor:K.string().min(1).max(180).nullable()}),Ey=K.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Os=K.strictObject({from:bn,to:bn,entityId:K.uuid().optional(),snapshotAt:bn.nullable(),after:K.strictObject({at:bn,id:K.uuid(),position:K.number().int().nonnegative()}).nullable(),limit:K.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"),Fd=K.strictObject({customerId:K.uuid(),entityId:K.uuid().nullable(),from:bn,to:bn,snapshotAt:bn,totals:K.array(K.strictObject({internal_credit_feature_id:K.uuid(),name:K.string(),consumed:ut,refunded:ut,net:Ey})).max(1e3),rows:K.array(K.strictObject({operationId:K.uuid(),position:K.number().int().nonnegative(),kind:K.enum(["consume","confirm","refund"]),originalId:K.uuid().nullable(),occurredAt:bn,internal_feature_id:K.uuid(),entitlementName:K.string(),sourceId:K.uuid(),internal_credit_feature_id:K.uuid(),creditName:K.string(),units:cr,amount:ut,pricing:K.array(Cs).max(12),properties:Xe})).max(100),nextCursor:Os.shape.after});import{z as Ft}from"zod";var yT=Ft.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"]),Md=Ft.object({operationId:Ft.uuid(),windowId:Ft.uuid(),customerId:Ft.uuid(),entityId:Ft.uuid().nullable(),internal_feature_id:Ft.uuid(),entitlementKey:en,basis:Ft.enum(["usage","credits"]),interval:Ft.enum(["day","week","month","year"]),filter:Xe,startsAt:Ft.iso.datetime({offset:!0}),endsAt:Ft.iso.datetime({offset:!0}),limit:Y.refine(e=>/[1-9]/.test(e)),used:ut,reserved:ut,threshold:Ft.number().positive().max(1)}).strict(),ST=Md.omit({threshold:!0,limit:!0}).extend({alertThreshold:Y.refine(e=>/[1-9]/.test(e)),limit:Y.nullable()}),xT=Md.omit({limit:!0}).extend({includedAllowance:Ft.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z as C}from"zod";import{z as an}from"zod";var Ty=an.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Ry=an.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Oa=an.strictObject({internal_feature_id:an.uuid(),entityId:an.uuid().nullable()}),Ld=Oa.extend({quantity:Y,expectedRevision:an.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:an.string().min(1).max(120),properties:Xe.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),wi=Oa.extend({operationId:an.uuid().nullable(),usage:Y,capacity:Ty.nullable(),remaining:Ry.nullable(),withinLimit:an.boolean(),revision:an.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:an.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Ye=C.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),on=C.iso.datetime({offset:!0}),ky=C.enum(["access","metered","credit"]),Oi={internal_feature_id:C.uuid(),key:en,name:C.string().min(1).max(120),kind:ky},Bd=C.object({customerId:C.uuid(),snapshotAt:on,memberships:C.array(C.object({id:C.uuid(),productId:C.string().min(1).max(255),productVersionId:C.uuid(),billingProductVersionId:C.uuid(),version:C.number().int().positive(),key:C.string().min(1).max(64),name:C.string().min(1).max(120),groupId:C.string().max(255).nullable(),membershipType:C.enum(["main","addon"]),status:C.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:C.boolean(),accessEnabled:C.boolean(),renewalChange:C.object({productVersionId:C.uuid(),name:C.string().min(1).max(120),version:C.number().int().positive(),effectiveAt:on,benefitsAppliedAt:on.nullable(),timing:C.enum(["immediate","renewal"]),changeKind:C.enum(["plan","seats","quantity"]),feature:C.strictObject({internal_feature_id:C.uuid(),name:C.string().min(1).max(80),fromQuantity:C.number().int().min(0).max(1e4),toQuantity:C.number().int().min(0).max(1e4)}).optional(),seat:C.object({key:C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:C.number().int().min(0).max(1e4),toQuantity:C.number().int().min(0).max(1e4)}).strict().nullable(),status:C.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:C.object({phase:C.enum(["paid","trial"]),startsAt:on,endsAt:on.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:C.boolean(),balances:C.array(C.object({...Oi,usageType:C.enum(["consumable","non_consumable"]).nullable(),accessible:C.boolean(),unlimited:C.boolean(),available:Ye,held:Ye,debt:Ye,nextExpiresAt:on.nullable(),usage:wi.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:C.boolean()}).strict(),qd=C.enum(["source","usage","transaction","invoice","debt","settlement"]),Ea=C.object({at:on,id:C.uuid(),type:qd}).strict(),Vd=C.object({type:qd.nullable(),resourceKey:en.optional(),kind:C.enum(["purchase","refund"]).optional(),topup:C.boolean().optional(),from:C.iso.date().nullable(),to:C.iso.date().nullable(),after:Ea.nullable(),limit:C.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Er={id:C.uuid(),occurredAt:on},jy=C.discriminatedUnion("type",[C.strictObject({...Er,type:C.literal("invoice"),status:C.string().min(1).max(80),paid:Ye,refunded:Ye,currency:Q,externalId:C.string().nullable()}),C.object({...Er,...Oi,type:C.literal("source"),reason:C.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ye,unlimited:C.boolean(),status:C.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:on,expiresAt:on.nullable(),orderId:C.uuid().nullable(),parentSourceId:C.uuid().nullable()}).strict(),C.object({...Er,type:C.literal("usage"),internal_feature_id:C.uuid(),name:C.string().min(1).max(120),kind:C.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:C.uuid().nullable(),quantity:Y,accepted:C.boolean(),reason:C.enum([...wa.options,"expired"]).nullable(),properties:Xe,reservationStatus:C.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:on.nullable(),charges:C.array(C.discriminatedUnion("funding",[C.strictObject({funding:C.literal("balance"),sourceId:C.uuid(),rolloverId:C.uuid().nullable(),units:cr,amount:Ye}),C.strictObject({funding:C.literal("unbilled"),units:cr}),C.object({...Oi,funding:C.literal("prepaid"),amount:Ye}).strict(),C.object({funding:C.literal("postpaid"),invoiceId:C.uuid(),invoiceLineId:C.uuid(),authorizationId:C.uuid(),units:Y,currency:Q}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),C.object({...Er,type:C.literal("transaction"),purpose:C.enum(["product","invoice"]),productVersionId:C.uuid().nullable(),productName:C.string().min(1).max(120).nullable(),productVersion:C.number().int().positive().nullable(),invoiceId:C.uuid().nullable(),orderId:C.uuid(),originalId:C.uuid().nullable(),kind:C.enum(["purchase","refund"]),amountMinor:C.number().int().nonnegative().max(2e8).nullable(),currency:Q.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),C.object({...Er,...Oi,type:C.literal("debt"),sourceId:C.uuid(),transactionId:C.uuid(),amount:Ye}).strict(),C.object({...Er,...Oi,type:C.literal("settlement"),sourceId:C.uuid(),debtId:C.uuid(),kind:C.enum(["payment","usage_refund","payment_return"]),amount:Ye}).strict()]),$d=C.object({customerId:C.uuid(),rows:C.array(jy).max(50),nextCursor:Ea.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as ee}from"zod";var Hd=ee.object({customerId:ee.uuid()}).strict(),Kd=ee.discriminatedUnion("action",[ee.object({customerId:ee.uuid(),requestId:ee.uuid(),action:ee.literal("assign"),poolId:ee.uuid(),memberCustomerId:ee.uuid()}).strict(),ee.strictObject({customerId:ee.uuid(),requestId:ee.uuid(),action:ee.literal("assign_entity"),poolId:ee.uuid(),entityId:ee.uuid()}),ee.object({customerId:ee.uuid(),requestId:ee.uuid(),action:ee.literal("release"),poolId:ee.uuid(),slotId:ee.uuid()}).strict()]),Ei=ee.number().int().nonnegative(),Es=ee.iso.datetime({offset:!0}),Ts=ee.strictObject({internalId:ee.uuid(),id:ee.string(),name:ee.string().nullable(),version:ee.number().int().positive()}),Gd=ee.enum(["active","past_due"]),Rs=ee.strictObject({customerId:ee.uuid(),licenses:ee.array(ee.strictObject({id:ee.uuid(),linkId:ee.uuid(),parent:ee.strictObject({customerProductId:ee.uuid(),status:Gd,product:Ts}),product:Ts,planLicense:ee.strictObject({id:ee.uuid(),prepaidOnly:ee.boolean(),isCustom:ee.boolean()}).nullable(),granted:Ei,included:Ei,paidQuantity:Ei,usage:Ei,remaining:Ei,createdAt:Es}).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:ee.array(ee.strictObject({id:ee.uuid(),linkId:ee.uuid(),status:Gd,product:Ts,entity:ee.strictObject({internalId:ee.uuid(),id:ee.string().nullable(),name:ee.string().nullable()}).nullable(),beneficiary:ee.strictObject({internalId:ee.uuid(),id:ee.string().nullable(),name:ee.string().nullable()}).nullable(),startedAt:Es.nullable(),endedAt:Es.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:ee.boolean()});import{z as Ln}from"zod";var Ny=Ln.object({name:Ln.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:Ln.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")}),Wd=Ln.object({description:Ln.string().trim().max(240)}),DT=Ln.object({project:Ny.extend({id:Ln.string().min(1)}),environments:Ln.object({sandbox:Wd,live:Wd})});import{z as Be}from"zod";import{z as we}from"zod";import{z as Tr}from"zod";var Qd=Tr.enum(["stripe","apple","google"]),Zd=Tr.enum(["membership","credit_pack","lifetime"]),MT=Tr.enum(["active","grace","suspended","inactive","revoked"]),LT=Tr.strictObject({currency:Tr.string().regex(/^[A-Z]{3}$/),micros:Tr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as Ne}from"zod";var Dy=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()})]),Uy=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),Bn=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"})}),zd=Ne.record(Ne.uuid(),Bn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function Fy(e,t){if(e.nativeOffers!==void 0)return zd.parse(e.nativeOffers)[t]}function My(e,t,n,r){return Bn.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 ks=we.object({type:we.literal("native_purchase"),receiptId:we.uuid(),orderId:we.uuid(),productVersionId:we.uuid(),provider:we.enum(["apple","google"]),productId:we.string().min(1).max(255),productKind:Zd,replacement:we.strictObject({sourceOrderId:we.uuid(),sourceProductId:we.string().min(1).max(255),policy:we.enum(["apple_store","google_full_price"]),sourceAccountTokens:we.array(we.uuid()).max(50)}).nullable(),appAccountToken:we.uuid().optional(),obfuscatedAccountId:we.string().min(1).max(64).optional(),obfuscatedProfileId:we.uuid().optional(),basePlanId:we.string().min(1).max(255).optional(),offerId:we.string().min(1).max(255).optional(),offerKind:we.enum(["none","introductory","promotional"]),currency:Q,catalogAmountMinor:we.number().int().nonnegative().max(1e8),discountMinor:we.number().int().nonnegative().max(1e8),trialDays:we.number().int().min(1).max(730).nullable(),seatBundle:we.array(we.strictObject({key:we.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:we.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:we.strictObject({offerId:we.string().min(1).max(255),keyId:we.string().min(1).max(255),nonce:we.uuid(),signature:we.string().min(1).max(1024),timestamp:we.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 me}from"zod/v4";import{z as Ly}from"zod/v4";var By=Ly.registry(),{BillingInterval:Yd}=(()=>{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:qy}=(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')."})})}))(me),{withSpecDefault:Vy}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(By),{COMMON:Jd}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:$y}={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:Gy}=(e=>({COMMON_SET:new Set(e)}))(Jd),{hasNoDuplicateCurrencies:Xd}={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:em}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Hy}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(me),{Infinite:Ky}={Infinite:"inf"},{TierBehavior:Wy}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:tm}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Qy}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Zy}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:zy}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Yy}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(me),{ApiCreditTierSchema:nm}=(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."})})}))(me),{VIOLATION_MESSAGES:Jy}={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:rm}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(me),{ModelMarkupsSchema:Xy}=((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()}))(me,rm),{InvoiceUsageEntrySchema:eS}=(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()}))(me),{AttachDiscountSchema:im}=(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."})}))(me),{CustomLineItemSchema:tS}=(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."})})}))(me),{UnixMsTimestampSchema:nS}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(me),{CreateInvoicePreviewLineSchema:rS}=(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()})}))(me),{ReissueInvoiceParamsSchema:js}=(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."})})}))(me),{InvoiceModeParamsSchema:qn}=(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."})}))(me),{InvoiceTemplateSchema:iS}=(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."})})}))(me),{BasePriceSchema:aS}=((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."})})}))(me,Yd,qy),{CURRENCY_CODES:oS}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Jd,$y,Gy),{ApiPriceProcessorsSchema:am}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(me,Hy),{AllocatedBillingFieldSchema:sS}=((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'."})}))(me,Qy),{CreditDimensionNameSchema:cS}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(me,Zy,zy),{ApiCreditMatchSchema:om}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Yy),{findCreditTierViolations:uS}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Jy),{ApiCreditMultiplierSchema:lS}=((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."})}))(me,om),{ProviderMarkupsSchema:dS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(me,rm),{InvoiceFeatureQuantitySchema:sm}=((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."})}))(me,tm,eS),{CreateInvoicePreviewSchema:Ns}=((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()})}))(me,rS),{SUPPORTED_SET:mS}=(e=>({SUPPORTED_SET:new Set(e)}))(oS),{ApiCreditDimensionBaseSchema:pS}=((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."})})}))(me,om),{refineGraduatedTiers:cm}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(uS),{ApiFeatureMarkupsOverrideSchema:fS}=((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."})})}))(me,dS,Xy),{isValidCurrencyCode:hS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(mS),{ApiCreditDimensionSchema:gS}=((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()])}))(me,pS,nm,cm),{CurrencyCodeSchema:um}=((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')."})}))(me,hS),{AdditionalCurrencyTierSchema:bS}=((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"]})}))(me,um),{ApiCreditSchemaItemBaseSchema:lm}=((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."})})}))(me,cS,gS,lS),{ApiFlatCreditSchemaItemSchema:_S}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(lm,me),{AdditionalCurrencyPriceSchema:yS}=((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."})})}))(me,um),{AdditionalCurrencyTierArraySchema:SS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(me,bS,Xd,em),{ApiGraduatedCreditSchemaItemSchema:xS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(lm,me,nm,cm),{AdditionalCurrencyPriceArraySchema:dm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(me,yS,Xd,em),{ApiUsageTierWithCurrenciesSchema:vS}=((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()}))}))(me,Ky,SS),{ApiCreditSchemaItemSchema:IS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(me,xS,_S),{BasePriceParamsSchema:AS}=((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."})}))(aS,Vy,me,dm),{PlanItemPriceParamsSchema:PS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(me,dm,vS,Wy,Yd,tm,sS),{ApiFeatureOverrideSchema:CS}=((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."})})}))(me,IS,fS),{InvoiceBasePriceParamsSchema:mm}=((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()}))(AS,am),{InvoiceItemPriceParamsSchema:wS}=((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()}))(PS,am),{InvoiceLicenseQuantitySchema:OS}=((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()}))(me,mm,sm),{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()}))(me,wS,CS),{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."})}))(me,mm,ES),{InvoicePlanParamsSchema:RS}=((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()}))(me,TS,sm,OS,im),{CreateInvoiceParamsSchema:Rr}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(me,RS,tS,im,nS);var hm=f.strictObject({requestId:f.uuid(),invoiceMode:qn.optional(),entityId:f.uuid().optional(),billingSubscriptionId:f.uuid().optional(),newBillingSubscription:f.literal(!0).optional(),offerId:f.uuid().optional(),nativeOffer:Bn.optional(),plans:f.array(f.strictObject({productVersionId:f.uuid(),seatQuantities:f.record(gn,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:Q}).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"),dr=f.strictObject({operationId:f.uuid()}),lt=f.number().int().min(0).max(1e8),kS=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:lt,seats:f.array(f.strictObject({key:gn,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:lt})).max(20),prepaid:f.array(Ad).max(100).optional(),catalogAmountMinor:lt,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+ya({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"),gm=f.string().regex(/^[A-Za-z0-9_-]{1,200}$/),jS=f.strictObject({id:gm,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"),NS=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()}),bm=f.strictObject({invoiceMode:qn.optional(),append:NS.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:gm,terms:jS})).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})}),Ti=f.strictObject({operationId:f.uuid(),entityId:f.uuid().nullable(),billingSubscriptionId:f.uuid().nullable(),discount:f.strictObject({offerId:f.uuid(),couponId:f.uuid(),discount:wr,duration:nn,amountMinor:lt,allocations:f.array(f.strictObject({productVersionId:f.uuid(),amountMinor:lt})).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:lt,discountMinor:lt,taxMinor:lt,totalMinor:lt}).nullable(),expiresAt:f.iso.datetime({offset:!0}),provider:f.enum(["stripe","apple","google"]),nativeOffer:Bn.optional(),currency:Q,lines:f.array(kS).min(1).max(20),catalogAmountMinor:lt,automaticTax:f.boolean(),execution:bm.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"),kr=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:bm.nullable(),currency:Q,catalogAmountMinor:lt,taxMinor:lt,totalMinor:f.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.boolean(),nativePurchase:ks.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"),Ra=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()}),_m=f.strictObject({requestId:f.uuid(),invoiceMode:qn.optional(),membershipId:f.uuid(),carryOverBalances:Ra.optional(),carryOverUsages:Ra.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:gn,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"),Ta=f.string().regex(/^price_[A-Za-z0-9]+$/),pm=f.strictObject({grooveUpdateId:f.uuid(),grooveCustomerId:f.uuid()}),fm=f.strictObject({price:Ta.nullable(),priceId:f.uuid().optional(),quantity:f.number().int().min(0).max(1e4)}),ym=f.strictObject({provider:f.literal("stripe"),invoiceMode:qn.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(fm).max(20),remove:f.array(Ta).max(20),restoreItems:f.array(f.strictObject({price:Ta,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:pm}).nullable(),cancel:f.strictObject({prorate:f.literal(!1),invoiceNow:f.literal(!1)}).nullable(),schedule:f.strictObject({currentItems:f.array(f.strictObject({price:Ta,quantity:f.number().int().min(0).max(1e4)})).max(20),nextItems:f.array(fm).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:pm}).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"),Ds=f.strictObject({carryOverBalances:Ra.optional(),carryOverUsages:Ra.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:Q,creditMinor:lt,debitMinor:lt,discountMinor:lt,taxMinor:lt,totalMinor:lt,retainedProductVersionIds:f.array(f.uuid()).max(19),execution:ym}),DS=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:ym.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),US=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:Q,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:lt,policy:f.enum(["apple_store","google_full_price"])})}),FS=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:ks.nullable()}),Sm=f.union([Ds,US]),Us=f.union([DS,FS]),Ri=f.number().int().positive().max(2e8),lr=f.number().int().min(0).max(2e8),xm=f.strictObject({requestId:f.uuid(),invoiceId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:Ri.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"),vm=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:Ri,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)}),Im=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().regex(/^in_[A-Za-z0-9]+$/),currency:Q,paidMinor:lr,refundedMinor:lr,pendingMinor:lr,amountMinor:Ri,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:vm,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"),ka=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:Q,amountMinor:Ri,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),refundId:f.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:vm.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"),oR=f.strictObject({invoiceId:f.uuid(),currency:Q,paidMinor:lr,refundedMinor:lr,pendingMinor:lr,refundableMinor:lr,executor:f.enum(["indiana","merchant"]).nullable(),canRefund:f.boolean(),operations:f.array(ka).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),sR=f.strictObject({requestId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:Ri.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 Am=Be.strictObject({requestId:Be.uuid(),targets:Be.array(Be.strictObject({membershipId:Be.uuid(),action:Be.enum(["cancel","uncancel"]),timing:Be.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"),ja=Be.strictObject({batchId:Be.uuid()}),MS=Be.strictObject({operationId:Be.uuid(),membershipIds:Be.array(Be.uuid()).min(1).max(20),provider:Be.enum(["stripe","apple","google"]),action:Be.enum(["cancel","uncancel"]),timing:Be.enum(["immediate","renewal"]),status:Be.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ds.nullable(),managementUrl:Be.url().nullable(),failureCode:Be.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),ki=Be.strictObject({batchId:Be.uuid(),ready:Be.boolean(),status:Be.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Be.iso.datetime({offset:!0}),acceptedAt:Be.iso.datetime({offset:!0}).nullable(),groups:Be.array(MS).min(1).max(100)});import{z as ye}from"zod";var LS=ye.string().trim().min(1).max(240),Fs={requestId:ye.uuid(),reason:LS},Na=ye.discriminatedUnion("action",[ye.strictObject({...Fs,action:ye.literal("start"),productVersionId:ye.uuid(),entityId:ye.uuid().optional(),days:ye.number().int().min(1).max(730).optional()}),ye.strictObject({...Fs,action:ye.literal("extend"),membershipId:ye.uuid(),days:ye.number().int().min(1).max(730)}),ye.strictObject({...Fs,action:ye.literal("end"),membershipId:ye.uuid()})]),Pm=ye.strictObject({operationId:ye.uuid()}),Cm=ye.iso.datetime({offset:!0}),BS=ye.strictObject({provider:ye.literal("stripe"),executor:ye.enum(["indiana","merchant"]),accountId:ye.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:ye.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:ye.union([ye.literal("now"),Cm]),prorationBehavior:ye.literal("none")}),Ms=ye.strictObject({operationId:ye.uuid(),action:ye.enum(["start","extend","end"]),status:ye.enum(["pending","effective"]),managedBy:ye.enum(["indiana","stripe"]),membershipIds:ye.array(ye.uuid()).min(1).max(20),endsAt:Cm.nullable(),execution:BS.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"),pR=ye.strictObject({groupId:ye.uuid(),productVersionId:ye.uuid(),enabled:ye.boolean()});import{z as ke}from"zod";var wm=ke.strictObject({requestId:ke.uuid(),currency:Q,makeDefault:ke.boolean()}),Om=ke.strictObject({setupId:ke.uuid()}),qS=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})}),Ls=ke.strictObject({id:ke.uuid(),provider:ke.literal("stripe"),status:ke.enum(["prepared","complete","expired"]),currency:Q,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:qS.nullable()});import{z as dt}from"zod";var Em=dt.union([dt.string(),dt.number(),dt.boolean(),dt.null()]),Tm=dt.strictObject({customerId:dt.uuid()}),Rm=dt.strictObject({customerId:dt.uuid(),provider:dt.literal("stripe"),checkedAt:dt.iso.datetime({offset:!0}),status:dt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:dt.number().int().nonnegative(),differences:dt.array(dt.strictObject({subscriptionId:dt.string().startsWith("sub_"),itemId:dt.string().nullable(),field:dt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Em,actual:Em})).max(1e4)});import{z as de}from"zod";var Da=de.iso.datetime({offset:!0}),Ua=de.strictObject({createdAt:Da,id:de.uuid()}),Fa=de.strictObject({customerId:de.uuid().optional(),entityId:de.uuid().optional(),productId:de.string().min(1).max(256).optional(),provider:de.enum(["stripe","apple","google","free"]).optional(),status:de.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Ua.optional(),limit:de.number().int().min(1).max(100).optional()}),Bs={id:de.uuid(),customerId:de.uuid(),entityId:de.uuid().nullable(),productId:de.string().min(1).max(256),productVersionId:de.uuid(),name:de.string().min(1).max(120),provider:de.enum(["stripe","apple","google","free"]),createdAt:Da},VS=de.strictObject({...Bs,status:de.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:de.boolean(),billingSubscriptionId:de.uuid().nullable()}),$S=de.strictObject({...Bs,status:de.enum(["active","ended","refunded"]),orderId:de.uuid().nullable(),transactionId:de.uuid().nullable(),currency:Q.nullable(),amountMinor:de.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),GS=de.strictObject({...Bs,status:de.enum(["blocked","resolved"]),conflict:de.strictObject({detectedAt:Da,blockingMembershipIds:de.array(de.uuid()).min(1).max(100),transactionId:de.uuid()}),resolvedAt:Da.nullable()}),km=Fa.extend({status:de.enum(["blocked","resolved"]).optional()}),jm=de.strictObject({customerId:de.uuid(),orderId:de.uuid()}),Nm=de.strictObject({orderId:de.uuid(),status:de.enum(["blocked","resolved"])}),Dm=de.strictObject({items:de.array(VS).max(100),nextCursor:Ua.nullable()}),Um=de.strictObject({items:de.array($S).max(100),nextCursor:Ua.nullable()}),Fm=de.strictObject({items:de.array(GS).max(100),nextCursor:Ua.nullable()});import{z as Ue}from"zod";var Mm=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)})]),Lm=Ue.strictObject({requestId:Ue.uuid(),orderId:Ue.uuid(),purchaseIntentId:Ue.uuid(),status:Ue.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:Q,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 He}from"zod";import{z as HS}from"zod";var jr=HS.object({provider:Qd,currency:Q}).strict();var Vn=He.strictObject({internal_feature_id:He.uuid(),quantity:Y.refine(e=>/[1-9]/.test(e)),properties:Xe,entityId:He.uuid().optional()}),Bm=He.strictObject({requirement:Vn,commerce:jr.optional(),paywallId:He.uuid().optional()}),KS=He.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),qs=He.strictObject({productId:He.string().min(1),productVersionId:He.string().min(1),name:He.string().min(1).max(120),action:He.enum(["purchase","upgrade","addon","topup"]),membershipId:He.string().min(1).nullable(),currency:Q,amountMinor:He.string().regex(/^(0|[1-9]\d{0,8})$/),interval:He.enum(["free","week","month","year","one_time"]),intervalCount:He.number().int().min(1).max(156)}),mr=He.strictObject({internal_feature_id:He.string().min(1),name:He.string().min(1).max(120),kind:He.enum(["access","metered","credit"]),quantity:Y,allowed:He.boolean(),reason:KS.nullable(),preview:He.strictObject({scenario:He.enum(["feature_flag","usage_limit"]),candidates:He.array(qs).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),NR=He.strictObject({paywallId:He.uuid(),requirement:Vn});import{z as R}from"zod";var Gs=R.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),WS=R.record(R.string(),R.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),QS=3,ji=20,ZS=QS*ji,Vs=R.strictObject({type:R.literal("product"),productId:Gs}),qm={type:R.literal("group"),key:R.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:R.string().trim().min(1).max(80)},zS=R.discriminatedUnion("type",[Vs,R.strictObject({...qm,items:R.array(Vs).max(ji)})]),YS=R.discriminatedUnion("type",[Vs,R.strictObject({...qm,items:R.array(zS).max(ji)})]),JS=R.array(YS).max(ji).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>ji||i>ZS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ni(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ni(t))}function FR(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 Ma=R.strictObject({lookupKey:R.string().trim().min(1).max(200),displayName:R.string().trim().min(1).max(1500),items:JS,metadata:WS}),$s=Ma.extend({paywallId:R.uuid().nullable()}),XS=R.strictObject({product:R.record(R.string(),R.json()),prices:R.array(R.record(R.string(),R.json())),entitlements:R.array(R.record(R.string(),R.json())),freeTrials:R.array(R.record(R.string(),R.json())),licenses:R.array(R.record(R.string(),R.json()))}),Vm=$s.extend({id:R.uuid(),projectId:R.uuid(),environmentId:R.uuid(),state:R.enum(["active","archived"]),isCurrent:R.boolean(),revision:R.number().int().nonnegative(),publishedVersionId:R.uuid().nullable(),createdAt:R.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"})}),$m=R.strictObject({id:R.uuid(),offeringId:R.uuid(),projectId:R.uuid(),environmentId:R.uuid(),version:R.number().int().positive(),document:Ma,productEvidence:R.record(Gs,XS),createdAt:R.number().nonnegative().nullable()}).superRefine((e,t)=>{let n=Ni(e.document);(!n.length||n0(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"})}),e0=R.strictObject({rows:R.array(Vm).max(200),versions:R.array($m).max(500)}),MR=R.discriminatedUnion("action",[R.strictObject({action:R.literal("create"),document:$s}),R.strictObject({action:R.literal("save"),id:R.uuid(),revision:R.number().int().nonnegative(),document:$s}),R.strictObject({action:R.enum(["publish","set_current","archive","restore"]),id:R.uuid(),revision:R.number().int().nonnegative()})]),LR=R.strictObject({record:Vm,version:$m.nullable()}),Gm=R.discriminatedUnion("type",[R.strictObject({type:R.literal("current")}),R.strictObject({type:R.literal("id"),id:R.uuid()}),R.strictObject({type:R.literal("lookup_key"),lookupKey:R.string().min(1).max(200)}),R.strictObject({type:R.literal("version"),versionId:R.uuid()})]),t0=R.strictObject({internalId:Gs,id:R.string(),name:R.string().nullable(),version:R.number().int().positive(),archived:R.boolean()}),BR=e0.extend({products:R.array(t0).max(500),paywalls:R.array(R.strictObject({id:R.uuid(),name:R.string()})).max(200)});function n0(e){let t=[];Ni(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 La}from"zod";var Nr=La.strictObject({id:La.uuid(),offeringId:La.uuid(),version:La.number().int().positive(),document:Ma});import{z as Rt}from"zod";import{z as ne}from"zod";import{z as Dr}from"zod";import{z as wn}from"zod";var Hm=wn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ba=wn.strictObject({tiers:wn.array(wn.strictObject({id:Hm,name:wn.string().trim().min(1).max(80)})).min(1).max(8),assignments:wn.array(wn.strictObject({productVersionId:wn.string().min(1).max(200),tierId:Hm,period:wn.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function qa(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var Km=Dr.strictObject({items:Dr.array(Dr.strictObject({productVersionId:Dr.string().min(1).max(200),label:Dr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Dr.string().min(1).max(200).nullable(),grouping:Ba.optional()});function ZR(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}function Wm(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Ur(e){let t={};function n(r){if(Wm(r)){let i=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let o of r.children){let s=o.type==="stack"?o.bind?.plan:void 0;s&&!i.ids.includes(s)&&i.ids.push(s)}let a=r.children[r.interaction.defaultIndex];!i.defaultId&&a?.type==="stack"&&(i.defaultId=a.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}function Qm(e,t,n){let r={};function i(c){if(c.hidden)return;if(c.type==="plan_picker"){let d=n.pickers[c.id];r[c.id]={ids:d?.options??[],defaults:d?.selected?[d.selected]:[],remembered:[]};return}if(c.type!=="stack")return;let u=c.children.filter(d=>!d.hidden),l=c.interaction;if(Wm(c)){let d=r[c.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},m=n.pickers[c.interaction.pickerId]?.options??[];for(let p of u){let h=p.type==="stack"?p.bind?.plan:void 0;h&&m.includes(h)&&!d.ids.includes(h)&&d.ids.push(h),h&&p.id===t[c.id]&&d.remembered.push(h)}let g=c.children[c.interaction.defaultIndex];g?.type==="stack"&&!g.hidden&&g.bind?.plan&&d.defaults.push(g.bind.plan)}if(l?.type==="tabs"){let d=u.find(m=>m.id===t[c.id])??c.children[l.defaultIndex];d&&i(d)}else if(l?.type==="toggle"){let d=typeof t[c.id]=="boolean"?t[c.id]:l.defaultEnabled,m=c.children[d?0:1];m&&i(m)}else u.forEach(i)}let a=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,o=e.pages.find(c=>c.id===a);o&&i(o.root);let s={};for(let[c,u]of Object.entries(r)){let l=t[c],d=u.remembered[0]??(u.ids.includes(n.pickers[c]?.selected??"")?n.pickers[c]?.selected:u.defaults[0]);s[c]=typeof l=="string"?u.ids.includes(l)?l:"":d&&u.ids.includes(d)?d:""}for(let c of Object.keys(Ur(e)))s[c]??="";return s}import{z as ae}from"zod";var r0=["plan.name","plan.price","plan.period","plan.price_per_month","trial.headline","trial.terms","offer.headline","offer.name","offer.description","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.price","offer.original_price","offer.months","offer.code","offer.ends_at","offer.expires_at","paywall.feature","paywall.message","paywall.action"],Hs=ae.object({plan:ae.string().min(1).max(200).optional(),coupon:ae.uuid().optional(),promotionCode:ae.uuid().optional(),picker:ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Zm=ae.object({text:ae.string().optional(),label:ae.string().optional(),alt:ae.string().optional(),html:ae.string().max(32768).optional(),price:ae.object({current:ae.string(),original:ae.string().nullable(),period:ae.string()}).optional(),code:ae.string().optional(),countdownAt:ae.iso.datetime().optional(),planId:ae.string().min(1).max(200).optional(),planVersionId:ae.string().min(1).max(200).optional(),currency:Q.optional(),couponId:ae.uuid().optional(),offerId:ae.uuid().optional(),unavailable:ae.boolean().optional(),unavailableReason:ae.string().optional(),missing:ae.array(ae.string()).optional()}).strict(),Va=ae.object({paywall:mr.optional(),nodes:ae.record(ae.string(),ae.object({base:Zm,picker:ae.string().optional(),byPlan:ae.record(ae.string(),Zm).optional()}).strict()),plans:ae.record(ae.string(),ae.object({id:ae.string().min(1).max(200),versionId:ae.string().min(1).max(200),available:ae.boolean(),name:ae.string(),price:ae.string(),period:ae.string(),currency:Q.optional()}).strict()),pickers:ae.record(ae.string(),ae.object({options:ae.array(ae.string().min(1).max(200)).max(20),selected:ae.string().min(1).max(200).nullable()}).strict()),diagnostics:ae.array(ae.object({nodeId:ae.string(),message:ae.string()}).strict())}).strict();function $a(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}function Ga(e){let t=$a(e).filter(r=>!r0.includes(r)),n=e.replace(/\{\{\s*[^{}]+?\s*\}\}/g,"");return(n.includes("{{")||n.includes("}}"))&&t.push("\u65E0\u6548\u53D8\u91CF\u8BED\u6CD5"),[...new Set(t)]}function tk(e,t,n,r=!1){let i=$a(e).filter(a=>!/^(input|params)\.[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(a)&&t[a]===void 0);return i.length&&!r?{value:n,missing:i}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(a,o)=>t[o.trim()]??a),missing:i}}function nk(e,t,n={}){let r=e?.nodes[t];if(!r)return;let i=r.picker?n[r.picker]??e?.pickers[r.picker]?.selected:void 0;return typeof i=="string"?r.byPlan?.[i]??r.base:r.base}import{z as y}from"zod";import{z}from"zod";var i0=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],zm=z.enum(i0),Ym=z.object({source:zm,layout:z.enum(["full","compact"]),resourceKey:en.optional(),pageSize:z.number().int().min(1).max(50),showSources:z.boolean(),allowPurchase:z.boolean(),outputs:z.object({billing_adjustment:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),ot=z.string().max(2e3),Jm=z.object({id:z.string().max(100),label:ot,detail:z.array(ot).max(12),value:ot.optional(),status:ot.optional(),facts:z.array(z.object({label:ot,value:ot}).strict()).max(1e3),purchaseId:z.uuid().optional(),invoiceUrl:z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:z.array(z.strictObject({action:z.literal("invoice_open"),label:ot})).max(1).optional(),membershipActions:z.array(z.object({value:z.string().max(100),label:ot}).strict()).max(3).optional()}).strict(),a0=z.object({key:en,name:ot,spendable:ot,reserved:ot,available:ot,expiry:ot.nullable(),sources:z.array(Jm).max(50),sourceCount:z.number().int().nonnegative(),sourcePage:z.number().int().positive(),hasNextSources:z.boolean(),hasPreviousSources:z.boolean()}).strict(),o0=z.object({source:zm,status:z.enum(["idle","loading","ready","error"]),stale:z.boolean(),preview:z.boolean(),errorCode:z.string().max(80).optional(),errorMessage:ot.optional(),resources:z.array(a0).max(500),rows:z.array(Jm).max(50),hasNext:z.boolean(),hasPrevious:z.boolean(),page:z.number().int().positive(),filter:z.string().max(40),updatedAt:z.iso.datetime().optional(),buyingId:z.uuid().optional(),membershipBusy:z.boolean().optional(),billingBusy:z.boolean().optional(),membershipReview:z.object({title:ot,note:ot,facts:z.array(z.object({label:ot,value:ot}).strict()).max(100)}).strict().optional(),membershipResult:ot.optional()}).strict(),Xm=z.object({nodes:z.record(z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),o0)}).strict(),ok=z.object({nodeId:z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:z.string().max(100).optional()}).strict();function ep(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function Ks(e){let t=Ga(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let r=n;if(e.startsWith("<!--",n)){let i=e.indexOf("-->",n+4);n=i<0?e.length:i+2}else{let i="";for(n++;n<e.length;n++){let a=e[n];if(i)a===i&&(i="");else if(a==='"'||a==="'")i=a;else if(a===">")break}}/\{\{|\}\}/.test(e.slice(r,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function tp(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}function uk(e,t,n,r=!1){let i=Ks(e);if(i.length)throw new Error(i[0]);let a=[...new Set($a(e).filter(o=>t[o]===void 0))];return a.length&&!r?{value:tp(n),missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(o,s)=>t[s.trim()]===void 0?o:tp(t[s.trim()])),missing:a}}var s0=4,cn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Ui=y.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Fe=y.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),c0=y.enum(["none","xs","sm","md","lg","xl"]),u0=y.enum(["none","sm","md","lg","full"]),Ws=y.string().regex(/^#[0-9a-fA-F]{6}$/),ip=y.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),Qs=y.union([ip,y.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),y.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),y.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),np=y.object({primary:Ws,background:Ws,text:Ws,radius:u0,font:y.enum(["system","serif","rounded","mono"])}).strict(),Fi=y.union([y.enum(["primary","text","muted","background","surface"]),y.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Oe=(e,t)=>y.number().int().min(e).max(t),rp=y.union([y.enum(["fit","fill"]),Oe(1,1200)]),l0=y.object({top:Oe(0,200),right:Oe(0,200),bottom:Oe(0,200),left:Oe(0,200)}).strict(),d0=y.object({top:Oe(-100,200),right:Oe(-100,200),bottom:Oe(-100,200),left:Oe(-100,200)}).strict(),ap=y.object({x:Oe(0,100),y:Oe(0,100)}).strict(),m0=y.discriminatedUnion("type",[y.object({type:y.literal("color"),color:Fi}).strict(),y.object({type:y.literal("linear"),angle:Oe(0,360),stops:y.array(y.object({color:Fi,at:Oe(0,100)}).strict()).min(2).max(4)}).strict(),y.object({type:y.literal("image"),src:Qs,fit:y.enum(["cover","contain"]),position:ap.optional()}).strict()]),p0=y.discriminatedUnion("type",[y.object({type:y.literal("rect"),radius:y.union([Oe(0,200),y.object({topLeft:Oe(0,200),topRight:Oe(0,200),bottomRight:Oe(0,200),bottomLeft:Oe(0,200)}).strict()])}).strict(),y.object({type:y.literal("pill")}).strict()]),f0=y.object({width:Oe(0,12),color:Fi,style:y.enum(["solid","dashed"])}).strict(),h0=y.object({x:Oe(-40,40),y:Oe(-40,40),blur:Oe(0,80),spread:Oe(-20,40),color:Fi}).strict(),g0=y.object({font:y.enum(["system","serif","rounded","mono"]),size:Oe(8,96),weight:y.number().int().min(100).max(900).multipleOf(100),lineHeight:y.number().min(.8).max(3),letterSpacing:y.number().min(-5).max(20),color:Fi,align:y.enum(["start","center","end"]),italic:y.boolean(),decoration:y.enum(["none","underline","line-through"]),transform:y.enum(["none","uppercase"])}).strict().partial(),pr=y.object({width:rp,height:rp,padding:l0,margin:d0,gap:Oe(0,120),grow:y.union([y.boolean(),y.number().min(0).max(12)]),background:m0,opacity:y.number().min(0).max(1),clipContent:y.boolean(),shape:p0,border:f0,shadow:h0,text:g0}).strict().partial(),Mt={id:Ui,name:y.string().trim().min(1).max(60).optional(),hidden:y.boolean().optional(),style:pr.optional(),fallback:Fe.optional()},b0=y.object({...Mt,type:y.literal("text"),productField:y.enum(["name","price","trial","period"]).optional(),feature:y.object({id:y.uuid(),field:y.enum(["name","allowance"])}).strict().optional(),text:Fe,variant:y.enum(["title","heading","body","caption"])}).strict(),_0=y.object({...Mt,type:y.literal("image"),src:Qs,localizedSrc:y.record(tn,Qs).optional(),alt:Fe,aspect:y.enum(["auto","1:1","4:3","16:9","3:1"]),fit:y.enum(["cover","contain"]),position:ap.optional()}).strict(),y0=y.object({...Mt,type:y.literal("button"),label:Fe,variant:y.enum(["primary","secondary","link"]),action:Fe,purpose:y.enum(["purchase","navigation","close"]).optional(),bind:Hs.optional()}).strict(),S0=y.object({...Mt,type:y.literal("divider")}).strict(),x0=y.object({...Mt,type:y.literal("customer_data"),title:Fe,data:Ym}).strict(),v0=y.object({...Mt,type:y.literal("spacer"),size:c0}).strict(),I0=y.object({...Mt,type:y.literal("custom_html"),html:y.record(tn,y.string().max(cn.customHtml)),css:y.string().max(cn.customCss)}).strict(),A0=y.object({...Mt,type:y.literal("price"),fallback:Fe,parts:y.object({current:pr.optional(),original:pr.optional(),period:pr.optional()}).strict().optional()}).strict(),P0=y.object({...Mt,type:y.literal("coupon_code"),label:Fe,fallback:Fe}).strict(),C0=y.object({...Mt,type:y.literal("countdown"),source:y.enum(["offer.ends_at","offer.expires_at","fixed"]),at:y.iso.datetime().optional(),granularity:y.enum(["day","hour","minute","second"]),expired:Fe,fallback:Fe}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),w0=y.object({...Mt,type:y.literal("plan_picker"),label:Fe,fallback:Fe,planIds:y.array(y.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:y.string().min(1).max(200).optional(),grouping:Ba.safeExtend({monthLabel:Fe,yearLabel:Fe,unavailableLabel:Fe}).optional(),states:y.object({selected:pr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!qa(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),O0=y.discriminatedUnion("type",[y.object({type:y.literal("input"),label:Fe,keyboard:y.enum(["text","email","tel","url"]),maxLength:Oe(1,500)}).strict(),y.object({type:y.literal("multiselect"),label:Fe,min:Oe(0,50),max:Oe(1,50)}).strict(),y.object({type:y.literal("select"),label:Fe,defaultIndex:Oe(0,49),purpose:y.enum(["option","product","tier"]).optional(),pickerId:Ui.optional(),selectedStyle:pr.optional()}).strict(),y.object({type:y.literal("tabs"),label:Fe,defaultIndex:Oe(0,49),purpose:y.literal("tier").optional()}).strict(),y.object({type:y.literal("toggle"),label:Fe,defaultEnabled:y.boolean()}).strict(),y.object({type:y.literal("carousel"),label:Fe}).strict()]),sn={...Mt,type:y.literal("stack"),direction:y.enum(["vertical","horizontal","overlay"]),align:y.enum(["start","center","end","stretch"]),justify:y.enum(["start","center","end","between"]),productSlot:y.object({index:Oe(0,19),period:y.enum(["month","year"]).optional(),requireBinding:y.boolean().optional()}).strict().optional(),interaction:O0.optional(),states:y.object({selected:pr.optional()}).strict().optional(),purpose:y.literal("benefits").optional(),purchaseAction:Fe.optional(),buttonVariant:y.enum(["primary","secondary","link"]).optional(),bind:Hs.optional()},op=y.lazy(()=>y.object({...Mt,type:sn.type,direction:sn.direction,align:sn.align,justify:sn.justify,children:y.array(E0).max(cn.children),productSlot:sn.productSlot,interaction:sn.interaction,states:sn.states,purpose:sn.purpose,purchaseAction:sn.purchaseAction,buttonVariant:sn.buttonVariant,bind:sn.bind}).strict()),E0=y.lazy(()=>y.union([op,b0,_0,y0,S0,v0,I0,A0,P0,C0,w0,x0])),T0=y.union([y.string().max(500),y.number().finite(),y.boolean(),y.null()]),Di={id:Fe,event:Fe,properties:y.record(Fe,T0).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},R0=y.discriminatedUnion("type",[y.object({...Di,type:y.literal("navigate"),close:y.literal(!1),pageId:Ui}).strict(),y.object({...Di,type:y.literal("event"),close:y.boolean()}).strict(),y.object({...Di,type:y.literal("close"),close:y.literal(!0)}).strict(),y.object({...Di,type:y.literal("open_url"),close:y.boolean(),url:ip}).strict(),y.object({...Di,type:y.literal("claim_offer"),close:y.boolean(),couponId:y.uuid()}).strict()]),k0=y.object({defaultLocale:tn,locales:y.record(tn,y.record(Fe,y.string().max(cn.stringLength)))}).strict(),Zs=y.enum(["popup","paywall","onboarding","page"]),_k={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},j0=y.discriminatedUnion("type",[y.object({type:y.literal("modal"),size:y.enum(["sm","md","lg"])}).strict(),y.object({type:y.literal("sheet"),size:y.enum(["sm","md","lg"])}).strict(),y.object({type:y.literal("fullscreen")}).strict()]),yk={sm:360,md:420,lg:560},N0=y.object({kind:y.literal("screen"),schemaVersion:y.literal(s0),name:y.string().trim().min(1).max(80),surface:Zs,initialPageId:Ui.optional(),presentation:j0,theme:np,pages:y.array(y.object({id:Ui,name:y.string().trim().min(1).max(60),root:op,theme:np.optional(),editorPosition:y.object({x:y.number().finite().min(-1e5).max(1e5),y:y.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(cn.pages),strings:k0,actions:y.array(R0).max(cn.actions)}).strict();function wt(e,t){for(let n of e.pages)_n(n.root,t)}function Sk(e,t){return{...e,pages:e.pages.map((n,r)=>r===0?{...n,root:t}:n)}}var Tt=N0.superRefine((e,t)=>{let n=cn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(d=>d.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>cn.locales&&r(`\u6700\u591A ${cn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;wt(e,(l,d)=>{if(c++,d>cn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let m of Object.keys(l.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(l.type==="image")for(let m of Object.keys(l.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${cn.depth} \u5C42`)});function _n(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)_n(i,t,n+1,e)}function zs(e){let t=[],n=new Set;return wt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function D0(e,t,n){if(t.field==="html"){let r;return wt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Mi(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function Fr(e){let t=zs(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!D0(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function xk(e){return sp(e,!0)}function vk(e){return sp(e,!1)}function sp(e,t){let n=[],r=t&&e.actions.some(u=>typeof u.properties.templateKey=="string"&&u.properties.templateKey.startsWith("popup-coupon-"));r&&(!e.actions.some(u=>u.type==="claim_offer")||e.actions.some(u=>u.type==="event"&&typeof u.properties.templateKey=="string"&&u.properties.templateKey.startsWith("popup-coupon-")))&&n.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u8BF7\u5C06\u9886\u53D6\u6309\u94AE\u8BBE\u4E3A\u300C\u9886\u53D6\u4F18\u60E0\u300D\u5E76\u9009\u62E9\u751F\u6548\u4E2D\u7684\u5238");function i(u,l){let d=u.type==="stack"||u.type==="button"?u.bind?.coupon??l:l;if(r&&u.type==="text"&&Object.values(e.strings.locales).some(m=>m[u.text]?.includes("{{offer."))&&!d&&n.push("\u4F18\u60E0\u5F39\u7A97\u6A21\u677F\u5C1A\u672A\u7ED1\u5B9A\u771F\u5B9E\u4F18\u60E0\u5238\uFF1A\u52A8\u6001\u6587\u6848\u9700\u8981\u7EE7\u627F\u4F18\u60E0\u5238\u7ED1\u5B9A"),u.type==="button"){let m=e.actions.find(g=>g.id===u.action);m?.type==="claim_offer"&&d&&d!==m.couponId&&n.push(`\u9886\u53D6\u6309\u94AE ${u.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}u.type==="stack"&&u.children.forEach(m=>i(m,d))}e.pages.forEach(u=>i(u.root));let a=[],o=Tt.safeParse(e);o.success||n.push(...o.error.issues.map(u=>u.message));for(let u of Object.values(e.strings.locales))for(let l of Object.values(u))for(let d of Ga(l))n.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${d}`);wt(e,u=>{if(u.type==="customer_data"&&Object.values(e.strings.locales).some(d=>/\{\{|\}\}/.test(d[u.title]??""))&&n.push(`\u6570\u636E\u7EC4\u4EF6 ${u.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(u.type==="text"?[u.text]:u.type==="button"?[u.label]:[]).some(d=>Object.values(e.strings.locales).some(m=>m[d]?.includes("{{")))&&!u.fallback&&n.push(`\u7EC4\u4EF6 ${u.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),u.fallback&&Object.values(e.strings.locales).some(d=>d[u.fallback]?.includes("{{"))&&n.push(`\u7EC4\u4EF6 ${u.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),u.type==="custom_html"){for(let d of Object.values(u.html))n.push(...Ks(d).map(m=>`HTML ${u.id}\uFF1A${m}`));Object.values(u.html).some(d=>d.includes("{{"))&&!u.fallback&&n.push(`HTML ${u.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{/.test(u.css)&&n.push(`HTML ${u.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(u.type==="stack"||u.type==="button")&&u.bind?.picker&&Mi(e,u.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(Ur(e),u.bind.picker)&&n.push(`\u5BB9\u5668 ${u.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let u of Object.keys(Ur(e)))Mi(e,u)||n.push(`Product selection scope ${u} must reference a UI node`);let s=Fr(e);for(let u of s)u.complete||(u.locale===e.strings.defaultLocale?n.push(`\u9ED8\u8BA4\u8BED\u8A00 ${u.locale} \u8FD8\u6709 ${u.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):n.push(`${u.locale} \u8FD8\u6709 ${u.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));zs(e).length===0&&!e.pages.some(u=>U0(u.root))&&n.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let c=new Set;wt(e,u=>{u.type==="button"&&c.add(u.action)});for(let u of e.actions)!c.has(u.id)&&!e.pages.some(l=>F0(l.root,u.id))&&a.push(`\u52A8\u4F5C ${u.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:n,warnings:a}}function U0(e){let t=!1;return _n(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function F0(e,t){let n=!1;return _n(e,r=>{if(r.type==="custom_html")for(let i of Object.values(r.html))i.includes(`data-grow-action="${t}"`)&&(n=!0)}),n}function M0(e){return Fr(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Ys(e,t){return xa(t,M0(e),e.strings.defaultLocale)}function Ik(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let o of zs(e)){if(o.field==="html"||o.field==="src")continue;let s=n[o.key]?.trim()?n[o.key]:r[o.key];s!==void 0&&(i[o.key]=s)}let a=o=>{if(o.type==="stack")return{...o,children:o.children.map(a)};if(o.type==="custom_html"){let s=o.html[t]?.trim()?o.html[t]:o.html[e.strings.defaultLocale];return{...o,html:s===void 0?{}:{[t]:s}}}if(o.type==="image"){let{localizedSrc:s,...c}=o;return{...c,src:s?.[t]??s?.[e.strings.defaultLocale]??o.src}}return o};return{...e,pages:e.pages.map(o=>({...o,root:a(o.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function L0(e,t){let n=null;return _n(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Mi(e,t){for(let n of e.pages){let r=L0(n.root,t);if(r)return r}return null}function Ak(e){let t=rr(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function Pk(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;if(wt(e,a=>{if(a.type==="plan_picker"){let s=i[a.id];typeof s=="string"&&(r[a.id]=n?.pickers[a.id]?.options.includes(s)?s:"");return}if(a.type!=="stack"||!a.interaction)return;let o=Object.hasOwn(i,a.id)?i[a.id]:void 0;["select","tabs"].includes(a.interaction.type)&&typeof o=="string"&&a.children.some(s=>s.id===o)&&(r[a.id]=o),a.interaction.type==="toggle"&&typeof o=="boolean"&&(r[a.id]=o)}),e.surface==="paywall"&&typeof i.__page=="string"&&e.pages.some(a=>a.id===i.__page)&&(r.__page=i.__page),n){let a={...r};for(let[o,s]of Object.entries(i))(typeof s=="string"||typeof s=="boolean")&&(a[o]=s);Object.assign(r,Qm(e,a,n))}return r}import{z as it}from"zod";var B0=it.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),cp=it.discriminatedUnion("type",[it.object({type:it.literal("fixed"),productVersionId:it.string().min(1).max(200)}).strict(),it.object({type:it.literal("picker"),pickerId:B0,allowedProductVersionIds:it.array(it.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")]),On=it.discriminatedUnion("type",[it.object({type:it.literal("modal"),size:it.enum(["sm","md","lg"])}).strict(),it.object({type:it.literal("sheet"),size:it.enum(["sm","md","lg"])}).strict(),it.object({type:it.literal("fullscreen")}).strict(),it.object({type:it.literal("inline")}).strict()]);var q0=ne.discriminatedUnion("type",[ne.strictObject({type:ne.literal("event"),event:ne.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ne.strictObject({type:ne.literal("open_url"),url:ne.url().refine(e=>new URL(e).protocol==="https:")})]),V0=Tt,$0=ne.discriminatedUnion("type",[ne.object({type:ne.literal("checkout"),product:cp}).strict(),ne.object({type:ne.literal("close")}).strict(),ne.object({type:ne.literal("action"),action:q0}).strict()]),Ha=ne.object({schemaVersion:ne.literal(3),kind:ne.literal("paywall"),name:ne.string().trim().min(1).max(80),presentation:On,requirement:Vn.optional(),products:Km,offeringVersionId:ne.uuid().nullable(),offeringId:ne.uuid().nullable(),screen:V0,buttons:ne.record(ne.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),$0)}).strict(),Ka=Ha.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 H0(e))t.addIssue({code:"custom",message:r});for(let r of G0(e))t.addIssue({code:"custom",message:r});Fr(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 G0(e){let t=e.products.items.map(a=>a.productVersionId),n=Ur(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&&(!qa(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),wt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),wt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function H0(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),_n(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 a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var up=ne.object({id:ne.uuid(),projectId:ne.uuid(),environmentId:ne.uuid(),revision:ne.number().int().nonnegative(),status:ne.enum(["draft","published","archived"]),publishedVersionId:ne.uuid().nullable(),updatedAt:ne.iso.datetime({offset:!0}),draft:Ha}).strict(),Uk=ne.object({rows:ne.array(up).max(200),nextCursor:ne.uuid().nullable()}).strict(),Fk=up.omit({draft:!0}).extend({name:ne.string(),productCount:ne.number().int().nonnegative()}).strict(),Mk=ne.discriminatedUnion("action",[ne.object({action:ne.literal("save"),id:ne.uuid().nullable(),revision:ne.number().int().nonnegative(),document:Ha}).strict(),ne.object({action:ne.enum(["publish","archive"]),id:ne.uuid(),revision:ne.number().int().nonnegative()}).strict()]),Lk=ne.object({paywalls:ne.array(ne.object({id:ne.uuid(),paywallId:ne.uuid(),version:ne.number().int().positive(),name:ne.string().min(1).max(80),presentation:On,buttons:Ha.shape.buttons}).strict()).max(500),limited:ne.boolean()}).strict();var lp=Rt.strictObject({selector:Rt.discriminatedUnion("type",[Rt.strictObject({type:Rt.literal("paywall"),paywallId:Rt.uuid()}),Rt.strictObject({type:Rt.literal("version"),versionId:Rt.uuid()})]),customerId:Rt.uuid().optional(),commerce:jr,locale:Rt.string().min(1).max(35),requirement:Vn.optional()}),Wa=Rt.strictObject({id:Rt.uuid(),paywallId:Rt.uuid(),version:Rt.number().int().positive(),document:Ka,offering:Nr,capabilities:Va,check:mr.nullable()}).superRefine((e,t)=>{let n=new Set(Ni(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 vt}from"zod";var dp={requestId:vt.uuid(),sourceId:vt.uuid(),expectedAvailable:Ye},mp=vt.discriminatedUnion("action",[vt.strictObject({...dp,action:vt.enum(["add","subtract","set_remaining"]),amount:Y}),vt.strictObject({...dp,action:vt.literal("edit"),granted:Y,expiresAt:vt.iso.datetime({offset:!0}).nullable(),nextResetAt:vt.iso.datetime({offset:!0}).nullable(),expectedRevision:vt.number().int().nonnegative()})]),Js=vt.strictObject({sourceId:vt.uuid(),available:Ye,held:Ye,spent:Ye,adjustmentGrantId:vt.uuid().nullable()}),pp=Js.extend({granted:Ye,expiresAt:vt.iso.datetime({offset:!0}).nullable(),nextResetAt:vt.iso.datetime({offset:!0}).nullable(),revision:vt.number().int().nonnegative()});import{z as Lt}from"zod";var fp=Lt.discriminatedUnion("action",[Lt.object({action:Lt.literal("upsert"),externalId:Lt.string().min(1).max(128),name:Lt.string().trim().min(1).max(80)}).strict(),Lt.object({action:Lt.literal("archive"),entityId:Lt.uuid()}).strict()]),hp=Lt.object({id:Lt.uuid(),externalId:Lt.string().min(1).max(128),name:Lt.string().min(1).max(80),archived:Lt.boolean()}).strict();import{z as ft}from"zod";import{z as hr}from"zod";var bp=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],gp=hr.string().regex(/.+\/.+/),Xs=hr.number().min(-100),fr=hr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),K0=hr.strictObject({input:fr,output:fr,cache_read:fr.optional(),cache_write:fr.optional(),reasoning:fr.optional(),input_audio:fr.optional(),output_audio:fr.optional()}),ec=(e,t)=>hr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),nj=hr.strictObject({defaultMarkup:Xs,providerMarkups:ec(hr.string().min(1),Xs),modelMarkups:ec(gp,Xs),customModels:ec(gp,K0.partial())});import{z as oe}from"zod";var gr=oe.iso.datetime({offset:!0}),$n=oe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),W0=oe.discriminatedUnion("kind",[oe.object({kind:oe.literal("absolute"),from:gr,to:gr}).strict(),oe.object({kind:oe.literal("last_days"),days:oe.union([oe.literal(1),oe.literal(7),oe.literal(30),oe.literal(90)])}).strict(),oe.object({kind:oe.literal("billing_cycles"),membershipId:oe.uuid(),count:oe.number().int().min(1).max(12),includeCurrent:oe.boolean()}).strict()]),_p=oe.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"),Q0=oe.object({key:oe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:oe.array(oe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),br=oe.object({range:W0,timezone:_p,filterBy:oe.array(Q0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:oe.enum(["hour","day","week","month"]),internal_feature_id:oe.uuid().nullable(),entityId:oe.uuid().nullable(),topN:oe.number().int().min(1).max(50).nullable(),groupBy:oe.union([oe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),oe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:oe.object({bucket:gr,group:oe.string().max(240),isOther:oe.boolean(),internal_feature_id:oe.uuid(),resourceId:oe.uuid()}).strict().nullable(),limit:oe.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)"})}),yp=oe.object({from:gr,to:gr,interval:oe.enum(["hour","day","week","month"]),timezone:_p,rows:oe.array(oe.object({bucket:gr,group:oe.string().max(240),isOther:oe.boolean(),internal_feature_id:oe.uuid(),resourceId:oe.uuid(),consumedUnits:$n,refundedUnits:$n,reservedUnits:$n,charged:$n,refunded:$n,reserved:$n,netUnits:$n,netCharged:$n}).strict()).max(100),nextCursor:oe.object({bucket:gr,group:oe.string().max(240),isOther:oe.boolean(),internal_feature_id:oe.uuid(),resourceId:oe.uuid()}).strict().nullable()}).strict();var Mr=ft.string().regex(/^(0|[1-9]\d{0,29})$/),Sp=ft.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),tc=ft.strictObject({bucket:ft.iso.datetime({offset:!0}),group:ft.string().max(240),isOther:ft.boolean(),internal_feature_id:ft.uuid()}),xp=ft.strictObject({...br.shape,groupBy:ft.union([ft.enum(["customer","entity","entitlement"]),ft.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:tc.nullable()}).superRefine((e,t)=>{let n=br.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),vp=ft.strictObject({from:ft.iso.datetime({offset:!0}),to:ft.iso.datetime({offset:!0}),interval:br.shape.interval,timezone:br.shape.timezone,rows:ft.array(ft.strictObject({...tc.shape,eventCount:Mr,units:Sp,tokenEventCount:Mr,tokens:ft.strictObject(Object.fromEntries(bp.map(e=>[e,Mr]))),totalTokens:Mr,providerCostEventCount:Mr,providerCostUsd:Sp,invalidTelemetryEventCount:Mr})).max(100),nextCursor:tc.nullable()});import{z as et}from"zod";var Ip=et.object({requestId:et.uuid(),items:et.array(et.object({customerId:et.uuid(),command:Pi.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"),Ap=et.object({batchId:et.uuid(),after:et.number().int().min(-1).max(999),limit:et.number().int().min(1).max(100)}).strict(),Pp=et.object({batchId:et.uuid(),status:et.enum(["queued","complete"]),total:et.number().int().min(1).max(1e3),processed:et.number().int().min(0).max(1e3),items:et.array(et.object({position:et.number().int().min(0).max(999),customerId:et.uuid(),idempotencyKey:et.string().min(1).max(120),status:et.enum(["queued","accepted","rejected","failed"]),receipt:Ci.nullable(),errorCode:et.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:et.number().int().min(0).max(999).nullable()}).strict();import{z as S}from"zod";var Z0=S.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Cp=S.enum(["draft","active","paused","archived"]),wp=S.string().min(1).max(256),Op=S.array(wp).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),z0=S.strictObject({duration:S.enum(["day","week","month","year"]),length:S.number().int().min(1).max(3660)}),Y0=S.strictObject({internal_feature_id:S.uuid(),allowance:S.number().nonnegative().max(1e15).nullable(),expiry:z0.nullable()}),J0=S.discriminatedUnion("type",[S.strictObject({type:S.literal("feature_grant"),grants:S.array(Y0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),S.strictObject({type:S.literal("free_product"),productId:wp,duration:nn}),S.strictObject({type:S.literal("invoice_credits"),amount:S.number().positive().max(1e8),duration:nn,rollover:S.boolean(),productIds:Op})]),X0=S.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Ep=S.object({key:X0,name:S.string().trim().min(1).max(80),configuration:J0}).strict(),Tp=S.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),nc=S.object({code:Tp,maxUses:S.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:S.boolean()}).strict(),Rp=S.object({key:S.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:S.string().trim().min(1).max(80),rewardId:S.uuid(),redeemOn:S.enum(["customer_creation","checkout"]),receivedBy:S.enum(["referrer","all"]),maxRedemptions:S.number().int().min(1).max(1e6).nullable(),productIds:Op,excludeTrial:S.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),kp={id:S.uuid(),projectId:S.uuid(),environmentId:S.uuid(),revision:S.number().int().nonnegative(),status:Cp,createdAt:S.iso.datetime({offset:!0}),updatedAt:S.iso.datetime({offset:!0})},ex=Ep.extend(kp).strict(),tx=Rp.safeExtend(kp).strict(),gj=S.strictObject({id:S.uuid(),key:S.string(),name:S.string(),type:Z0,status:Cp}),bj=S.discriminatedUnion("action",[S.object({action:S.literal("save"),id:S.uuid().nullable(),revision:S.number().int().nonnegative(),input:Ep}).strict(),S.object({action:S.enum(["activate","pause","resume","archive","delete"]),id:S.uuid(),revision:S.number().int().nonnegative()}).strict()]),_j=S.discriminatedUnion("action",[S.object({action:S.literal("save"),id:S.uuid().nullable(),revision:S.number().int().nonnegative(),input:Rp}).strict(),S.object({action:S.enum(["activate","pause","resume","archive","delete"]),id:S.uuid(),revision:S.number().int().nonnegative()}).strict()]),jp=S.object({id:S.uuid(),rewardId:S.uuid(),programId:S.uuid().nullable(),customerId:S.uuid(),referrerId:S.uuid().nullable(),status:S.enum(["pending","applied"]),result:S.record(S.string(),S.unknown()).nullable(),createdAt:S.iso.datetime({offset:!0})}).strict(),Np=S.object({code:Tp,requestId:S.uuid()}).strict(),Dp=S.strictObject({redemptionId:S.uuid(),currency:Q,requestId:S.uuid(),accepted:S.literal(!0)}),nx=S.strictObject({type:S.literal("checkout"),orderId:S.uuid(),productVersionId:S.uuid(),currency:Q,duration:nn,renewalAmountMinor:S.number().int().positive().max(1e8),status:S.enum(["created","pending","trialing","paid","cancelled","failed"]),url:S.url().nullable()}),Up=S.discriminatedUnion("type",[nx,S.strictObject({type:S.literal("subscription"),operationId:S.uuid(),membershipId:S.uuid(),productVersionId:S.uuid(),currency:Q,duration:nn,renewalAmountMinor:S.number().int().positive().max(1e8),status:S.enum(["pending","running","applied","failed"])})]),Fp=S.object({programId:S.uuid(),requestId:S.uuid()}).strict(),Mp=S.object({id:S.uuid(),programId:S.uuid(),code:nc.shape.code,createdAt:S.iso.datetime({offset:!0})}).strict(),yj=S.object({rows:S.array(ex).max(100),nextCursor:S.uuid().nullable()}).strict(),Sj=S.object({rows:S.array(tx).max(100),nextCursor:S.uuid().nullable()}).strict(),rx=nc.extend({id:S.uuid(),redemptions:S.number().int().nonnegative()}).strict(),ix=S.strictObject({id:S.uuid(),programId:S.uuid().nullable(),customerId:S.uuid().nullable(),referrerId:S.uuid().nullable(),code:S.string().nullable(),status:S.enum(["pending","triggered","applied"]),createdAt:S.iso.datetime({offset:!0})}),xj=S.object({codes:S.array(rx).max(100),redemptions:S.array(ix).max(100),customers:S.record(S.uuid(),S.string()),codesCursor:S.uuid().nullable(),redemptionsCursor:S.uuid().nullable()}).strict(),vj=S.discriminatedUnion("action",[S.object({action:S.literal("create"),rewardId:S.uuid(),revision:S.number().int().nonnegative(),input:nc}).strict(),S.object({action:S.literal("remove"),rewardId:S.uuid(),revision:S.number().int().nonnegative(),codeId:S.uuid()}).strict()]);import{z as _}from"zod";import{z as F}from"zod";var yn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Li=e=>new Set(e).size===e.length,rc=F.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),ax=F.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),Bi=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"))),ox=F.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Lp=F.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Pj=["isOn","isOff","getFeatureValue","evalFeature","eval_feature"],Bp=F.strictObject({id:F.uuid(),repo:ax,platform:F.enum(["github","gitlab","bitbucket"]),branches:F.array(Bi).min(1).max(4).refine(Li),workflow:F.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:F.array(F.uuid()).min(1).max(4).refine(Li),include:F.array(Lp).min(1).max(16),exclude:F.array(Lp).max(16),methods:F.array(F.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Li),maxAgeHours:F.number().int().min(1).max(720)}),qp=Bp.extend({revision:F.number().int().positive()}),Cj=F.strictObject({repository:Bp,expectedRevision:F.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Vp=F.strictObject({repositoryId:F.uuid(),branch:Bi}),sx=F.array(rc).max(yn.keys).refine(Li),$p=F.strictObject({repository:qp.omit({keyIds:!0}),branch:Bi,keys:sx,keySetHash:F.string().regex(/^[a-f0-9]{64}$/)}),cx=F.strictObject({filePath:ox,startingLineNumber:F.number().int().min(1).max(1e7)}),ic=F.strictObject({protocol:F.literal(1),repositoryId:F.uuid(),branch:Bi,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(yn.files),sourceBytes:F.number().int().min(0).max(yn.sourceBytes),unresolvedCalls:F.number().int().min(0).max(1e6),unsupportedFiles:F.number().int().min(0).max(yn.files)}),features:F.array(F.strictObject({key:rc,refs:F.array(cx).max(yn.referencesPerKey)})).max(yn.keys)}).superRefine((e,t)=>{Li(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)>yn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),ac=F.strictObject({scanId:F.uuid(),commit:F.string(),receivedAt:F.string(),references:F.number().int().nonnegative(),removedReferences:F.number().int().nonnegative()}),ux=ac.extend({repositoryId:F.uuid(),branch:Bi,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:ic.shape.coverage}),lx=F.strictObject({repositories:F.array(qp).max(yn.repositories),scans:F.array(ux).max(yn.repositories*yn.branches)}),dx=F.strictObject({key:rc,references:F.number().int().nonnegative(),coveredTargets:F.number().int().nonnegative(),expiredTargets:F.number().int().nonnegative(),uncertainTargets:F.number().int().nonnegative()}),wj=F.strictObject({available:F.boolean().default(!0),settings:lx,expectedTargets:F.number().int().min(0).max(80),features:F.array(dx).max(2001),truncated:F.boolean()});import{z as J}from"zod";var oc=J.array(J.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"),Lr=J.intersection(pn,J.object({tags:oc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Qa=J.string().trim().max(80),Za=J.union([J.email().max(254),J.literal("")]),za=J.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Gp=J.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Hp=J.object({externalUserId:Gp.optional(),name:Qa.default(""),email:Za.default(""),attributes:Lr.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Br=J.discriminatedUnion("type",[J.strictObject({type:J.literal("id"),value:J.uuid()}),J.strictObject({type:J.literal("externalUserId"),value:Gp})]),qr=J.strictObject({name:Qa.optional(),email:Za.optional(),attributes:Lr.optional(),fingerprint:za.optional()}),_r=e=>!e.customerData||e.customer?.type==="externalUserId",yr="customerData requires an externalUserId customer",Vr=J.object({id:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),name:Qa,email:Za,attributes:Lr,createdAt:J.iso.datetime()}).strict(),Kp=J.object({customer:Vr,changed:J.boolean(),replayed:J.boolean()}).strict(),mx=J.discriminatedUnion("type",[J.object({type:J.literal("id"),value:J.uuid()}).strict(),J.object({type:J.literal("externalUserId"),value:J.string().trim().min(1).max(255)}).strict()]),px=J.object({name:Qa.optional(),email:Za.optional(),attributes:Lr.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:J.array(J.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:J.strictObject({add:oc,remove:oc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),sc=J.object({lookup:mx}).strict(),Wp=sc.extend({requestId:J.uuid(),patch:px}).strict(),Qp=J.object({search:J.string().trim().max(200).default(""),tag:J.string().trim().max(40).default(""),planId:J.string().max(200).default(""),versionId:J.string().max(200).default(""),holdingStatus:J.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:J.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:J.union([J.iso.datetime(),J.literal("")]).default(""),createdUntil:J.union([J.iso.datetime(),J.literal("")]).default(""),offset:J.coerce.number().int().min(0).max(1e5).default(0),limit:J.coerce.number().int().min(1).max(100).default(50)}).strict(),Zp=J.object({customers:Vr.array(),hasMore:J.boolean(),total:J.number().int().nonnegative().nullable(),evaluatedAt:J.iso.datetime()}).strict();import{z as Ht}from"zod";var cc=Ht.strictObject({customerId:Ht.uuid(),eventId:Ht.string().trim().min(1).max(200),grantId:Ht.uuid(),productVersionId:Ht.uuid(),subscriptionId:Ht.string().trim().min(1).max(255),occurredAt:Ht.iso.datetime({offset:!0})}),zp=cc.extend({id:Ht.uuid(),couponId:Ht.uuid(),status:Ht.literal("redeemed"),source:Ht.literal("merchant"),recordedAt:Ht.iso.datetime({offset:!0})});import{z as Re}from"zod";import{z as Ya}from"zod";var uc=Ya.strictObject({eventsEnabled:Ya.boolean(),experimentViewsEnabled:Ya.boolean(),featureUsageEnabled:Ya.boolean()}),Dj=Object.freeze({eventsEnabled:!1,experimentViewsEnabled:!0,featureUsageEnabled:!1});function Uj(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var Yp=fn.extend({analyticsConfig:uc,remoteFeatures:Re.array(Re.string().min(1).max(255)).max(500)}),Jp=Re.strictObject({attributes:pn,features:Re.array(Re.string().min(1).max(255)).min(1).max(500).optional(),customerId:Re.uuid().optional()}),fx=Re.strictObject({value:Ke,source:Re.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Re.boolean(),off:Re.boolean(),ruleId:Re.string(),experimentResult:vu.optional()}),Xp=Re.strictObject({generation:fn.shape.generation,evaluatedAt:fn.shape.evaluatedAt,expiresAt:fn.shape.expiresAt,features:Re.record(Re.string(),fx)}),ef=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(),Ke).default({}),deviceId:Re.string().min(1).max(255).optional(),sessionId:Re.string().min(1).max(255).optional()})).min(1).max(100)}),tf=Re.strictObject({inserted:Re.number().int().nonnegative(),duplicates:Re.number().int().nonnegative(),rejected:Re.number().int().nonnegative(),skipped:Re.number().int().nonnegative(),analyticsConfig:uc});import{z as W}from"zod";var lc=W.strictObject({name:W.string().trim().min(1).max(255),memo:W.string().max(1e4).nullable().optional(),footer:W.string().max(1e4).nullable().optional(),net_terms_days:W.number().int().positive().nullable().optional()}),hx=lc.extend({id:W.string().min(1).max(255),created_at:W.number().nullable()}),nf=W.strictObject({items:W.array(hx).max(50),nextCursor:W.string().nullable()}),Hj=W.discriminatedUnion("action",[W.strictObject({action:W.literal("create"),requestId:W.uuid(),values:lc}),W.strictObject({action:W.literal("update"),id:W.string().min(1).max(255),values:lc}),W.strictObject({action:W.literal("delete"),id:W.string().min(1).max(255)})]),rf=W.discriminatedUnion("action",[W.strictObject({action:W.literal("create"),requestId:W.uuid(),params:Rr}),W.strictObject({action:W.enum(["finalize","send","pay","void"]),requestId:W.uuid(),invoiceId:W.uuid()}),W.strictObject({action:W.literal("reissue"),requestId:W.uuid(),invoiceId:W.uuid(),params:js})]),dc=W.strictObject({id:W.uuid(),customerId:W.uuid(),providerInvoiceId:W.string().nullable(),status:W.enum(["draft","open","paid","void","uncollectible"]),currency:W.string(),totalMinor:W.string().regex(/^-?\d+$/),paidMinor:W.string().regex(/^\d+$/),refundedMinor:W.string().regex(/^\d+$/),hostedInvoiceUrl:W.url().nullable(),createdAt:W.number(),collectionMethod:W.enum(["send_invoice","charge_automatically"]).nullable()}),af=dc.extend({lines:W.array(W.strictObject({id:W.uuid(),description:W.string(),amountMinor:W.string().regex(/^-?\d+$/),netAmountMinor:W.string().regex(/^-?\d+$/),quantity:W.number().nullable(),periodStart:W.number().nullable(),periodEnd:W.number().nullable()})).max(1e3)}),qi=W.strictObject({taskId:W.uuid(),status:W.enum(["ready","running","done","dead"]),invoice:dc.nullable(),errorCode:W.string().nullable()}),of=W.strictObject({items:W.array(dc).max(50),nextCursor:W.uuid().nullable(),operations:W.array(qi).max(50),operationsLimited:W.boolean()}),Kj=qn;var gx=_.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"]),sf={scope:$e,permissions:_.array(gx),expiresAt:_.iso.datetime().nullable()},RN=_.discriminatedUnion("kind",[_.object({...sf,kind:_.literal("server"),keyId:_.string().min(1)}),_.object({...sf,kind:_.literal("customer"),customerId:_.string().min(1),identityKind:_.enum(["identified","guest"]),expiresAt:_.iso.datetime()})]),D=_.object({requestId:_.uuid(),scope:$e}).strict(),bx=Hp.safeExtend({fingerprint:za.optional()}).strict(),_x=D.extend({customer:Vr,created:_.boolean()}),yx=_.enum(["unassigned","unknown","scheduled","active","expired"]),kN=_.object({customerId:_.string().min(1),evaluatedAt:_.iso.datetime(),status:yx,validity:fs.nullable(),planVersion:Bl.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 cf(){return D.extend({offer:fi.nullable(),reason:va.nullable()})}var N={listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:_.strictObject({cursor:_.uuid().optional()}),response:D.extend({templates:nf})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),params:Rr}),response:D.extend({preview:Ns})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),requestId:_.uuid(),params:Rr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:qi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),command:rf}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:qi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),taskId:_.uuid()}),response:D.extend({operation:qi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),cursor:_.uuid().optional()}),response:D.extend({invoices:of})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),invoiceId:_.uuid()}),response:D.extend({invoice:af})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Vp,response:D.extend({config:$p})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:ic,response:D.extend({receipt:ac})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:_.strictObject({}),response:D.extend({payload:Yp})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Jp,response:D.merge(Xp)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:ef,response:D.merge(tf)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),sourceId:_.uuid()}),response:D.extend({balance:pp})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:mp}),response:D.extend({balance:Js})},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:os,model_markups:_a})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),query:Oa}),response:D.extend({usage:wi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Ld}),response:D.extend({usage:wi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:kd}),response:D.extend({grant:ws})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:jd,response:D.extend({grants:Nd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:_.union(Mm.options.map(e=>e.extend({customerId:_.uuid().optional(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:D.extend({operation:Lm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:wm.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Ls})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Om.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Ls})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Am.safeExtend({customerId:_.uuid()}),response:D.extend({batch:ki})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ja.extend({customerId:_.uuid()}),response:D.extend({batch:ki})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ja.extend({customerId:_.uuid()}),response:D.extend({batch:ki})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ja.extend({customerId:_.uuid()}),response:D.extend({batch:ki})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:_.discriminatedUnion("action",[Na.options[0].extend({customerId:_.uuid()}),Na.options[1].extend({customerId:_.uuid()}),Na.options[2].extend({customerId:_.uuid()})]),response:D.extend({trial:Ms})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Pm.extend({customerId:_.uuid()}),response:D.extend({trial:Ms})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Fa,response:D.extend({subscriptions:Dm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Fa,response:D.extend({purchases:Um})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:km,response:D.extend({conflicts:Fm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:jm,response:D.extend({resolution:Nm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Tm,response:D.extend({verification:Rm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:hm.safeExtend({customerId:_.uuid().optional()}),response:D.extend({quote:Ti})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:dr.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:kr})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:dr.extend({customerId:_.uuid().optional()}),response:D.extend({operation:kr})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:_m.safeExtend({customerId:_.uuid().optional()}),response:D.extend({quote:Sm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:dr.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:Us})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:dr.extend({customerId:_.uuid().optional()}),response:D.extend({operation:Us})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:xm.safeExtend({customerId:_.uuid()}),response:D.extend({quote:Im})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:dr.extend({customerId:_.uuid()}),response:D.extend({operation:ka})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:dr.extend({customerId:_.uuid()}),response:D.extend({operation:ka})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:cd,response:D.extend({controls:_s})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:td,response:D.extend({prepared:rd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:id,response:D.extend({authorization:Ia})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:md,response:D.extend({coupons:pd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:ad,response:D.extend({authorization:Ia})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:ld,response:D.extend({invoices:dd})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:ud,response:D.extend({invoice:gi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:_.object({customerId:_.uuid(),command:sd}).strict(),response:D.extend({controls:_s})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:_.object({customerId:_.uuid(),command:fp}).strict(),response:D.extend({entity:hp})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid().nullable(),query:xp}),response:D.extend({analytics:vp})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:_.object({customerId:_.uuid().nullable(),query:br}).strict(),response:D.extend({analytics:yp})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Ip,response:D.extend({batchId:_.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Ap,response:D.extend({batch:Pp})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Bm.extend({customerId:_.string().min(1).optional()}),response:D.extend({check:mr})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:lp,response:D.extend({paywall:Wa})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:_.strictObject({selector:Gm,customerId:_.string().min(1).optional(),commerce:jr,requirement:Vn.optional()}),response:D.extend({offering:Nr,candidates:_.array(qs).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:mr.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:Bd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),query:Vd}).strict(),response:D.extend({ledger:$d})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Dd.extend({customerId:_.uuid().optional()}),response:D.extend({detail:Ud})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Os.safeExtend({customerId:_.uuid().optional()}),response:D.extend({statement:Fd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),command:Pi.options[0]}).strict(),response:D.extend({quote:Ed})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:_.strictObject({customerId:_.uuid(),command:_.union([_.strictObject({eventName:_.string().min(1),quantity:Y.optional(),properties:Xe.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)}),_.strictObject({internal_feature_id:_.uuid(),quantity:Y.optional(),properties:Xe.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)})])}),response:D.extend({receipts:_.array(Ci).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:_.object({customerId:_.uuid(),command:Pi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:D.extend({receipt:Ci})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Np,response:D.extend({redemption:jp})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Fp,response:D.extend({referralCode:Mp})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Dp,response:D.extend({checkout:Up})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Hd,response:D.extend({seats:Rs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Kd,response:D.extend({seats:Rs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:bx,response:_x},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:sc,response:D.extend({customer:Vr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Qp,response:D.extend(Zp.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Wp,response:D.extend(Kp.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:za.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:Vr,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:cf()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:_.object({}).strict(),response:D.extend({offers:_.array(fi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"server",request:_.object({customerId:_.string().min(1).max(255),couponId:_.uuid(),requestId:_.uuid()}).strict(),response:cf()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:cc,response:D.extend({receipt:zp})}},jN={listInvoiceTemplates:N.listInvoiceTemplates,previewInvoice:N.previewInvoice,createInvoice:N.createInvoice,manageInvoice:N.manageInvoice,readInvoiceOperation:N.readInvoiceOperation,listInvoices:N.listInvoices,getInvoice:N.getInvoice,getCodeReferenceConfig:N.getCodeReferenceConfig,submitCodeReferences:N.submitCodeReferences,getFeatures:N.getFeatures,evaluateFeatures:N.evaluateFeatures,trackEvents:N.trackEvents,setupPayment:N.setupPayment,readPaymentSetup:N.readPaymentSetup,previewSubscriptionBatch:N.previewSubscriptionBatch,confirmSubscriptionBatch:N.confirmSubscriptionBatch,readSubscriptionBatch:N.readSubscriptionBatch,abandonSubscriptionBatch:N.abandonSubscriptionBatch,manageSubscriptionTrial:N.manageSubscriptionTrial,readSubscriptionTrial:N.readSubscriptionTrial,listSubscriptions:N.listSubscriptions,listPurchases:N.listPurchases,listSubscriptionConflicts:N.listSubscriptionConflicts,retrySubscriptionConflict:N.retrySubscriptionConflict,readAiPricing:N.readAiPricing,readUsage:N.readUsage,setUsage:N.setUsage,previewRefund:N.previewRefund,refund:N.refund,readRefund:N.readRefund,previewUpdate:N.previewUpdate,update:N.update,readSubscriptionUpdate:N.readSubscriptionUpdate,restoreNativePurchase:N.restoreNativePurchase,verifySubscriptions:N.verifySubscriptions,previewAttach:N.previewAttach,attach:N.attach,readSubscriptionOperation:N.readSubscriptionOperation,manageBalanceGrant:N.manageBalanceGrant,readBalanceSource:N.readBalanceSource,adjustBalance:N.adjustBalance,listBalanceGrants:N.listBalanceGrants,readBillingControls:N.readBillingControls,prepareBillingAuthorization:N.prepareBillingAuthorization,confirmBillingAuthorization:N.confirmBillingAuthorization,setBillingCoupons:N.setBillingCoupons,revokeBillingAuthorization:N.revokeBillingAuthorization,listBillingInvoices:N.listBillingInvoices,confirmBillingAdjustment:N.confirmBillingAdjustment,manageBillingLimits:N.manageBillingLimits,createCustomer:N.createCustomer,getCustomer:N.getCustomer,listCustomers:N.listCustomers,updateCustomer:N.updateCustomer,createSession:N.createSession,renewSession:N.renewSession,revokeSessions:N.revokeSessions,createGuestCustomer:N.createGuestCustomer,resumeGuestSession:N.resumeGuestSession,claimGuestCustomer:N.claimGuestCustomer,checkEntitlement:N.checkEntitlement,resolveOffering:N.resolveOffering,resolvePaywall:N.resolvePaywall,readHoldings:N.readHoldings,readLedger:N.readLedger,readBillingInvoice:N.readBillingInvoice,readCreditStatement:N.readCreditStatement,quoteBalance:N.quoteBalance,trackUsage:N.trackUsage,mutateBalance:N.mutateBalance,manageUsageEntity:N.manageUsageEntity,readUsageAnalytics:N.readUsageAnalytics,readCreditAnalytics:N.readCreditAnalytics,submitUsageBatch:N.submitUsageBatch,readUsageBatch:N.readUsageBatch,listOffers:N.listOffers,grantOffer:N.grantOffer,recordCouponRedemption:N.recordCouponRedemption,redeemCoupon:N.redeemCoupon,redeemReward:N.redeemReward,createReferralCode:N.createReferralCode,claimRewardProduct:N.claimRewardProduct,readSeats:N.readSeats,manageSeat:N.manageSeat};import{z as mc}from"zod";var Sx="[a-f0-9]{64}",uf="[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",xx="[a-zA-Z][a-zA-Z0-9_.-]{0,63}",vx="[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?",pc=new RegExp(`^/web-view/screens/(${Sx})/(?:funnel/(${uf})/(${xx})|paywall/(${uf}))/(${vx})$`),lf=mc.string().max(256).regex(pc,"Invalid screen render address"),df=mc.union([lf,mc.string().max(512).regex(new RegExp(`^(?:https://[a-z0-9.-]+(?::[0-9]{1,5})?|http://(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?)${pc.source.slice(1)}`),"Invalid screen render URL")]);function LN(e){let t=e.kind==="funnel"?`/web-view/screens/${e.tag}/funnel/${e.versionId}/${e.screenId}/${e.locale}`:`/web-view/screens/${e.tag}/paywall/${e.versionId}/${e.locale}`;return lf.parse(t)}function BN(e){let t=pc.exec(e);if(!t)return null;let[,n,r,i,a,o]=t;return!n||!o||!tn.safeParse(o).success?null:r&&i?{kind:"funnel",tag:n,versionId:r,screenId:i,locale:o}:a?{kind:"paywall",tag:n,versionId:a,locale:o}:null}var qN={funnel:e=>`screen-render:funnel:${e}`,funnelVersion:e=>`screen-render:funnel-version:${e}`,paywall:e=>`screen-render:paywall:${e}`,paywallVersion:e=>`screen-render:paywall-version:${e}`};var tt={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},$N="00000000-0000-0000-0000-000000000000";var pf={primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},Vi=(e,t,n,r,i)=>({kind:"screen",schemaVersion:4,name:e,surface:"popup",presentation:{type:"modal",size:"md"},theme:{...pf},pages:[{id:"main",name:"\u4E3B\u9875\u9762",root:t}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":n,en:r}},actions:i}),$r=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}}}),Ja={id:"dismiss",type:"close",event:"popup.dismissed",properties:{},close:!0},mf=[{id:"blank",label:"\u7A7A\u767D",description:"\u4E00\u4E2A\u6807\u9898\u548C\u4E00\u4E2A\u6309\u94AE\uFF0C\u4ECE\u96F6\u5F00\u59CB\u642D\u3002",document:Vi("\u672A\u547D\u540D\u5F39\u7A97",$r([{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"},[Ja])},{id:"announcement",label:"\u516C\u544A",description:"\u65B0\u529F\u80FD\u6216\u91CD\u8981\u901A\u77E5\uFF0C\u4E00\u4E2A\u4E3B\u6309\u94AE\u3002",document:Vi("\u65B0\u529F\u80FD\u516C\u544A",$r([{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},Ja])},{id:"upgrade",label:"\u5347\u7EA7\u5230 Pro",description:"\u5217\u51FA\u51E0\u9879\u6743\u76CA\uFF0C\u5F15\u5BFC\u5347\u7EA7\u3002",document:Vi("\u5347\u7EA7\u5230 Pro",$r([{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},Ja])},{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:{...Vi("\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},Ja]),theme:{...pf,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:Vi("\u6EE1\u610F\u5EA6\u8C03\u67E5",$r([{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 Xa(e="blank"){let t=mf.find(n=>n.id===e)??mf[0];if(!t)throw new Error("Screen templates are unavailable");return structuredClone(t.document)}var Ix=(e,t,n)=>({type:"stack",id:e,name:"Web \u81EA\u9002\u5E94\u5E03\u5C40",direction:"horizontal",align:"center",justify:"center",children:[{...$r(t),id:`${e}_intro`,name:"\u4ECB\u7ECD",style:{width:480,gap:20,padding:{top:0,right:0,bottom:0,left:0}}},{...$r(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 HN(e,t="blank"){let n=Xa(t);if(e==="popup"||(n.surface=e,n.presentation={type:"fullscreen"},e==="page"))return n;if(e==="paywall"){let r=Xa("upgrade");r.actions=r.actions.map(o=>o.id==="upgrade"&&o.type==="event"?{...o,event:"paywall.upgrade_clicked",properties:{},close:!1}:o),(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 a=i.root.children;return i.root=Ix("root",[...a.slice(0,2),{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}}],a.slice(2)),{...r,surface:e,presentation:{type:"fullscreen"},name:"\u9AD8\u7EA7\u529F\u80FD\u4ED8\u8D39\u5899"}}return{...n,surface:e,presentation:{type:"fullscreen"}}}function ff(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=Xa(),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 he}from"zod";var $i=he.number().int().min(0).max(1e4),YN=he.strictObject({couponId:he.uuid(),couponRevision:he.number().int().nonnegative(),savedGroupId:he.uuid(),savedGroupRevision:he.number().int().nonnegative(),savedGroupName:he.string().min(1).max(128),count:$i,snapshotHash:he.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:he.iso.datetime({offset:!0})}),Ax=he.strictObject({id:he.uuid(),couponId:he.uuid(),couponName:he.string().min(1).max(80),savedGroupId:he.uuid(),savedGroupName:he.string().min(1).max(128),savedGroupRevision:he.number().int().nonnegative(),status:he.enum(["pending","running","completed"]),total:$i,issued:$i,skipped:$i,remaining:$i,createdAt:he.iso.datetime({offset:!0}),completedAt:he.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)),Px=he.strictObject({id:he.uuid(),customerId:he.uuid(),customerName:he.string().max(255),position:he.number().int().min(1).max(1e4),status:he.enum(["pending","issued","skipped"]),grantId:he.uuid().nullable(),reason:va.nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),JN=he.strictObject({batch:Ax,recipients:he.array(Px).max(50),nextPosition:he.number().int().min(1).max(1e4).nullable()}),XN=he.discriminatedUnion("action",[he.strictObject({action:he.literal("create"),requestId:he.uuid(),couponId:he.uuid(),couponRevision:he.number().int().nonnegative(),savedGroupId:he.uuid(),savedGroupRevision:he.number().int().nonnegative(),snapshotHash:he.string().regex(/^[a-f0-9]{64}$/)}),he.strictObject({action:he.literal("process"),batchId:he.uuid()})]);import{z as L}from"zod";var It=L.number().int().min(0),Gi=L.iso.datetime({offset:!0}),eo=L.strictObject({internalId:L.uuid(),version:L.number().int().positive()}),hf=L.enum(["subscription_change_required","unsupported_operation_input"]),Cx=L.enum([...hf.options,"internal_error"]),nD=L.strictObject({productId:L.string().min(1),productName:L.string(),from:eo,to:eo,noBillingChanges:L.boolean(),counts:L.strictObject({customers:It,movable:It,blocked:It,unsupported:It,canceled:It,custom:It}),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:hf.nullable()})).max(50),nextCursor:L.uuid().nullable()}),wx=L.enum(["queued","running","succeeded","no_changes","failed","canceled"]),gf=L.enum(["running","succeeded","skipped","failed"]),bf=L.strictObject({internalId:L.uuid(),id:L.string().min(1),productId:L.string().min(1),productName:L.string(),from:eo,to:eo,noBillingChanges:L.boolean(),retryFailed:L.boolean(),step:L.enum(["queued","received","get_customers","migrate_customers","finished","failed"]),snapshot:L.strictObject({total_customers:It,canceled_customers:It,custom_customers:It,migration_customers:It}),createdAt:Gi,run:L.strictObject({id:L.uuid(),status:wx,errorMessage:L.string().nullable(),createdAt:Gi,startedAt:Gi.nullable(),finishedAt:Gi.nullable()}).nullable(),totals:L.strictObject({succeeded:It,skipped:It,failed:It,running:It,blocked:It,remaining:It})}),Ox=L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),status:gf,skipReason:L.enum(["no_updates_needed","ineligible"]).nullable(),updatedAt:Gi,error:L.strictObject({code:Cx,message:L.string().nullable()}).nullable()}),rD=L.strictObject({migration:bf,items:L.array(Ox).max(50),nextCursor:L.uuid().nullable()}),iD=L.array(bf).max(20),aD=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()})]),oD=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:gf.optional(),after:L.uuid().optional()}),L.strictObject({action:L.literal("list"),productId:L.string().min(1).max(120)})]);import{z as ht}from"zod";var fc=ht.iso.datetime({offset:!0}),_f=ht.strictObject({internalId:ht.uuid(),productId:ht.string().min(1),name:ht.string(),version:ht.number().int().positive()}),Ex=ht.strictObject({id:ht.uuid(),status:ht.literal("scheduled"),effectiveAt:fc,createdAt:fc,entityId:ht.string().nullable(),to:_f,from:_f.extend({customerProductId:ht.uuid(),status:ht.enum(["active","past_due","trialing"]),endsAt:fc.nullable()}).nullable(),scheduleId:ht.uuid().nullable(),providerManaged:ht.boolean()}),uD=ht.array(Ex).max(100),lD=ht.strictObject({customerProductId:ht.uuid()});import{z as Hi}from"zod";var Tx=Hi.url().refine(e=>new URL(e).protocol==="https:"),pD=Hi.strictObject({requestId:Hi.uuid()}),fD=Hi.strictObject({url:Tx,createdAt:Hi.iso.datetime()});import{z as Je}from"zod";var yf=Je.object({id:Je.uuid(),key:Je.string().nullable(),label:Je.string().min(1).max(80),description:Je.string().max(300),category:Je.string().min(1).max(40),tags:Je.array(Je.string().max(30)).max(10),surface:Zs,source:Je.enum(["official","private"]),document:Tt,revision:Je.number().int().positive(),archived_at:Je.string().nullable(),created_at:Je.string()}).strict(),_D=Je.object({projectId:Je.uuid(),environmentId:Je.uuid(),label:Je.string().trim().min(1).max(80),description:Je.string().trim().max(300),category:Je.string().trim().min(1).max(40),document:Tt}).strict(),yD=Je.object({projectId:Je.uuid(),environmentId:Je.uuid(),id:Je.uuid(),revision:Je.number().int().positive()}).strict();import{z as B}from"zod";import{z as Ee}from"zod";var Ki=Ke;function Sf(e){let t={};for(let[n,r]of Object.entries(e.results??{})){let i=n.split(".");if(i.some(s=>["__proto__","constructor","prototype"].includes(s)))throw new Error("Reserved result path");let a=t;for(let s of i.slice(0,-1)){Object.hasOwn(a,s)||(a[s]={});let c=a[s];if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Ambiguous result path");a=c}let o=i.at(-1);if(o===void 0)throw new Error("Empty result path");a[o]=r}return{...e.attributes,parameters:e.parameters,answers:e.answers,results:t}}function hc(e,t){return yu(Sf(t),e,t.savedGroups)}function Wi(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i.startsWith("$")||t.add(i),i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.attributeKey=="string"&&t.add(a.attributeKey),["$and","$or","$nor","$not"].includes(i)&&n(a)}return n(e),[...t]}import{z as rt}from"zod";var to=rt.discriminatedUnion("kind",[rt.object({kind:rt.literal("ledger"),cursor:Ea}).strict(),rt.object({kind:rt.literal("billing"),cursor:rt.uuid()}).strict()]),Rx=rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Qi=rt.record(rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),rt.union([rt.string().max(500),rt.boolean(),rt.array(rt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),kx=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function gc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>gc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||kx.test(n)||gc(r,t+1)))}var jx=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,un=rt.record(Rx,Ke).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!gc(e)&&!jx.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function CD(e){let t=Object.create(null);for(let[n,r]of new URL(e).searchParams)rt.string().max(500).parse(r),Object.hasOwn(t,n)||(t[n]=r);return un.parse(t),t}var xf=rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),bc=rt.array(rt.object({key:xf,componentId:xf,required:rt.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.key)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),wD=rt.object({bindings:bc,answers:Qi}).strict();import{z as Sr}from"zod";var Gn=Sr.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"),no=Sr.discriminatedUnion("source",[Sr.strictObject({source:Sr.literal("literal"),value:Ke}),Sr.strictObject({source:Sr.enum(["parameter","answer","attribute","result"]),key:Sr.string().min(1).max(255),path:Gn.optional()})]);function ro(e,t){if(!t)return e;for(let n of Gn.parse(t).split(".")){if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function _c(e,t){if(e.source==="literal")return structuredClone(e.value);let n=e.source==="parameter"?t.parameters:e.source==="answer"?t.answers:e.source==="attribute"?t.attributes:t.results??{};if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Ke.parse(ro(n[e.key],e.path)))}function vf(e,t){let n={},r=Object.entries(e).sort(([i],[a])=>i.split(".").length-a.split(".").length||i.localeCompare(a,"en",{numeric:!0}));for(let[i,a]of r){let o=Gn.parse(i).split("."),s=n;for(let u=0;u<o.length-1;u++){let l=o[u],d=o[u+1];if(l===void 0||d===void 0)throw new Error("Invalid binding path");if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>s.length))throw new Error("Invalid array binding index");Object.hasOwn(s,l)||Reflect.set(s,l,/^(0|[1-9]\d*)$/.test(d)?[]:{});let 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=o.at(-1);if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(c)||Number(c)>s.length))throw new Error("Invalid array binding index");Reflect.set(s,c,_c(a,t))}return n}var io=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),If=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),ao=un.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),yc=Ee.record(io,Ee.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),Nx=no,Af=Ee.strictObject({type:Ee.literal("external_task"),endpointId:Ee.uuid(),taskKey:io,inputs:Ee.record(io,Nx).refine(e=>Object.keys(e).length<=20),outputs:yc}),Pf=Ee.strictObject({maxAttempts:Ee.number().int().min(1).max(5),retryDelaySeconds:Ee.number().int().min(1).max(30),backoff:Ee.enum(["fixed","exponential"]),requestTimeoutSeconds:Ee.number().int().min(1).max(10),timeoutSeconds:Ee.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline"),FD={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},MD=Ee.strictObject({outcome:Ee.enum(["success","failure"]),data:ao});function LD(e,t){let n=ao.parse(t);if(Object.keys(n).length!==Object.keys(e).length||Object.entries(e).some(([r,i])=>!Object.hasOwn(n,r)||(i==="strings"?!Array.isArray(n[r])||!n[r].every(a=>typeof a=="string"):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function BD(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=_c(i,t);return ao.parse(n)}var qD=Ee.discriminatedUnion("operation",[Ee.strictObject({operation:Ee.literal("signal"),runId:Ee.uuid(),nodeId:If,eventName:io,eventId:Ee.uuid(),data:ao}),Ee.strictObject({operation:Ee.literal("read_results"),runId:Ee.uuid()})]),VD=Ee.strictObject({scope:$e,runId:Ee.uuid(),eventId:Ee.uuid(),accepted:Ee.boolean()}),Dx=Ee.record(If,Ki),$D=Ee.strictObject({scope:$e,runId:Ee.uuid(),results:Dx});import{z as ge}from"zod";var Sc=ge.discriminatedUnion("type",[ge.strictObject({type:ge.literal("literal"),value:Ke}),ge.strictObject({type:ge.literal("feature"),featureKey:ge.string().min(1).max(128)})]),Ux=ge.strictObject({requestId:ge.uuid(),decisionId:ge.uuid(),customerId:ge.uuid(),externalUserId:ge.string().min(1).max(255).nullable(),versionId:ge.uuid(),receiptId:ge.uuid(),value:Ke}),xc={funnelId:ge.uuid(),requestId:ge.uuid(),customer:Br,customerData:qr.optional(),attributes:pn.refine(e=>!["parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"parameters, answers and results are reserved flow namespaces")},ZD=ge.discriminatedUnion("operation",[ge.strictObject({operation:ge.literal("decide"),...xc}).refine(_r,yr),ge.strictObject({operation:ge.literal("read_decision"),decisionId:ge.uuid()}),ge.strictObject({operation:ge.literal("feature_config"),funnelId:ge.uuid()}),ge.strictObject({operation:ge.literal("configuration"),funnelId:ge.uuid()}),ge.strictObject({operation:ge.literal("report_used"),decisionId:ge.uuid(),eventId:ge.uuid(),occurredAt:ge.iso.datetime({offset:!0}),reference:ge.string().min(1).max(128).optional()})]),zD=ge.strictObject({scope:$e,decisionId:ge.uuid(),requestId:ge.uuid(),status:ge.enum(["pending","completed","failed"]),decision:Ux.nullable()}).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"),YD=ge.strictObject({scope:$e,decisionId:ge.uuid(),eventId:ge.uuid(),source:ge.literal("caller_reported")});import{z as Kt}from"zod";var Cf=Kt.strictObject({type:Kt.literal("bundle"),paywallVersionId:Kt.uuid().optional(),couponIds:Kt.array(Kt.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Bundle Coupons must be unique"),data:Ke}),n2=Kt.strictObject({type:Kt.literal("bundle"),paywall:Kt.strictObject({versionId:Kt.uuid(),paywallId:Kt.uuid(),offeringVersionId:Kt.uuid()}).nullable(),coupons:Kt.array(fi).max(20),data:Ke});import{z as Wt}from"zod";import{z as gt}from"zod";var wf=gt.union([gt.string(),gt.number().finite(),gt.boolean(),gt.null()]),Fx=gt.union([wf,gt.array(wf).min(1).max(20)]),Mx=gt.record(Gn,Fx).refine(e=>Object.keys(e).length<=10),vc=gt.strictObject({path:Gn,type:gt.enum(["string","number","boolean","strings"]),nullable:gt.boolean().optional(),aggregation:gt.enum(["count","exists"]).optional(),where:Mx.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 o2(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{let i=vc.parse(r),a=ro(t,i.path);if(i.nullable&&a==null)return[n,null];if(i.aggregation){if(!Array.isArray(a))throw new Error("Collection projection requires an array");let s=a.filter(c=>Object.entries(i.where??{}).every(([u,l])=>{let d=ro(c,u);return Array.isArray(l)?l.some(m=>m===d):l===d}));return[n,i.aggregation==="count"?s.length:s.length>0]}let o=i.type==="strings"?gt.array(gt.string()):i.type==="string"?gt.string():i.type==="number"?gt.number().finite():gt.boolean();return[n,o.parse(a)]}))}var Lx=["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"],Ic=Wt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Bx=no,Of=Wt.discriminatedUnion("type",[Af,Wt.strictObject({type:Wt.literal("claim_offer"),couponId:Wt.uuid()}),Wt.strictObject({type:Wt.literal("event"),event:Ic}),Wt.strictObject({type:Wt.literal("api"),operation:Wt.enum(Lx),inputs:Wt.record(Gn,Bx).refine(e=>Object.keys(e).length<=40),resultKey:Ic,outputs:Wt.record(Ic,vc).refine(e=>Object.keys(e).length<=20)})]);function m2(e,t){return vf(e,t)}import{z as qx}from"zod";var Sn=qx.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");var Qe=B.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vx=B.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),Qt={id:Qe,name:B.string().trim().min(1).max(80),position:B.strictObject({x:B.number().finite(),y:B.number().finite()}).optional()},$x={success:Qe,cancel:Qe,unavailable:Qe,failure:Qe},Ac=B.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Pc=B.enum(["same_window","new_window"]),Gx=B.discriminatedUnion("type",[B.strictObject({...Qt,type:B.literal("entry"),next:Qe}),B.strictObject({...Qt,type:B.literal("screen"),screenId:Qe,presentation:On,outputs:B.record(Qe,Qe),offering:B.discriminatedUnion("source",[B.strictObject({source:B.literal("result"),key:Sn}),B.strictObject({source:B.literal("fixed"),versionId:B.uuid()})]).optional()}),B.strictObject({...Qt,type:B.literal("offering"),configuration:B.discriminatedUnion("source",[B.strictObject({source:B.literal("fixed"),versionId:B.uuid()}),B.strictObject({source:B.literal("feature"),featureKey:B.string().min(1).max(128)})]),resultKey:Sn,next:Qe}),B.strictObject({...Qt,type:B.literal("coupon"),couponId:B.uuid(),resultKey:Sn,next:Qe}),B.strictObject({...Qt,type:B.literal("output"),value:B.discriminatedUnion("type",[...Sc.options,Cf,B.strictObject({type:B.literal("result"),key:Sn}),B.strictObject({type:B.literal("selection"),screenId:Qe,offeringKey:Sn})])}),B.strictObject({...Qt,type:B.literal("condition"),cases:B.array(B.strictObject({condition:Nn,target:Qe})).min(1).max(50),default:Qe}),B.strictObject({...Qt,type:B.literal("feature"),featureKey:B.string().min(1).max(128),next:Qe}),B.strictObject({...Qt,type:B.literal("split"),experimentId:B.uuid(),routes:B.record(Vx,Qe).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Qe}),B.strictObject({...Qt,type:B.literal("action"),...$x,execution:Pf,action:Of}),B.strictObject({...Qt,type:B.literal("external_page"),url:Ac,openIn:Pc,opened:Qe,failed:Qe}),B.strictObject({...Qt,type:B.literal("end"),outcome:B.enum(["completed","closed","ineligible","failed"]),output:Sc.optional()}),B.strictObject({...Qt,type:B.literal("wait"),wait:B.discriminatedUnion("type",[B.strictObject({type:B.literal("duration"),delaySeconds:B.number().int().min(1).max(2592e3),elapsed:Qe}),B.strictObject({type:B.literal("event"),eventName:Qe,outputs:yc,timeoutSeconds:B.number().int().min(1).max(2592e3),received:Qe,timeout:Qe})])})]),Cc=B.strictObject({version:B.literal(4),entry:Qe,nodes:B.array(Gx).min(1).max(tt.flowNodes)}),wc=Cc.superRefine((e,t)=>{Hx(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Gr(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":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 Hx(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>tt.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>tt.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let d of Gr(l))d===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(d)||i(`Missing target ${d}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let d of Gr(r.get(l)))u(d);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}function Kx(e,t){let n=e.cases.findIndex(r=>hc(r.condition,t));return{ruleIndex:n<0?null:n,target:e.cases[n]?.target??e.default}}function C2(e,t,n,r){let i=e.nodes.find(c=>c.id===t.nodeId),a=[...t.history];if(!i||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let o,s=[];switch(n.type){case"start":if(i.type!=="entry")throw new Error("Flow already started");o=i.next;break;case"next":if(i.type!=="screen"||!Object.hasOwn(i.outputs,n.output)||i.outputs[n.output]===void 0)throw new Error("Invalid screen output");{let c=i.outputs[n.output];if(c===void 0)throw new Error("Invalid screen output");o=c}a.push(i.id);break;case"back":if(i.type!=="screen"||!a.length)throw new Error("No previous screen");if(o=a.pop(),e.nodes.find(c=>c.id===o)?.type!=="screen")throw new Error("Invalid screen history");break;case"condition":if(i.type!=="condition")throw new Error("Not a condition node");{let c=Kx(i,r);o=c.target,s.push({nodeId:i.id,...c})}break;case"feature":if(i.type!=="feature")throw new Error("Not a Feature node");o=i.next;break;case"configuration":if(i.type!=="offering"&&i.type!=="coupon")throw new Error("Not a configuration node");o=i.next;break;case"assignment":if(i.type!=="split")throw new Error("Not an Experiment node");{let c=n.variantId===null?i.notParticipating:i.routes[n.variantId];if(!c)throw new Error("Unknown native Variant key");o=c}break;case"result":if(i.type!=="action")throw new Error("Not a capability invocation");o=i[n.result];break;case"page":if(i.type!=="external_page")throw new Error("Not an external page");o=i[n.result];break;case"wait":if(i.type!=="wait")throw new Error("Not a wait node");if(i.wait.type==="duration"){if(n.result!=="elapsed")throw new Error("Invalid timer result");o=i.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid event result");o=i.wait[n.result]}break}if(!e.nodes.some(c=>c.id===o))throw new Error("Target does not exist");return{state:{nodeId:o,history:a.slice(-tt.pages),status:"running"},entered:[o],routed:s}}import{z as U}from"zod";function ln(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),d=l.replace(".","").length,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}function Ef(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Wi(c.condition))u.startsWith("results.")&&a(u.slice(8),!0)}if(e.type==="screen"&&e.offering?.source==="result"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="result"&&a(s.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;return o?.type==="result"&&a(o.key),o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as O}from"zod";var Hr=O.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),oo=e=>O.record(O.string(),Ke).refine(t=>ln(t)<=e,"Funnel evidence exceeds its byte budget"),D2=O.enum(["presentation","timer","event","operation"]),Ec=O.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Tc=O.discriminatedUnion("type",[O.strictObject({type:O.literal("flag"),key:O.string().min(1).max(128)}),O.strictObject({type:O.literal("experiment"),id:O.uuid()}),O.strictObject({type:O.literal("saved_group"),id:O.uuid()}),O.strictObject({type:O.literal("config"),key:O.string().min(1).max(128)}),O.strictObject({type:O.literal("constant"),key:O.string().min(1).max(128)}),O.strictObject({type:O.literal("paywall_version"),id:O.uuid()}),O.strictObject({type:O.literal("offering_version"),id:O.uuid()}),O.strictObject({type:O.literal("reward"),id:O.uuid()})]),U2=O.strictObject({schemaVersion:O.literal(1),kind:Ec,selector:Tc.nullable(),context:oo(131072),contract:O.strictObject({version:O.number().int().positive(),evaluator:O.string().min(1).max(128),policyRevision:O.number().int().nonnegative()})}).refine(e=>ln(e)<=131072,"Node input exceeds its byte budget"),F2=O.strictObject({schemaVersion:O.literal(1),kind:Ec,outcome:O.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:oo(131072),route:O.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:oo(131072)}).refine(e=>ln(e)<=131072,"Node result exceeds its byte budget"),M2=O.strictObject({schemaVersion:O.literal(1),operations:O.record(Hr,O.strictObject({attempts:O.number().int().nonnegative(),maxAttempts:O.number().int().min(1).max(5),deadlineAt:O.iso.datetime({offset:!0}),retryAt:O.iso.datetime({offset:!0}).nullable(),error:O.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:O.strictObject({type:Hr,id:O.uuid()}).nullable()}))}).refine(e=>ln(e)<=65536,"Execution state exceeds its byte budget"),xr={receiptId:O.uuid()},Oc=O.iso.datetime({offset:!0}),L2=O.discriminatedUnion("type",[O.strictObject({type:O.literal("node_entered"),details:O.strictObject({kind:Ec})}),O.strictObject({type:O.literal("presentation_shown"),details:O.strictObject({...xr,source:O.literal("client"),occurredAt:Oc.optional()})}),O.strictObject({type:O.literal("decision_accepted"),details:O.strictObject(xr)}),O.strictObject({type:O.literal("signal_received"),details:O.strictObject({signalId:O.uuid(),nodeId:Hr,eventName:Hr,data:oo(8192),source:O.literal("server"),occurredAt:Oc})}),O.strictObject({type:O.literal("signal_consumed"),details:O.strictObject({...xr,signalId:O.uuid()})}),O.strictObject({type:O.literal("wait_elapsed"),details:O.strictObject(xr)}),O.strictObject({type:O.literal("wait_timeout"),details:O.strictObject(xr)}),O.strictObject({type:O.literal("operation_completed"),details:O.strictObject({...xr,operation:Hr,reference:O.strictObject({type:Hr,id:O.uuid()}).nullable()})}),O.strictObject({type:O.literal("execution_recovered"),details:O.strictObject({generation:O.number().int().positive(),reason:O.enum(["interrupted","expired_lease","delivery_failed"])})}),O.strictObject({type:O.literal("execution_failed"),details:O.strictObject({generation:O.number().int().positive(),code:O.string().regex(/^[a-z_]{1,64}$/)})}),O.strictObject({type:O.literal("run_completed"),details:O.strictObject({outcome:O.enum(["completed","ineligible","failed"])})}),O.strictObject({type:O.literal("run_closed"),details:O.strictObject({source:O.enum(["client","server","expiry"])})}),O.strictObject({type:O.literal("treatment_used"),details:O.strictObject({...xr,source:O.enum(["client","server"]),occurredAt:Oc,reference:O.string().min(1).max(128).optional()})})]);var Zt=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Wx=U.discriminatedUnion("type",[U.strictObject({id:Zt,type:U.literal("owned"),document:Tt.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")}),U.strictObject({id:Zt,type:U.literal("paywall"),paywallVersionId:U.uuid()})]),Tf=U.strictObject({type:U.enum(["string","number","boolean","strings","json"]),nullable:U.boolean()}),jc={kind:U.literal("funnel"),schemaVersion:U.literal(3),screens:U.array(Wx).max(tt.pages),references:U.record(Zt,Tc).refine(e=>Object.keys(e).length<=500),inputs:U.array(U.strictObject({key:Zt,screenId:Zt,componentId:Zt,required:U.boolean()})).max(tt.questions),variables:U.record(Sn,Tf).refine(e=>Object.keys(e).length<=tt.logicNodes),outputSchema:Tf,execution:U.strictObject({runTimeoutSeconds:U.number().int().min(1).max(2592e3),maxTransitions:U.number().int().min(1).max(1e4)})},Bt=U.strictObject({...jc,graph:Cc});function kf(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])),a=(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 o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(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],x=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;if(x&&!a("flag",x)&&n("Flag selectors require an explicit GB resource reference","feature",h),p.type==="feature"&&u(p.featureKey,p),(p.type==="offering"||p.type==="coupon")&&u(p.resultKey,p),p.type==="action"&&p.action.type==="api"&&u(p.action.resultKey,p),p.type==="action"&&p.action.type==="external_task")for(let I of Object.keys(p.action.outputs))u(`${p.id}.${I}`,p);if(p.type==="wait"&&p.wait.type==="event")for(let I of Object.keys(p.wait.outputs))u(`${p.id}.${I}`,p);if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),p.type==="action"&&p.action.type==="claim_offer"&&!a("reward",p.action.couponId)&&n("Coupon claims require a Reward reference","coupon",h),p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),p.type==="screen"){let I=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("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"&&!a("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}Fr(I.document).some(T=>!T.complete)&&n("Owned screens require complete local content","translations",h);let j=new Set(I.document.actions.map(T=>T.id));(j.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(T=>!j.has(T)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),_n(v.root,T=>{!p.offering&&(T.type==="plan_picker"||(T.type==="stack"||T.type==="button")&&T.bind?.plan||T.type==="customer_data"&&["customer_plans","credit_packs"].includes(T.data.source))&&n("Product presentation requires an Offering Version","offering",h),T.type==="customer_data"&&Object.values(T.data.outputs??{}).some(P=>P!==void 0&&!j.has(P))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}if(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"&&!Rf(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",h),p.type==="output"&&p.value.type==="literal"&&!Rf(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",h),p.type==="condition")for(let I of p.cases){for(let v of ia(I.condition))a("saved_group",v)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let v of Wi(I.condition))v.startsWith("answers.")&&!e.inputs.some(j=>j.key===v.slice(8))&&n("Unknown answer reference","answer",h)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h),p.value.paywallVersionId&&!a("paywall_version",p.value.paywallVersionId)&&n("Bundle Paywall requires an explicit Version reference","paywall",h);for(let I of p.value.couponIds)a("reward",I)||n("Bundle Coupons require explicit Reward references","coupon",h)}}for(let[g,p]of e.graph.nodes.entries())for(let h of Ef(p,c)){let v=function(j){if(j===p.id)return!0;if(I.has(j))return!1;I.add(j);let T=e.graph.nodes.find(_e=>_e.id===j);return T?(x.has(j)?T.type==="action"?[T.cancel,T.unavailable,T.failure]:T.type==="wait"&&T.wait.type==="event"?[T.wait.timeout]:[]:Gr(T)).some(v):!1};var m=v;if(!Object.hasOwn(e.variables,h)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let x=s.get(h)??new Set,I=new Set;(!x.size||v(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}(new Set(e.inputs.map(g=>g.key)).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()){let h=i.get(p.screenId),x=h?.type==="owned"?Mi(h.document,p.componentId):null;(x?.type!=="stack"||!x.interaction||!["input","toggle","select","multiselect","tabs"].includes(x.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g])}let l=0,d=0;for(let g of e.screens)if(g.type==="owned"){for(let p of g.document.pages)_n(p.root,()=>{l++});d+=g.document.actions.length}(l>tt.components||d>tt.actions||ln(e)>tt.documentBytes)&&n("Funnel document exceeds its budget","budget")}var jf=U.strictObject({...jc,graph:wc}).superRefine(kf),Nf=U.strictObject({...jc,graph:wc,displayName:U.string().trim().min(1).max(80)}).superRefine(kf);function Rf(e,t){return t===null?e.nullable:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type)}var Rc=U.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),so={requestId:U.uuid(),nodeId:Zt,visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),customerToken:Rc.optional()},Qx=U.discriminatedUnion("type",[U.strictObject({type:U.literal("screen"),output:Zt,answers:Qi,selection:U.record(Zt,U.union([U.string().max(200),U.boolean()])).optional()}),U.strictObject({type:U.literal("paywall_quote"),actionId:Zt,productVersionId:U.uuid(),offerId:U.uuid().optional(),nativeOffer:Bn.optional()}),U.strictObject({type:U.literal("paywall_confirm"),operationId:U.uuid()}),U.strictObject({type:U.literal("paywall_cancel"),operationId:U.uuid()}),U.strictObject({type:U.literal("client_action"),receiptId:U.uuid(),outcome:U.enum(["success","cancel","failure","opened","failed"])})]),Zx=U.object({nodeId:Zt,visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),components:U.record(Zt,U.object({resourceKey:U.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:U.number().int().min(1).max(1e5),after:to.nullable(),filter:U.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Zi=U.discriminatedUnion("operation",[U.strictObject({operation:U.literal("start"),funnelId:U.uuid(),requestId:U.uuid(),customer:Br.optional(),customerData:qr.optional(),locale:U.string().min(1).max(35),parameters:un}).refine(_r,yr),U.strictObject({operation:U.literal("get"),data:Zx.optional(),purchase:U.strictObject({receiptId:U.uuid(),operationId:U.uuid()}).optional(),customerToken:Rc.optional()}),U.strictObject({operation:U.literal("resume"),requestId:U.uuid(),customerToken:Rc.optional()}),U.strictObject({operation:U.literal("submit"),...so,input:Qx}),U.strictObject({operation:U.literal("back"),...so}),U.strictObject({operation:U.literal("shown"),...so}),U.strictObject({operation:U.literal("close"),...so})]);function kc(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=kc(n,t);if(r)return r}return null}function zx(e,t,n,r,i){let a=e.graph.nodes.find(u=>u.id===t);if(a?.type!=="screen")throw new Error("Input is only accepted on a screen");let o=e.screens.find(u=>u.id===a.screenId),s=e.inputs.filter(u=>u.screenId===a.screenId),c={...r};for(let[u,l]of Object.entries(n)){let d=s.find(p=>p.key===u);if(!d||o?.type!=="owned")throw new Error("Unknown screen input");let m=kc(o.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"&&!U.email().safeParse(l).success)throw new Error("Invalid email");if(l&&g.keyboard==="url"&&!U.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(p=>p.id===l&&!p.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(p=>!m.children.some(h=>h.id===p&&!h.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}c[u]=l}if(i)for(let u of s){let l=c[u.key];if(u.required&&(l===void 0||l===""||Array.isArray(l)&&l.length===0))throw new Error(`Required input: ${u.key}`);l!==void 0&&!Object.hasOwn(n,u.key)&&zx(e,t,{[u.key]:l},{},!1);let d=o?.type==="owned"?kc(o.document.pages[0]?.root,u.componentId):null;if(d?.type==="stack"&&d.interaction?.type==="multiselect"&&Array.isArray(l)&&l.length<d.interaction.min)throw new Error("Not enough selected options")}return c}import{z as xe}from"zod";import{z as Yx}from"zod";var Nc=Yx.enum(["local","remote"]);var Jx=xe.strictObject({id:xe.uuid(),projectId:xe.uuid(),environmentId:xe.uuid(),name:xe.string().min(1).max(80),revision:xe.number().int().nonnegative(),evaluationMode:Nc,evaluationRevision:xe.number().int().nonnegative(),state:xe.enum(["active","paused","archived"]),publishedVersionId:xe.uuid().nullable(),updatedAt:xe.iso.datetime({offset:!0}),draft:Bt}),cU=xe.strictObject({rows:xe.array(Jx).max(200),nextCursor:xe.uuid().nullable()}),uU=xe.discriminatedUnion("action",[xe.strictObject({action:xe.literal("setEvaluationMode"),id:xe.uuid(),revision:xe.number().int().nonnegative(),evaluationMode:Nc}),xe.strictObject({action:xe.literal("create"),requestId:xe.uuid(),name:xe.string().trim().min(1).max(80),document:Bt}),xe.strictObject({action:xe.literal("save"),id:xe.uuid(),revision:xe.number().int().nonnegative(),name:xe.string().trim().min(1).max(80),document:Bt}),xe.strictObject({action:xe.literal("terminateRun"),id:xe.uuid(),revision:xe.number().int().nonnegative(),runId:xe.uuid()}),xe.strictObject({action:xe.enum(["publish","archive","pause","activate","stop"]),id:xe.uuid(),revision:xe.number().int().nonnegative()})]).superRefine((e,t)=>{(e.action==="create"||e.action==="save")&&ln(e.document)>tt.documentBytes&&t.addIssue({code:"custom",path:["document"],message:"Funnel document exceeds its byte budget"})});function lU(e){let t=e==="en",n=ff("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"},jf.parse({schemaVersion:3,references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",inputs:[],screens:[{id:"welcome",type:"owned",document:n}],graph:{version:4,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 re}from"zod";var Kr=re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Dc=re.enum(["running","waiting","completed","closed","ineligible","failed"]),Xx=re.discriminatedUnion("type",[re.strictObject({type:re.literal("wait"),receiptId:re.uuid(),kind:re.enum(["timer","event","operation"]),deadline:re.iso.datetime({offset:!0}).nullable(),eventName:Kr.optional()}),re.strictObject({type:re.literal("open_url"),receiptId:re.uuid(),url:Ac,openIn:Pc}),re.strictObject({type:re.literal("event"),receiptId:re.uuid(),event:Kr})]),ev=re.strictObject({type:re.literal("funnel"),id:re.uuid(),versionId:re.uuid()}),Df=re.strictObject({type:re.literal("render"),url:df}),Uf={id:Kr,presentation:On,outputs:re.array(Kr).max(250),inputs:bc,offeringKey:Sn.optional(),capabilities:Va,customerData:Xm,dataCursors:re.record(Kr,to.nullable())},tv=re.strictObject({...Uf,content:re.discriminatedUnion("type",[Df,re.strictObject({type:re.literal("document"),document:Tt})])}),Uc=re.strictObject({id:re.uuid(),source:ev,revision:re.number().int().nonnegative(),visit:re.number().int().nonnegative(),nodeId:Kr,nodeType:re.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","output"]),status:Dc,stopped:re.boolean(),canBack:re.boolean(),authenticated:re.boolean(),locale:re.string().min(1).max(35),answers:Qi,parameters:un,variables:re.record(re.string(),Ke),output:Ke.nullable(),screen:tv.nullable(),paywall:re.strictObject({receiptId:re.uuid(),resolution:Wa,quote:Ti.nullable(),operation:kr.nullable(),purchaseRequestId:re.uuid().nullable()}).nullable(),instruction:Xx.nullable(),pendingRequest:re.strictObject({requestId:re.uuid(),authenticationRequired:re.boolean()}).nullable(),runExpiresAt:re.iso.datetime({offset:!0}),credentialExpiresAt:re.iso.datetime({offset:!0}).nullable()}),nv=Uc.extend({screen:re.strictObject({...Uf,content:Df}).nullable()}),Ff=re.strictObject({scope:$e,run:nv,purchase:re.strictObject({receiptId:re.uuid(),quote:Ti.nullable(),operation:kr.nullable()}).optional(),runToken:re.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:re.uuid().optional()});import{z as kt}from"zod";import{z as co}from"zod";var OU=co.strictObject({operation:co.literal("renew_run"),runId:co.uuid(),customerId:co.uuid()}),Mf=Ff.refine(e=>!!e.runToken,"Renewal returns a credential");var UU=kt.discriminatedUnion("operation",[kt.strictObject({operation:kt.literal("campaign_decide"),...xc}).refine(_r,yr),kt.strictObject({operation:kt.literal("campaign_start"),funnelId:kt.uuid(),requestId:kt.uuid(),customer:Br,customerData:qr.optional(),locale:kt.string().min(1).max(35),parameters:un,cooldownSeconds:kt.number().int().min(1).max(2592e3)}).refine(_r,yr)]),FU=kt.union([kt.strictObject({scope:$e,suppressed:kt.literal(!0),reason:kt.enum(["frequency","in_progress"]),retryAt:kt.iso.datetime({offset:!0})}),Mf]);import{z as qe}from"zod";function Lf(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(p){for(let h of ia(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),a.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 x=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!x){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,x),a.push(()=>{for(let I of x.rules??[]){d(I);for(let v of I.tracks??[])d(v.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),a.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(x=>u(x.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 a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var zi=qe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),qf=qe.strictObject({entry:zi,nodes:qe.array(qe.strictObject({id:zi,type:qe.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","output"]),outputs:qe.record(qe.string(),zi),resources:qe.strictObject({screenId:zi.optional(),paywallVersionId:qe.uuid().optional(),couponId:qe.uuid().optional(),experimentId:qe.uuid().optional(),featureKey:qe.string().optional(),offeringVersionId:qe.uuid().optional()})})).min(1).max(500)}),Bf={scope:$e,funnelId:qe.uuid(),versionId:qe.uuid(),evaluationRevision:qe.number().int().nonnegative(),expiresAt:qe.iso.datetime({offset:!0}).nullable(),topology:qf},rv=qe.discriminatedUnion("evaluationMode",[qe.strictObject({...Bf,evaluationMode:qe.literal("local"),growth:fn,conditions:qe.record(zi,qe.array(qe.strictObject({condition:Nn,port:qe.string()})))}),qe.strictObject({...Bf,evaluationMode:qe.literal("remote")})]);function iv(e){return qf.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":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let i=e.screens.find(a=>a.id===t.screenId);i?.type==="paywall"&&(r.paywallVersionId=i.paywallVersionId)}break;case"condition":t.cases.forEach((i,a)=>{n[`case:${a}`]=i.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 i of["success","cancel","unavailable","failure"])n[i]=t[i];t.action.type==="claim_offer"&&(r.couponId=t.action.couponId);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}return t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r}})})}function WU(e){let t=Nf.parse(e.document),n=e.evaluationMode==="local"?fn.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:iv(t)};return rv.parse(e.evaluationMode==="remote"?r:{...r,growth:Lf(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}import{z as M}from"zod";var $f={commands:tt.flowNodes*4,receipts:tt.flowNodes*2,requestBytes:tt.documentBytes+2e6},Wr=M.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Vf={requestId:M.uuid(),nodeId:Wr,visit:M.number().int().nonnegative(),revision:M.number().int().nonnegative()},av=M.union([Zi.options[3].omit({customerToken:!0}),Zi.options[4].omit({customerToken:!0}),Zi.options[5].omit({customerToken:!0}),Zi.options[6].omit({customerToken:!0}),M.strictObject({operation:M.literal("wait"),...Vf,result:M.enum(["elapsed","received","timeout"])}),M.strictObject({operation:M.literal("simulate"),...Vf,outcome:M.enum(["success","cancel","failure","unavailable"])})]),Fc=M.enum(["success","cancel","failure","unavailable","pending"]),Mc=M.strictObject({seed:M.uuid(),now:M.iso.datetime({offset:!0}),locale:M.string().min(2).max(35),currency:Q,parameters:un,attributes:M.record(M.string(),Ki).refine(e=>Object.keys(e).length<=100),authenticated:M.boolean(),holdings:M.enum(["sample","empty"]),results:M.record(M.string(),Ke).optional(),outcomes:M.record(Wr,Fc),variants:M.record(Wr,M.string().min(1).max(128).nullable())}),Lc=M.strictObject({schemaVersion:M.literal(1),growth:fn,paywalls:M.record(M.uuid(),Ka),offerings:M.record(M.uuid(),Nr),surfaces:M.record(Wr,Ke)}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=1e6,"Preview dependencies exceed their byte budget"),ov=M.array(M.strictObject({command:av,authenticated:M.boolean(),outcome:Fc})).max($f.commands),sv=M.discriminatedUnion("type",[M.strictObject({type:M.literal("draft"),document:Bt}),M.strictObject({type:M.literal("snapshot"),id:M.uuid()})]),oF=M.strictObject({previewId:M.uuid(),source:sv,scenario:Mc,journal:ov,dependencySnapshot:Lc.optional()}),sF=M.strictObject({mode:M.literal("simulation"),run:Uc,dependencySnapshot:Lc,traceTruncated:M.boolean(),trace:M.array(M.strictObject({nodeId:Wr,visit:M.number().int().nonnegative(),type:M.enum(["entered","shown","assigned","feature_evaluated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:M.record(M.string(),M.union([M.string(),M.number(),M.boolean(),M.null()]))})).max(2e3),receipts:M.array(M.strictObject({id:M.uuid(),nodeId:Wr,visit:M.number().int().nonnegative(),outcome:Fc})).max($f.receipts)}),cF=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),document:Bt,scenario:Mc,dependencySnapshot:Lc,expiresAt:M.iso.datetime({offset:!0})}),uF=M.discriminatedUnion("action",[M.strictObject({action:M.literal("create"),requestId:M.uuid(),document:Bt,scenario:Mc}),M.strictObject({action:M.literal("revoke"),id:M.uuid()})]);import{z as Ie}from"zod";var mF=Ie.object({overall:Ie.object({entered:Ie.number(),running:Ie.number(),closed:Ie.number(),completed:Ie.number(),authenticated:Ie.number(),authReached:Ie.number(),paid:Ie.number(),free:Ie.number()}),steps:Ie.array(Ie.object({node_id:Ie.string(),visitors:Ie.number()})),edges:Ie.array(Ie.object({node_id:Ie.string(),target:Ie.string(),visitors:Ie.number()})),currencies:Ie.array(Ie.object({currency:Ie.string(),grossCents:Ie.number(),refundCents:Ie.number()})),variants:Ie.array(Ie.object({experimentId:Ie.uuid(),revision:Ie.number(),variantId:Ie.string(),exposed:Ie.number(),completed:Ie.number(),paid:Ie.number(),exposedRuns:Ie.number().optional(),completedRuns:Ie.number().optional(),paidRuns:Ie.number().optional()}))});var Bc={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 hF(e,t,n=[]){let r=rr(t)??"en",[i="en",...a]=r.split("-"),o=i==="zh"&&!a.includes("Hans")&&a.some(p=>["Hant","TW","HK","MO"].includes(p))?"zh-Hant":i,s=Bc[o]??Bc.en,c=Bc[o]?r:"en",u=p=>new Intl.NumberFormat(c).format(p),l=p=>new Intl.DateTimeFormat(c,{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(new Date(p))+" UTC",d=[e.appliesTo.type==="all"?s[0]:`${s[1]}${n.length?`: ${n.slice(0,3).join(", ")+(n.length>3?` (+${u(n.length-3)})`:"")}`:""}`,e.eligibility.firstPurchaseOnly?s[3]:s[2],Object.keys(e.eligibility.condition).length?`${s[4]}${Gf(e.eligibility.condition)?`: ${Gf(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),m=[e.startsAt?`${s[5]}: ${l(e.startsAt)}`:null,e.endsAt?`${s[6]}: ${l(e.endsAt)}`:s[7]].filter(Boolean).join(" \xB7 "),g=[d,m,`${s[8]}: ${u(e.grantWindowHours)} ${s[9]}`,`${s[10]}: ${u(e.perCustomerLimit)}`,e.totalLimit===null?null:`${s[11]}: ${u(e.totalLimit)}`].filter(Boolean).join(" \xB7 ");return{eligibility:d,validity:m,terms:g}}function Gf(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 qc={"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 Hf(e){return e.actions.map(t=>t.properties.templateKey).find(t=>typeof t=="string"&&t.startsWith("popup-coupon-"))}function yF(e,t){let n=Hf(e);if(!n||!Object.hasOwn(qc,n))return e;let r=i=>{let a={...i.root.bind,coupon:t};return i.root.bind?.coupon!==t&&delete a.promotionCode,{bind:a}};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 SF(e){let t=Hf(e),n=t?qc[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(([a,o])=>[a,o.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 as te}from"zod";var zt=te.string().min(1).max(255),Hn=te.number().finite().nonnegative(),Kf=te.strictObject({properties:te.record(te.string().min(1).max(64),te.union([te.string().min(1).max(128),te.number().finite(),te.boolean()]).transform(String).pipe(te.string())).refine(e=>Object.keys(e).length>=1&&Object.keys(e).length<=4)}),cv=te.strictObject({feature_id:zt,enabled:te.boolean().default(!1),threshold:te.number().finite(),quantity:te.number().finite().min(1),purchase_limit:te.strictObject({interval:te.enum(["hour","day","week","month"]),interval_count:te.number().finite().min(1).default(1),limit:te.number().finite().min(1)}).optional(),invoice_mode:te.boolean().optional()}),uv=te.strictObject({feature_id:zt.optional(),enabled:te.boolean().default(!1),limit_type:te.enum(["absolute","usage_percentage"]).optional(),overage_limit:Hn.optional(),skip_overage_billing:te.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"),lv=te.strictObject({feature_id:zt,enabled:te.boolean().default(!0),limit:Hn,interval:te.enum(["day","week","month","year"]),anchor:te.enum(["billing_cycle","utc"]).optional(),filter:Kf.optional()}),dv=te.strictObject({feature_id:zt.optional(),enabled:te.boolean().default(!0),threshold:Hn,threshold_type:te.enum(["usage","usage_percentage","remaining","remaining_percentage"]),basis:te.enum(["balance","included","recurring","usage_limit"]).default("balance"),filter:Kf.optional(),name:te.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"),mv=te.strictObject({feature_id:zt,enabled:te.boolean().default(!1)}),pv=te.strictObject({auto_topups:te.array(cv).nullable(),spend_limits:te.array(uv).nullable(),usage_limits:te.array(lv).nullable(),usage_alerts:te.array(dv).nullable(),overage_allowed:te.array(mv).nullable()}),AF=pv.omit({auto_topups:!0}),fv=Lr,PF=te.strictObject({internal_id:te.uuid(),id:zt.nullable(),project_id:te.uuid(),environment_id:te.uuid(),name:te.string().max(80).nullable(),email:te.string().max(254).nullable(),metadata:fv.nullable(),created_at:te.number().finite().nonnegative().max(864e13)}),CF=te.strictObject({id:zt,internal_product_id:zt,product_id:zt.nullable(),status:te.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:Hn.nullable(),free_trial_id:zt.nullable(),trial_ends_at:Hn.nullable(),starts_at:Hn.nullable(),access_starts_at:Hn.nullable(),ended_at:Hn.nullable(),product:te.strictObject({internal_id:zt,id:zt,name:te.string(),version:te.number().int().positive(),is_add_on:te.boolean()})});function TF(e,t,n=[]){let r={nodes:{}},i=t.startsWith("zh"),a=(s,c)=>i?s:c,o=(s,c,u,l,d=[])=>({id:s,label:c,value:u,status:l,detail:d,facts:[]});return wt(e,s=>{if(s.type!=="customer_data")return;let c={...ep(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??a("\u521B\u4F5C\u79EF\u5206","Creative credits"),spendable:"3,840",available:"4,040",reserved:"200",expiry:a("1,200 \xB7 2026\u5E7411\u67081\u65E5","1,200 \xB7 November 1, 2026"),sources:[o("sample-monthly",a("\u4F1A\u5458\u6708\u5EA6\u79EF\u5206","Monthly membership credits"),"2,640",a("\u53EF\u7528","Available")),o("sample-pack",a("\u8D2D\u4E70\u79EF\u5206\u5305","Purchased credit pack"),"1,200",a("\u53EF\u7528","Available"))],sourceCount:2,sourcePage:1,hasNextSources:!1,hasPreviousSources:!1}]}else s.data.source==="credit_transactions"?(c.rows=[o("sample-usage-1",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67083\u65E5 09:42","Oct 3, 09:42")]),o("sample-usage-2",a("\u89C6\u9891\u751F\u6210","Video generation"),"",a("\u9884\u6263","Reserved"),[a("10\u67083\u65E5 09:30","Oct 3, 09:30")]),o("sample-usage-3",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u9000\u56DE","Refund"),[a("10\u67082\u65E5 16:10","Oct 2, 16:10")]),o("sample-usage-4",a("\u89C6\u9891\u751F\u6210","Video generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67082\u65E5 15:24","Oct 2, 15:24")]),o("sample-usage-5",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67082\u65E5 14:08","Oct 2, 14:08")])].slice(0,s.data.pageSize),c.rows.forEach((u,l)=>{u.facts=[{label:a("\u521B\u4F5C\u79EF\u5206","Creative credits"),value:l%2===1?"180":l===4?"24":"12"}]})):s.data.source==="membership"?c.rows=[o("sample-plan",a("\u4E13\u4E1A\u7248 \xB7 \u6708\u4ED8","Pro \xB7 Monthly"),"",a("\u6709\u6548","Active"),[a("\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=[o("sample-free",a("\u57FA\u7840\u7248","Starter"),a("\u514D\u8D39","Free"),a("\u53EF\u9009\u62E9","Available")),o("sample-pro",a("\u4E13\u4E1A\u7248","Pro"),a("$29 / \u6708","$29 / month"),a("\u5F53\u524D\u5957\u9910","Current plan")),o("sample-team",a("\u56E2\u961F\u7248","Team"),a("$79 / \u6708","$79 / month"),a("\u53EF\u9009\u62E9","Available"))].slice(0,s.data.pageSize):s.data.source==="billing_controls"?c.rows=[o("sample-control",a("\u6708\u5EA6\u7528\u91CF\u4E0A\u9650","Monthly usage limit"),"240 / 1,000",a("\u793A\u4F8B \xB7 \u672A\u6388\u6743\u4ED8\u6B3E","Sample \xB7 Payments not authorized"),[a("\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=[{...o("sample-invoice","GROW-2026-001","$29.00",a("\u5DF2\u652F\u4ED8","Paid"),["October 1, 2026"]),billingActions:[{action:"invoice_open",label:a("\u67E5\u770B\u53D1\u7968","View invoice")}]}]:s.data.source==="credit_packs"?c.rows=[o("sample-pack-small",a("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12","",[a("1,200 \u79EF\u5206 \xB7 90 \u5929\u6709\u6548","1,200 credits \xB7 90 days validity")]),o("sample-pack-large",a("\u521B\u4F5C\u6269\u5C55\u5305","Creative expansion"),"$40","",[a("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=[o("sample-order",a("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12",a("\u5DF2\u4ED8\u6B3E","Paid"),["2026-10-01 12:30"])]:c.rows=[o("sample-offer",a("\u4F1A\u5458\u7EED\u8D39\u4F18\u60E0","Membership renewal offer"),"",a("\u53EF\u7528","Available"),[a("2026\u5E7411\u67081\u65E5\u5230\u671F","Expires November 1, 2026")])];r.nodes[s.id]=c}),r}import{z as Te}from"zod";import{z as pe}from"zod";var hv=pe.enum(["customer","coupon","audience"]),gv=pe.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),uo=pe.object({baseRevision:pe.number().int().nonnegative(),latestRevision:pe.number().int().nonnegative(),mode:pe.enum(["merge","use_latest"]),decisions:pe.array(pe.object({field:gv,mine:pe.number().int().min(0).max(1e3),latest:pe.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),Wf=pe.number().int().nonnegative().nullable(),bv=pe.object({resource:hv,id:pe.uuid(),projectId:pe.uuid(),environmentId:pe.uuid(),fromRevision:Wf,toRevision:Wf,provenance:pe.enum(["recorded","historical"]),changes:pe.array(pe.object({field:pe.string(),redacted:pe.boolean(),before:pe.union([pe.string(),pe.number(),pe.boolean(),pe.null()]),after:pe.union([pe.string(),pe.number(),pe.boolean(),pe.null()])})),merge:uo.safeExtend({source:pe.literal("client")}).nullable()}),_v=pe.object({createdAt:pe.iso.datetime({offset:!0}),id:pe.uuid()}).strict(),jF=pe.object({events:pe.array(pe.object({id:pe.uuid(),action:pe.string(),actorId:pe.uuid().nullable(),actorEmail:pe.email().nullable(),createdAt:pe.iso.datetime({offset:!0}),object:bv})),nextCursor:_v.nullable()});var MF={type:"condition",condition:{}},LF=Te.strictObject({id:Te.uuid(),name:Te.string().min(1).max(80),description:Te.string().max(500),config:Fo,revision:Te.number().int().min(1),status:Te.enum(["active","archived"]),batchable:Te.boolean(),created_at:Te.iso.datetime({offset:!0}),updated_at:Te.iso.datetime({offset:!0})}),BF=Te.discriminatedUnion("action",[Te.strictObject({action:Te.literal("save"),id:Te.uuid().nullable(),audit:uo.nullable().optional(),revision:Te.number().int().min(0),name:Te.string().trim().min(1).max(80),description:Te.string().max(500),config:Fo}),Te.strictObject({action:Te.literal("archive"),id:Te.uuid(),audit:uo.nullable().optional(),revision:Te.number().int().min(1)})]),yv=Te.object({id:Te.uuid(),name:Te.string().nullable(),external_user_id:Te.string(),attributes:pn,created_at:Te.iso.datetime({offset:!0})}),qF=Te.object({customers:yv.array(),hasMore:Te.boolean(),offset:Te.number().int().min(0),limit:Te.number().int().min(1),evaluatedAt:Te.iso.datetime({offset:!0}),revision:Te.number().int().min(1)});import{z as Yi}from"zod";var HF=Yi.object({defaultLocale:tn,locales:Yi.record(tn,Yi.object({name:Yi.string().max(80),description:Yi.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 KF(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=xa([t],r,n.defaultLocale),a=n.locales[i],o=n.locales[n.defaultLocale];return{name:a?.name.trim()?a.name:o?.name.trim()?o.name:e.name,description:a?.description.trim()?a.description:o?.description.trim()?o.description:""}}var Qf="#172033",lo="#667085",Sv="#E2E6EE",xv="#2C3C96",Ot=e=>({top:e,right:e,bottom:e,left:e}),bt=e=>({type:"color",color:e}),qt=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,a=lo,o={}){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:a,weight:i>=30?600:400,lineHeight:1.35,...i>=30?{letterSpacing:-1.2}:{}},...o}}}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,a=!1,o={}){let s=t+"_title";return this.zh[s]=r,this.en[s]=i,{id:t,type:"customer_data",title:s,data:{source:n,layout:a?"compact":"full",pageSize:n==="credit_transactions"?5:4,showSources:n==="credit_balance"&&!a,allowPurchase:n==="credit_packs"},style:o}}rule(t,n=Sv){return{id:t,type:"divider",style:{background:bt(n),height:1}}}header(t,n,r,i,a,o=!1){return this.stack("account_header",[this.stack("intro",[this.text("eyebrow","\u5DE5\u4F5C\u7A7A\u95F4 / \u8D26\u6237","WORKSPACE / ACCOUNT",11,o?"#A9B4CB":lo,{text:{size:11,color:o?"#A9B4CB":lo,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,o?"#FFFFFF":Qf),this.text("description",r,i,14,o?"#A9B4CB":lo)],{gap:12,width:660,grow:!0}),...a?[a]:[]],{gap:32},!0)}document(t,n=!1){return Tt.parse({kind:"screen",schemaVersion:4,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:xv,background:n?"#101A30":"#F5F6FA",text:Qf,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 po="#19202E",vv="#667080",Vc="#2C3C96",Zf="#DDE2E9",zf="#F0F3FA",Iv=(e=72,t=po)=>({text:{size:e,color:t,weight:600,font:"system"}}),mo=(e,t=1)=>({width:e,grow:t}),Av={background:bt("#FFFFFF"),shape:{type:"rect",radius:10}};function Pv(e){return new qt(e,{theme:{background:"#FFFFFF",text:po,primary:Vc},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function Cv(e,t,n,r,i){let a=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,Vc,{text:{size:13,color:Vc,weight:700,letterSpacing:.8}});return e.stack("page_header",[a,e.text("heading",t,n,40,po,{text:{size:40,color:po,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,vv)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function Yf(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new qt("\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}}),a=(o,s,c)=>i.text(o,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}}),a("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",[a("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",[a("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",[a("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",[a("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",[a("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",[a("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 Jf(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new qt("\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=(a,o,s)=>r.text(a,o,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:Ot(28),background:bt("#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:Ot(28),background:bt("#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:Ot(24),background:bt("#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:Ot(24),background:bt("#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:Ot(24),background:bt("#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 Xf(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new qt("\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}}),a=(o,s,c,u=n)=>i.text(o,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}}),a("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",[a("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",[a("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:Ot(32),background:bt(e)}),i.stack("balance_inset",[a("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:Ot(28),background:bt(r)})],{gap:0},!0),i.stack("plan_comparison",[a("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",[a("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",[a("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"),a("club_footer","GROW CLUB / \u7559\u51FA\u521B\u9020\u7684\u7A7A\u95F4","GROW CLUB / ROOM FOR WHAT'S NEXT")])}function eh(){let e=Pv("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([Cv(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,{...mo(784,2),...Iv(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{...mo(328),background:bt(zf),padding:Ot(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",Zf),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,mo(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",Zf),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{...mo(328),...Av,padding:Ot(24),gap:24,background:bt(zf)})],{gap:48},!0)])}function th(){return eh()}var xn=(e,t=1)=>({width:e,grow:t}),fo=(e=16)=>({shape:{type:"rect",radius:e}}),st=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),En=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function wv(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 Ov(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 Ji(e,t,n,r,i,a="system"){let o=e.stack("masthead",[wv(e,t,n,r,a),Ov(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return o.justify="between",o.align="center",o}function nh(e,t,n=!1,r=5){let i=e.widget("activity","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",n,st(t));return i.data.pageSize=r,i}function Ev(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new qt("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:En(32,24,48)});return i.document([Ji(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,st(t,96)),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,st(t))],{...xn(680,2),gap:32,padding:En(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,st(e))],{...xn(328),background:bt(r),padding:Ot(24),...fo(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),nh(i,t,!1,4)])}function Tv(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new qt("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:En(40,24,48)});return r.document([Ji(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,st(e,96,"serif"))],{...xn(628,2),padding:En(12,0),gap:24}),r.stack("membership_column",[r.widget("membership","membership","\u4F1A\u5458\u72B6\u6001","Membership",!1,st(e)),r.widget("offers","offer_history","\u8D26\u6237\u4F18\u60E0","Your offers",!0,st(e))],{...xn(356),gap:20,padding:En(12,0)})],{gap:96},!0),r.rule("orders_rule",n),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Purchases",!1,st(e))])}function Rv(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new qt("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:En(32,24,48)});return i.document([Ji(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,st("#F4F7F0"))],{...xn(640,2),gap:24,background:bt(n),padding:Ot(32),...fo(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,st(e,64))],{...xn(400),background:bt("#E9EFE5"),padding:Ot(28),...fo(20)})],{gap:24},!0),i.widget("plans","customer_plans","\u65B9\u6848\u4E0E\u4EF7\u683C","Plans & pricing",!1,st(e)),i.rule("offer_rule","#D5DFD3"),i.widget("offers","offer_history","\u6211\u7684\u4F18\u60E0","Your offers",!0,st(e))])}function kv(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new qt("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:En(32,24,48)});return r.document([Ji(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,{...xn(688,2),...st(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...xn(372),...st(e)})],{gap:72,padding:En(4,0,8)},!0),r.rule("activity_rule",n),nh(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,st(e))])}function jv(){let e="#3F3029",t="#8B766A",n="#A34525",r=new qt("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:En(32,24,48)});return r.document([Ji(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,st(e,56)),r.rule("context_rule","#DBC5B5"),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,st(e))],{...xn(304),gap:28,padding:Ot(24),background:bt("#F1E5D9"),...fo(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,st(e))],{...xn(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,st(e))])}function rh(){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:Ev},{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:Tv},{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:Rv},{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:th},{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:kv},{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:jv}].map(({create:e,...t})=>({...t,document:e()}))}function Nv(){return Jf()}function Dv(){return Yf()}function Uv(){return Xf()}function aM(){return[...rh(),{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:Nv()},{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:Dv()},{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:Uv()}]}import{z as jt}from"zod";var ih=jt.object({id:jt.string().min(1).max(136),name:jt.string().min(1).max(128),type:jt.enum(["entry","condition","feature"])}).strict(),Fv=jt.object({id:jt.uuid(),name:jt.string().min(1).max(80),status:jt.enum(["draft","published","archived"]),draftNodes:jt.array(ih).max(600),publishedNodes:jt.array(ih).max(600),runningVersions:jt.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"),cM=jt.object({rows:jt.array(Fv).max(50),nextCursor:jt.uuid().nullable()}).strict();import{z as ve}from"zod";var At=ve.number().int().nonnegative(),ah=ve.strictObject({at:ve.iso.datetime({offset:!0}),id:ve.uuid()}),pM=ve.strictObject({versionId:ve.uuid().nullable(),from:ve.iso.datetime({offset:!0}).nullable(),to:ve.iso.datetime({offset:!0}).nullable(),after:ah.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),fM=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:At,completed:At,closed:At,failed:At,waiting:At,paid:At}),decisions:ve.strictObject({queries:At,completed:At,reportedUsed:At,pending:At,failed:At}),revenue:ve.array(ve.strictObject({currency:Q,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:At,completed:At,shown:At,waiting:At})).max(1e4),recentRuns:ve.array(ve.strictObject({id:ve.uuid(),versionId:ve.uuid(),customerId:ve.uuid(),status:Dc,nodeId:ve.string(),visit:At,createdAt:ve.iso.datetime({offset:!0}),updatedAt:ve.iso.datetime({offset:!0})})).max(100),nextCursor:ah.nullable()});import{z as Kn}from"zod";var yM=Kn.object({requestId:Kn.uuid(),coupon:Wl,audienceId:Kn.uuid().nullable(),productVersionId:Kn.uuid().optional(),presentation:On,locale:Kn.enum(["en","zh-CN"])}).strict(),SM=Kn.object({couponId:Kn.uuid(),funnelId:Kn.uuid()}).strict();import{z as Pe}from"zod";var _t=Pe.number().int().nonnegative(),ho=Pe.string().regex(/^-?\d+$/),Mv=Pe.object({currency:Q,grossMinor:ho,refundMinor:ho,netMinor:ho,purchases:_t,refunds:_t}).strict(),AM=Pe.object({snapshotAt:Pe.iso.datetime({offset:!0}),customers:Pe.object({total:_t,created:_t,paid:_t}).strict(),memberships:Pe.object({active:_t,trial:_t,pastDue:_t,ended:_t}).strict(),runs:Pe.object({started:_t,completed:_t,closed:_t,paid:_t}).strict(),revenue:Pe.array(Mv).max(100),unknownMoney:_t,funnels:Pe.array(Pe.object({id:Pe.uuid(),name:Pe.string(),started:_t,completed:_t,paid:_t}).strict()).max(50),daily:Pe.array(Pe.object({date:Pe.iso.date(),currency:Q,netMinor:ho}).strict()).max(9e3)}).strict(),PM=Pe.object({customerId:Pe.uuid(),rows:Pe.array(Pe.object({id:Pe.string().regex(/^\d+$/),funnelId:Pe.uuid(),funnelName:Pe.string(),versionId:Pe.uuid(),runId:Pe.uuid(),nodeId:Pe.string(),experimentId:Pe.uuid(),visit:Pe.number().int().nonnegative(),variationKey:Pe.string(),inExperiment:Pe.boolean(),hashUsed:Pe.boolean(),acceptedAt:Pe.iso.datetime({offset:!0}),runStatus:Pe.string()}).strict()).max(50),nextCursor:Pe.string().regex(/^\d+$/).nullable()}).strict();import{z as Yt}from"zod";import{z as yt}from"zod";var oh=yt.discriminatedUnion("provider",[yt.strictObject({provider:yt.literal("apple"),orderId:yt.uuid(),receiptId:yt.uuid(),signedTransaction:yt.string().min(1).max(131072)}),yt.strictObject({provider:yt.literal("google"),orderId:yt.uuid(),receiptId:yt.uuid(),purchaseToken:yt.string().min(1).max(16384)})]),sh=yt.strictObject({orderId:yt.uuid(),receiptId:yt.uuid(),transactionIds:yt.array(yt.string().min(1).max(255)).min(1).max(50),membership:yt.boolean()});var kM=Yt.strictObject({operation:Yt.literal("native_receipt"),requestId:Yt.uuid(),customerToken:Yt.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:Yt.uuid(),receiptId:Yt.uuid(),nativeEvidence:oh.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),jM=Yt.strictObject({scope:$e,requestId:Yt.uuid(),orderId:Yt.uuid(),receiptId:Yt.uuid(),orderStatus:Yt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:Yt.boolean(),nativeCompletion:sh.optional()});import{z as Lv}from"zod";var Bv=yf.extend({document:Lv.union([Tt.refine(e=>e.pages.length===1,"Use a single owned screen template"),Bt.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(a=>a.screenId===i.id).length!==1))&&t.addIssue({code:"custom",message:"Every template screen requires one unique flow node"})}});function VM(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}}function qv(e,t){let n=structuredClone(Bv.parse(e).document);if(n.kind==="funnel"){let u=function(l){if(Array.isArray(l)){l.forEach(u);return}if(!l||typeof l!="object")return;let d=l;d.type==="experiment-ref"&&(d.experimentId=c),d.$savedGroup&&typeof d.$savedGroup=="object"&&(d.$savedGroup.id=c),typeof d.$inGroup=="string"&&(d.$inGroup=c),typeof d.$notInGroup=="string"&&(d.$notInGroup=c),Object.values(d).forEach(u)};var s=u;let c="00000000-0000-0000-0000-000000000000";for(let l of Object.values(n.references))"id"in l&&(l.id=c);for(let l of n.graph.nodes)l.type==="condition"&&l.cases.forEach(d=>u(d.condition));for(let l of n.screens)l.type==="owned"&&ch(l.document);return Bt.parse({...n,screens:n.screens.map(l=>l.type==="owned"?{...l,document:{...l.document,strings:{...l.document.strings,defaultLocale:Ys(l.document,[t])}}}:l),graph:{...n.graph,nodes:n.graph.nodes.map(l=>l.type==="split"?{...l,experimentId:"00000000-0000-0000-0000-000000000000"}:l.type==="offering"?{...l,configuration:l.configuration.source==="fixed"?{source:"fixed",versionId:c}:l.configuration}:l.type==="coupon"?{...l,couponId:c}:l)}})}let r={...n,strings:{...n.strings,defaultLocale:Ys(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"}],a={};r.actions=r.actions.map((c,u)=>{let l=`action_${u}`;return a[c.id]=c.close?"closed":"done",c.type==="open_url"?(a[c.id]=l,i.push({id:l,name:c.id,type:"output",value:{type:"literal",value:{intent:"open_url",url:c.url}}})):c.type==="claim_offer"&&(a[c.id]="unconnected"),{id:c.id,type:"event",event:c.id,properties:{},close:!1}}),ch(r),i.push({id:"screen",name:e.label,type:"screen",screenId:"screen",presentation:e.surface==="page"?{type:"inline"}:n.presentation,outputs:a});let o=new Set(i.flatMap(Gr));return Bt.parse({references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",schemaVersion:3,inputs:(()=>{let c=[];return wt(r,u=>{u.type==="stack"&&u.interaction&&["input","select","multiselect","toggle","tabs"].includes(u.interaction.type)&&c.push({key:`answer_${crypto.randomUUID().replaceAll("-","")}`,screenId:"screen",componentId:u.id,required:!1})}),c})(),screens:[{id:"screen",type:"owned",document:r}],graph:{version:4,entry:"entry",nodes:i.filter(c=>c.type!=="end"||o.has(c.id))}})}function $M(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=qv(t,n),i=`tpl_${crypto.randomUUID().replaceAll("-","").slice(0,16)}_`,a=new Map,o=d=>d==="unconnected"?d:(a.has(d)||a.set(d,`${i}${crypto.randomUUID().replaceAll("-","").slice(0,24)}`),a.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:o(d.id),screenId:o(d.screenId),outputs:Object.fromEntries(Object.entries(d.outputs).map(([m,g])=>[m,o(g)]))}:d.type==="action"?{...d,id:o(d.id),success:o(d.success),cancel:o(d.cancel),unavailable:o(d.unavailable),failure:o(d.failure)}:d.type==="external_page"?{...d,id:o(d.id),opened:o(d.opened),failed:o(d.failed)}:{...d,id:o(d.id)}),c=Bt.parse({...e,screens:[...e.screens,...r.screens.map(d=>({...d,id:o(d.id)}))],inputs:[...e.inputs,...r.inputs.map(d=>({...d,screenId:o(d.screenId)}))],graph:{...e.graph,nodes:[...e.graph.nodes,...s]}}),u=0,l=0;for(let d of c.screens)d.type==="owned"&&(wt(d.document,()=>{u++}),l+=d.document.actions.length);if(u>tt.components||l>tt.actions||ln(c)>tt.documentBytes)throw new Error("Template exceeds the flow capacity");return c}function ch(e){wt(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 Vv(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function HM(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function uh(e){return Vv(e)?e.intervalCount??1:1}function KM(e,t){return e.interval===t.interval&&uh(e)===uh(t)}function WM(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},a={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},o=e==="week"?`/${a[r]??a.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?o:`/${n} ${o.slice(1)}${r==="en"?"s":""}`}import{z as Ve}from"zod";var lh=Ve.enum(["membership","trial","topup","manual","rollover","seat"]),dh=Ve.enum(["scheduled","active","expired","revoked","unavailable"]),JM=Ve.strictObject({customerId:Ve.uuid().nullable(),entityId:Ve.uuid().nullable(),internal_feature_id:Ve.uuid().nullable(),reason:lh.nullable(),status:dh.nullable(),after:Ve.uuid().nullable(),limit:Ve.number().int().min(1).max(50)}),XM=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:en,name:Ve.string().min(1).max(120),kind:Ve.enum(["access","metered","credit"]),reason:lh,status:dh,unlimited:Ve.boolean(),granted:Ye,available:Ye,held:Ye,spent:Ye,revoked:Ye,transferred:Ye,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 mh=Me.string().regex(/^[a-f0-9]{64}$/),$v=xu.omit({variations:!0,active:!0}).extend({changeId:mh,variations:Me.array(Me.strictObject({urlRedirect:Me.string().max(2048)})).min(2).max(20)}),a4=Me.strictObject({environmentId:Me.uuid(),trackExposures:Me.boolean(),generation:mh,experiments:Me.array($v).max(100),savedGroups:Iu}),Gv=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)}),o4=Me.strictObject({events:Me.array(Gv).min(1).max(20)}),s4=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 fh=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"})}),hh=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)}),$c={id:q.uuid(),revision:q.number().int().positive()},m4=q.strictObject({groups:q.array(q.strictObject({id:q.uuid(),name:q.string(),type:q.enum(["condition","list"])})),experiments:q.array(q.strictObject({...$c,configuration:si,archivedAt:q.iso.datetime({offset:!0}).nullable()})),namespaces:q.array(q.strictObject({...$c,configuration:hh})),attributes:q.array(q.strictObject({...$c,configuration:fh})),truncated:q.boolean()}),Gc={id:q.uuid().nullable(),revision:q.number().int().min(0)},p4=q.discriminatedUnion("resource",[q.strictObject({...Gc,resource:q.literal("experiment"),configuration:si.safeExtend({archivedAt:q.iso.datetime({offset:!0}).nullable()})}),q.strictObject({...Gc,resource:q.literal("namespace"),configuration:hh}),q.strictObject({...Gc,resource:q.literal("attribute"),configuration:fh})]),f4=q.strictObject({operation:q.literal("evaluate"),attributes:pn,condition:Nn.optional(),features:Su,featureKey:q.string().min(1).max(128),customerId:q.uuid().nullable()}),h4=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()}),ph=q.strictObject({resource:q.enum(["group","experiment","coupon"]),id:q.uuid()}),g4=q.strictObject({rows:q.array(ph.extend({name:q.string(),status:q.string()})).max(50),total:q.number().int().nonnegative(),nextCursor:ph.nullable()});var go=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Hv(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!go(n.condition,r.condition)||!go(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"),(!go(n.variationWeights,r.variationWeights)||!go(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 a=i.some(c=>["namespace","namespaceRange","weights","identity"].includes(c)),o=!t.disableStickyBucketing,s=a||i.length>0&&!o?"new-phase":o?"same-phase-sticky":"same-phase-everyone";return{reasons:i,disableSamePhase:a,recommended:s,risk:i.length?a?"danger":"warning":"safe"}}function y4(e,t,n,r,i){let a=structuredClone(t),o=a.phases.at(-1),s=!a.disableStickyBucketing;if(n==="same-phase-sticky"&&!s||n==="new-phase-block-sticky"&&!s)throw Error("Sticky bucketing is required");if(Hv(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");if(a.bucketVersion=e.bucketVersion+(s&&n!=="same-phase-sticky"?1:0),a.minBucketVersion=n==="new-phase-block-sticky"?a.bucketVersion:e.minBucketVersion,n.startsWith("new-phase")){a.phases=structuredClone(e.phases);let c=a.phases.at(-1);if(!c)throw new Error("Experiment requires a phase");c.dateEnded=r,a.phases.push({...o,name:o.name,reason:o.reason,dateStarted:r,dateEnded:null,seed:i})}return si.parse(a)}import{z as Kv}from"zod";var v4=Kv.enum(["owner","admin","developer","sales","member"]),Wv=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],gh=Wv.flatMap(e=>e==="analytics"?["analytics:read"]:[`${e}:read`,`${e}:write`]),bh={owner:gh,admin:gh,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 I4(e,t){if(!e||!Object.hasOwn(bh,e))return!1;let n=bh[e];return n.includes(t)||t.endsWith(":read")&&n.includes(t.replace(/:read$/,":write"))}var P4=["boolean","metered","credit_system","ai_credit_system"];function C4(e,t,n,r=!1){let i=[],a=(o,s)=>i.push({field:o,code:s});return e.type!==t.type&&(e.type==="credit_system"!=(t.type==="credit_system")&&a("type","type_switch_credit_system"),n.customerHistory&&a("type","attached_to_customer"),n.entityFeature&&a("type","used_as_entity_feature"),n.usagePrice&&a("type","has_usage_price"),n.creditSystems&&a("type","used_in_credit_system"),n.productEntitlements&&(e.type==="credit_system"||t.type==="credit_system")&&a("type","used_in_product_credit_system")),e.id!==t.id&&(r&&a("id","id_already_exists"),n.customerHistory&&a("id","attached_to_customer")),e.type!=="boolean"&&t.type!=="boolean"&&e.config?.usage_type!==t.config?.usage_type&&t.config?.usage_type&&(n.creditSystems&&a("usage_type","used_in_credit_system"),n.entityFeature&&a("usage_type","used_as_entity_feature"),n.customerHistory&&a("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 Qr=9e15,zn=1e9,Hc="0123456789abcdef",yo="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",So="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Kc={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Qr,maxE:Qr,crypto:!1},xh,Tn,le=!0,vo="[DecimalError] ",Zn=vo+"Invalid argument: ",vh=vo+"Precision limit exceeded",Ih=vo+"crypto unavailable",Ah="[object Decimal]",Pt=Math.floor,ct=Math.pow,Qv=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Zv=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,zv=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Ph=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,dn=1e7,ie=7,Yv=9007199254740991,Jv=yo.length-1,Wc=So.length-1,E={toStringTag:Ah};E.absoluteValue=E.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),X(e)};E.ceil=function(){return X(new this.constructor(this),this.e+1,2)};E.clampedTo=E.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(Zn+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};E.comparedTo=E.cmp=function(e){var t,n,r,i,a=this,o=a.d,s=(e=new a.constructor(e)).d,c=a.s,u=e.s;if(!o||!s)return!c||!u?NaN:c!==u?c:o===s?0:!o^c<0?1:-1;if(!o[0]||!s[0])return o[0]?c:s[0]?-u:0;if(c!==u)return c;if(a.e!==e.e)return a.e>e.e^c<0?1:-1;for(r=o.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==s[t])return o[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1};E.cosine=E.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())+ie,r.rounding=1,n=Xv(r,Th(r,n)),r.precision=e,r.rounding=t,X(Tn==2||Tn==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};E.cubeRoot=E.cbrt=function(){var e,t,n,r,i,a,o,s,c,u,l=this,d=l.constructor;if(!l.isFinite()||l.isZero())return new d(l);for(le=!1,a=l.s*ct(l.s*l,1/3),!a||Math.abs(a)==1/0?(n=St(l.d),e=l.e,(a=(e-n.length+1)%3)&&(n+=a==1||a==-2?"0":"00"),a=ct(n,1/3),e=Pt((e+1)/3)-(e%3==(e<0?-1:2)),a==1/0?n="5e"+e:(n=a.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new d(n),r.s=l.s):r=new d(a.toString()),o=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),u=c.plus(l),r=Le(u.plus(l).times(s),u.plus(c),o+2,1),St(s.d).slice(0,o)===(n=St(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(X(s,e+1,0),s.times(s).times(s).eq(l))){r=s;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(X(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return le=!0,X(r,e,d.rounding,t)};E.decimalPlaces=E.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-Pt(this.e/ie))*ie,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};E.dividedBy=E.div=function(e){return Le(this,new this.constructor(e))};E.dividedToIntegerBy=E.divToInt=function(e){var t=this,n=t.constructor;return X(Le(t,new n(e),0,1,1),n.precision,n.rounding)};E.equals=E.eq=function(e){return this.cmp(e)===0};E.floor=function(){return X(new this.constructor(this),this.e+1,3)};E.greaterThan=E.gt=function(e){return this.cmp(e)>0};E.greaterThanOrEqualTo=E.gte=function(e){var t=this.cmp(e);return t==1||t===0};E.hyperbolicCosine=E.cosh=function(){var e,t,n,r,i,a=this,o=a.constructor,s=new o(1);if(!a.isFinite())return new o(a.s?1/0:NaN);if(a.isZero())return s;n=o.precision,r=o.rounding,o.precision=n+Math.max(a.e,a.sd())+4,o.rounding=1,i=a.d.length,i<32?(e=Math.ceil(i/3),t=(1/Ao(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),a=Zr(o,1,a.times(t),new o(1),!0);for(var c,u=e,l=new o(8);u--;)c=a.times(a),a=s.minus(c.times(l.minus(c.times(l))));return X(a,o.precision=n,o.rounding=r,!0)};E.hyperbolicSine=E.sinh=function(){var e,t,n,r,i=this,a=i.constructor;if(!i.isFinite()||i.isZero())return new a(i);if(t=a.precision,n=a.rounding,a.precision=t+Math.max(i.e,i.sd())+4,a.rounding=1,r=i.d.length,r<3)i=Zr(a,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/Ao(5,e)),i=Zr(a,2,i,i,!0);for(var o,s=new a(5),c=new a(16),u=new a(20);e--;)o=i.times(i),i=i.times(s.plus(o.times(c.times(o).plus(u))))}return a.precision=t,a.rounding=n,X(i,t,n,!0)};E.hyperbolicTangent=E.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,Le(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};E.inverseCosine=E.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()?vn(t,r,i):new t(0):new t(NaN):e.isZero()?vn(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))};E.inverseHyperbolicCosine=E.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,le=!1,n=n.times(n).minus(1).sqrt().plus(n),le=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};E.inverseHyperbolicSine=E.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,le=!1,n=n.times(n).plus(1).sqrt().plus(n),le=!0,r.precision=e,r.rounding=t,n.ln())};E.inverseHyperbolicTangent=E.atanh=function(){var e,t,n,r,i=this,a=i.constructor;return i.isFinite()?i.e>=0?new a(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=a.precision,t=a.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?X(new a(i),e,t,!0):(a.precision=n=r-i.e,i=Le(i.plus(1),new a(1).minus(i),n+e,1),a.precision=e+4,a.rounding=1,i=i.ln(),a.precision=e,a.rounding=t,i.times(.5))):new a(NaN)};E.inverseSine=E.asin=function(){var e,t,n,r,i=this,a=i.constructor;return i.isZero()?new a(i):(t=i.abs().cmp(1),n=a.precision,r=a.rounding,t!==-1?t===0?(e=vn(a,n+4,r).times(.5),e.s=i.s,e):new a(NaN):(a.precision=n+6,a.rounding=1,i=i.div(new a(1).minus(i.times(i)).sqrt().plus(1)).atan(),a.precision=n,a.rounding=r,i.times(2)))};E.inverseTangent=E.atan=function(){var e,t,n,r,i,a,o,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<=Wc)return o=vn(l,d+4,m).times(.25),o.s=u.s,o}else{if(!u.s)return new l(NaN);if(d+4<=Wc)return o=vn(l,d+4,m).times(.5),o.s=u.s,o}for(l.precision=s=d+10,l.rounding=1,n=Math.min(28,s/ie+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(le=!1,t=Math.ceil(s/ie),r=1,c=u.times(u),o=new l(u),i=u;e!==-1;)if(i=i.times(c),a=o.minus(i.div(r+=2)),i=i.times(c),o=a.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===a.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),le=!0,X(o,l.precision=d,l.rounding=m,!0)};E.isFinite=function(){return!!this.d};E.isInteger=E.isInt=function(){return!!this.d&&Pt(this.e/ie)>this.d.length-2};E.isNaN=function(){return!this.s};E.isNegative=E.isNeg=function(){return this.s<0};E.isPositive=E.isPos=function(){return this.s>0};E.isZero=function(){return!!this.d&&this.d[0]===0};E.lessThan=E.lt=function(e){return this.cmp(e)<0};E.lessThanOrEqualTo=E.lte=function(e){return this.cmp(e)<1};E.logarithm=E.log=function(e){var t,n,r,i,a,o,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)a=!0;else{for(i=n[0];i%10===0;)i/=10;a=i!==1}if(le=!1,s=d+g,o=Qn(u,s),r=t?xo(l,s+10):Qn(e,s),c=Le(o,r,s,1),Xi(c.d,i=d,m))do if(s+=10,o=Qn(u,s),r=t?xo(l,s+10):Qn(e,s),c=Le(o,r,s,1),!a){+St(c.d).slice(i+1,i+15)+1==1e14&&(c=X(c,d+1,0));break}while(Xi(c.d,i+=10,m));return le=!0,X(c,d,m)};E.minus=E.sub=function(e){var t,n,r,i,a,o,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 le?X(e,s,c):e}if(n=Pt(e.e/ie),l=Pt(g.e/ie),u=u.slice(),a=l-n,a){for(d=a<0,d?(t=u,a=-a,o=m.length):(t=m,n=l,o=u.length),r=Math.max(Math.ceil(s/ie),o)+2,a>r&&(a=r,t.length=1),t.reverse(),r=a;r--;)t.push(0);t.reverse()}else{for(r=u.length,o=m.length,d=r<o,d&&(o=r),r=0;r<o;r++)if(u[r]!=m[r]){d=u[r]<m[r];break}a=0}for(d&&(t=u,u=m,m=t,e.s=-e.s),o=u.length,r=m.length-o;r>0;--r)u[o++]=0;for(r=m.length;r>a;){if(u[--r]<m[r]){for(i=r;i&&u[--i]===0;)u[i]=dn-1;--u[i],u[r]+=dn}u[r]-=m[r]}for(;u[--o]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=Io(u,n),le?X(e,s,c):e):new p(c===3?-0:0)};E.modulo=E.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]?X(new r(n),r.precision,r.rounding):(le=!1,r.modulo==9?(t=Le(n,e.abs(),0,3,1),t.s*=e.s):t=Le(n,e,0,r.modulo,1),t=t.times(e),le=!0,n.minus(t))};E.naturalExponential=E.exp=function(){return Qc(this)};E.naturalLogarithm=E.ln=function(){return Qn(this)};E.negated=E.neg=function(){var e=new this.constructor(this);return e.s=-e.s,X(e)};E.plus=E.add=function(e){var t,n,r,i,a,o,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)),le?X(e,s,c):e;if(a=Pt(d.e/ie),r=Pt(e.e/ie),u=u.slice(),i=a-r,i){for(i<0?(n=u,i=-i,o=l.length):(n=l,r=a,o=u.length),a=Math.ceil(s/ie),o=a>o?a+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=u.length,i=l.length,o-i<0&&(i=o,n=l,l=u,u=n),t=0;i;)t=(u[--i]=u[i]+l[i]+t)/dn|0,u[i]%=dn;for(t&&(u.unshift(t),++r),o=u.length;u[--o]==0;)u.pop();return e.d=u,e.e=Io(u,r),le?X(e,s,c):e};E.precision=E.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Zn+e);return n.d?(t=Ch(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};E.round=function(){var e=this,t=e.constructor;return X(new t(e),e.e+1,t.rounding)};E.sine=E.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())+ie,r.rounding=1,n=tI(r,Th(r,n)),r.precision=e,r.rounding=t,X(Tn>2?n.neg():n,e,t,!0)):new r(NaN)};E.squareRoot=E.sqrt=function(){var e,t,n,r,i,a,o=this,s=o.d,c=o.e,u=o.s,l=o.constructor;if(u!==1||!s||!s[0])return new l(!u||u<0&&(!s||s[0])?NaN:s?o:1/0);for(le=!1,u=Math.sqrt(+o),u==0||u==1/0?(t=St(s),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=Pt((c+1)/2)-(c<0||c%2),u==1/0?t="5e"+c:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new l(t)):r=new l(u.toString()),n=(c=l.precision)+3;;)if(a=r,r=a.plus(Le(o,a,n+2,1)).times(.5),St(a.d).slice(0,n)===(t=St(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(X(a,c+1,0),a.times(a).eq(o))){r=a;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(X(r,c+1,1),e=!r.times(r).eq(o));break}return le=!0,X(r,c,l.rounding,e)};E.tangent=E.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=Le(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,X(Tn==2||Tn==4?n.neg():n,e,t,!0)):new r(NaN)};E.times=E.mul=function(e){var t,n,r,i,a,o,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=Pt(l.e/ie)+Pt(e.e/ie),c=m.length,u=g.length,c<u&&(a=m,m=g,g=a,o=c,c=u,u=o),a=[],o=c+u,r=o;r--;)a.push(0);for(r=u;--r>=0;){for(t=0,i=c+r;i>r;)s=a[i]+g[r]*m[i-r-1]+t,a[i--]=s%dn|0,t=s/dn|0;a[i]=(a[i]+t)%dn|0}for(;!a[--o];)a.pop();return t?++n:a.shift(),e.d=a,e.e=Io(a,n),le?X(e,d.precision,d.rounding):e};E.toBinary=function(e,t){return Zc(this,2,e,t)};E.toDecimalPlaces=E.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Nt(e,0,zn),t===void 0?t=r.rounding:Nt(t,0,8),X(n,e+n.e+1,t))};E.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=In(r,!0):(Nt(e,0,zn),t===void 0?t=i.rounding:Nt(t,0,8),r=X(new i(r),e+1,t),n=In(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};E.toFixed=function(e,t){var n,r,i=this,a=i.constructor;return e===void 0?n=In(i):(Nt(e,0,zn),t===void 0?t=a.rounding:Nt(t,0,8),r=X(new a(i),e+i.e+1,t),n=In(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};E.toFraction=function(e){var t,n,r,i,a,o,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),a=t.e=Ch(p)-g.e-1,o=a%ie,t.d[0]=ct(10,o<0?ie+o:o),e==null)e=a>0?t:u;else{if(s=new h(e),!s.isInt()||s.lt(u))throw Error(Zn+s);e=s.gt(t)?a>0?t:u:s}for(le=!1,s=new h(St(p)),l=h.precision,h.precision=a=p.length*ie*2;d=Le(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=Le(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=Le(u,r,a,1).minus(g).abs().cmp(Le(c,n,a,1).minus(g).abs())<1?[u,r]:[c,n],h.precision=l,le=!0,m};E.toHexadecimal=E.toHex=function(e,t){return Zc(this,16,e,t)};E.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:Nt(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]?(le=!1,n=Le(n,e,0,t,1).times(e),le=!0,X(n)):(e.s=n.s,n=e),n};E.toNumber=function(){return+this};E.toOctal=function(e,t){return Zc(this,8,e,t)};E.toPower=E.pow=function(e){var t,n,r,i,a,o,s=this,c=s.constructor,u=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(ct(+s,u));if(s=new c(s),s.eq(1))return s;if(r=c.precision,a=c.rounding,e.eq(1))return X(s,r,a);if(t=Pt(e.e/ie),t>=e.d.length-1&&(n=u<0?-u:u)<=Yv)return i=wh(c,s,n,r),e.s<0?new c(1).div(i):X(i,r,a);if(o=s.s,o<0){if(t<e.d.length-1)return new c(NaN);if((e.d[t]&1)==0&&(o=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=o,s}return n=ct(+s,u),t=n==0||!isFinite(n)?Pt(u*(Math.log("0."+St(s.d))/Math.LN10+s.e+1)):new c(n+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?o/0:0):(le=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Qc(e.times(Qn(s,r+n)),r),i.d&&(i=X(i,r+5,1),Xi(i.d,r,a)&&(t=r+10,i=X(Qc(e.times(Qn(s,t+n)),t),t+5,1),+St(i.d).slice(r+1,r+15)+1==1e14&&(i=X(i,r+1,0)))),i.s=o,le=!0,c.rounding=a,X(i,r,a))};E.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=In(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Nt(e,1,zn),t===void 0?t=i.rounding:Nt(t,0,8),r=X(new i(r),e,t),n=In(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};E.toSignificantDigits=E.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Nt(e,1,zn),t===void 0?t=r.rounding:Nt(t,0,8)),X(new r(n),e,t)};E.toString=function(){var e=this,t=e.constructor,n=In(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};E.truncated=E.trunc=function(){return X(new this.constructor(this),this.e+1,1)};E.valueOf=E.toJSON=function(){var e=this,t=e.constructor,n=In(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function St(e){var t,n,r,i=e.length-1,a="",o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+"",n=ie-r.length,n&&(a+=Wn(n)),a+=r;o=e[t],r=o+"",n=ie-r.length,n&&(a+=Wn(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return a+o}function Nt(e,t,n){if(e!==~~e||e<t||e>n)throw Error(Zn+e)}function Xi(e,t,n,r){var i,a,o,s;for(a=e[0];a>=10;a/=10)--t;return--t<0?(t+=ie,i=0):(i=Math.ceil((t+1)/ie),t%=ie),a=ct(10,ie-t),s=e[i]%a|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),o=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):o=(n<4&&s+1==a||n>3&&s+1==a/2)&&(e[i+1]/a/100|0)==ct(10,t-2)-1||(s==a/2||s==0)&&(e[i+1]/a/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),o=(r||n<4)&&s==9999||!r&&n>3&&s==4999):o=((r||n<4)&&s+1==a||!r&&n>3&&s+1==a/2)&&(e[i+1]/a/1e3|0)==ct(10,t-3)-1,o}function bo(e,t,n){for(var r,i=[0],a,o=0,s=e.length;o<s;){for(a=i.length;a--;)i[a]*=t;for(i[0]+=Hc.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function Xv(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/Ao(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=Zr(e,1,t.times(i),new e(1));for(var a=n;a--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var Le=(function(){function e(r,i,a){var o,s=0,c=r.length;for(r=r.slice();c--;)o=r[c]*i+s,r[c]=o%a|0,s=o/a|0;return s&&r.unshift(s),r}function t(r,i,a,o){var s,c;if(a!=o)c=a>o?1:-1;else for(s=c=0;s<a;s++)if(r[s]!=i[s]){c=r[s]>i[s]?1:-1;break}return c}function n(r,i,a,o){for(var s=0;a--;)r[a]-=s,s=r[a]<i[a]?1:0,r[a]=s*o+r[a]-i[a];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,a,o,s,c){var u,l,d,m,g,p,h,x,I,v,j,T,P,_e,nt,Ze,je,ue,V,De,Z=r.constructor,mt=r.s==i.s?1:-1,fe=r.d,ce=i.d;if(!fe||!fe[0]||!ce||!ce[0])return new Z(!r.s||!i.s||(fe?ce&&fe[0]==ce[0]:!ce)?NaN:fe&&fe[0]==0||!ce?mt*0:mt/0);for(c?(g=1,l=r.e-i.e):(c=dn,g=ie,l=Pt(r.e/g)-Pt(i.e/g)),V=ce.length,je=fe.length,I=new Z(mt),v=I.d=[],d=0;ce[d]==(fe[d]||0);d++);if(ce[d]>(fe[d]||0)&&l--,a==null?(_e=a=Z.precision,o=Z.rounding):s?_e=a+(r.e-i.e)+1:_e=a,_e<0)v.push(1),p=!0;else{if(_e=_e/g+2|0,d=0,V==1){for(m=0,ce=ce[0],_e++;(d<je||m)&&_e--;d++)nt=m*c+(fe[d]||0),v[d]=nt/ce|0,m=nt%ce|0;p=m||d<je}else{for(m=c/(ce[0]+1)|0,m>1&&(ce=e(ce,m,c),fe=e(fe,m,c),V=ce.length,je=fe.length),Ze=V,j=fe.slice(0,V),T=j.length;T<V;)j[T++]=0;De=ce.slice(),De.unshift(0),ue=ce[0],ce[1]>=c/2&&++ue;do m=0,u=t(ce,j,V,T),u<0?(P=j[0],V!=T&&(P=P*c+(j[1]||0)),m=P/ue|0,m>1?(m>=c&&(m=c-1),h=e(ce,m,c),x=h.length,T=j.length,u=t(h,j,x,T),u==1&&(m--,n(h,V<x?De:ce,x,c))):(m==0&&(u=m=1),h=ce.slice()),x=h.length,x<T&&h.unshift(0),n(j,h,T,c),u==-1&&(T=j.length,u=t(ce,j,V,T),u<1&&(m++,n(j,V<T?De:ce,T,c))),T=j.length):u===0&&(m++,j=[0]),v[d++]=m,u&&j[0]?j[T++]=fe[Ze]||0:(j=[fe[Ze]],T=1);while((Ze++<je||j[0]!==void 0)&&_e--);p=j[0]!==void 0}v[0]||v.shift()}if(g==1)I.e=l,xh=p;else{for(d=1,m=v[0];m>=10;m/=10)d++;I.e=d+l*g-1,X(I,s?a+I.e+1:a,o,p)}return I}})();function X(e,t,n,r){var i,a,o,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(a=t-i,a<0)a+=ie,o=t,l=d[m=0],c=l/ct(10,i-o-1)%10|0;else if(m=Math.ceil((a+1)/ie),s=d.length,m>=s)if(r){for(;s++<=m;)d.push(0);l=c=0,i=1,a%=ie,o=a-ie+1}else break e;else{for(l=s=d[m],i=1;s>=10;s/=10)i++;a%=ie,o=a-ie+i,c=o<0?0:l/ct(10,i-o-1)%10|0}if(r=r||t<0||d[m+1]!==void 0||(o<0?l:l%ct(10,i-o-1)),u=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(a>0?o>0?l/ct(10,i-o):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]=ct(10,(ie-t%ie)%ie),e.e=-t||0):d[0]=e.e=0,e;if(a==0?(d.length=m,s=1,m--):(d.length=m+1,s=ct(10,ie-a),d[m]=o>0?(l/ct(10,i-o)%ct(10,o)|0)*s:0),u)for(;;)if(m==0){for(a=1,o=d[0];o>=10;o/=10)a++;for(o=d[0]+=s,s=1;o>=10;o/=10)s++;a!=s&&(e.e++,d[0]==dn&&(d[0]=1));break}else{if(d[m]+=s,d[m]!=dn)break;d[m--]=0,s=1}for(a=d.length;d[--a]===0;)d.pop()}return le&&(e.e>g.maxE?(e.d=null,e.e=NaN):e.e<g.minE&&(e.e=0,e.d=[0])),e}function In(e,t,n){if(!e.isFinite())return Eh(e);var r,i=e.e,a=St(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+"."+a.slice(1)+Wn(r):o>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(e.e<0?"e":"e+")+e.e):i<0?(a="0."+Wn(-i-1)+a,n&&(r=n-o)>0&&(a+=Wn(r))):i>=o?(a+=Wn(i+1-o),n&&(r=n-i-1)>0&&(a=a+"."+Wn(r))):((r=i+1)<o&&(a=a.slice(0,r)+"."+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+="."),a+=Wn(r))),a}function Io(e,t){var n=e[0];for(t*=ie;n>=10;n/=10)t++;return t}function xo(e,t,n){if(t>Jv)throw le=!0,n&&(e.precision=n),Error(vh);return X(new e(yo),t,1,!0)}function vn(e,t,n){if(t>Wc)throw Error(vh);return X(new e(So),t,n,!0)}function Ch(e){var t=e.length-1,n=t*ie+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 Wn(e){for(var t="";e--;)t+="0";return t}function wh(e,t,n,r){var i,a=new e(1),o=Math.ceil(r/ie+4);for(le=!1;;){if(n%2&&(a=a.times(t),yh(a.d,o)&&(i=!0)),n=Pt(n/2),n===0){n=a.d.length-1,i&&a.d[n]===0&&++a.d[n];break}t=t.times(t),yh(t.d,o)}return le=!0,a}function _h(e){return e.d[e.d.length-1]&1}function Oh(e,t,n){for(var r,i,a=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){a=i;break}r=a.cmp(i),(r===n||r===0&&a.s===n)&&(a=i)}return a}function Qc(e,t){var n,r,i,a,o,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?(le=!1,c=p):c=t,s=new m(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(ct(2,d))/Math.LN10*2+5|0,c+=r,n=a=o=new m(1),m.precision=c;;){if(a=X(a.times(e),c,1),n=n.times(++l),s=o.plus(Le(a,n,c,1)),St(s.d).slice(0,c)===St(o.d).slice(0,c)){for(i=d;i--;)o=X(o.times(o),c,1);if(t==null)if(u<3&&Xi(o.d,c-r,g,u))m.precision=c+=10,n=a=s=new m(1),l=0,u++;else return X(o,m.precision=p,g,le=!0);else return m.precision=p,o}o=s}}function Qn(e,t){var n,r,i,a,o,s,c,u,l,d,m,g=1,p=10,h=e,x=h.d,I=h.constructor,v=I.rounding,j=I.precision;if(h.s<0||!x||!x[0]||!h.e&&x[0]==1&&x.length==1)return new I(x&&!x[0]?-1/0:h.s!=1?NaN:x?0:h);if(t==null?(le=!1,l=j):l=t,I.precision=l+=p,n=St(x),r=n.charAt(0),Math.abs(a=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=St(h.d),r=n.charAt(0),g++;a=h.e,r>1?(h=new I("0."+n),a++):h=new I(r+"."+n.slice(1))}else return u=xo(I,l+2,j).times(a+""),h=Qn(new I(r+"."+n.slice(1)),l-p).plus(u),I.precision=j,t==null?X(h,j,v,le=!0):h;for(d=h,c=o=h=Le(h.minus(1),h.plus(1),l,1),m=X(h.times(h),l,1),i=3;;){if(o=X(o.times(m),l,1),u=c.plus(Le(o,new I(i),l,1)),St(u.d).slice(0,l)===St(c.d).slice(0,l))if(c=c.times(2),a!==0&&(c=c.plus(xo(I,l+2,j).times(a+""))),c=Le(c,new I(g),l,1),t==null)if(Xi(c.d,l-p,v,s))I.precision=l+=p,u=o=h=Le(d.minus(1),d.plus(1),l,1),m=X(h.times(h),l,1),i=s=1;else return X(c,I.precision=j,v,le=!0);else return I.precision=j,c;c=u,i+=2}}function Eh(e){return String(e.s*e.s/0)}function _o(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)%ie,n<0&&(r+=ie),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=ie;r<i;)e.d.push(+t.slice(r,r+=ie));t=t.slice(r),r=ie-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),le&&(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 eI(e,t){var n,r,i,a,o,s,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Ph.test(t))return _o(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Zv.test(t))n=16,t=t.toLowerCase();else if(Qv.test(t))n=2;else if(zv.test(t))n=8;else throw Error(Zn+t);for(a=t.search(/p/i),a>0?(c=+t.slice(a+1),t=t.substring(2,a)):t=t.slice(2),a=t.indexOf("."),o=a>=0,r=e.constructor,o&&(t=t.replace(".",""),s=t.length,a=s-a,i=wh(r,new r(n),a,a*2)),u=bo(t,n,dn),l=u.length-1,a=l;u[a]===0;--a)u.pop();return a<0?new r(e.s*0):(e.e=Io(u,l),e.d=u,le=!1,o&&(e=Le(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?ct(2,c):mn.pow(2,c))),le=!0,e)}function tI(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:Zr(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/Ao(5,n)),t=Zr(e,2,t,t);for(var i,a=new e(5),o=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(a.plus(i.times(o.times(i).minus(s))));return t}function Zr(e,t,n,r,i){var a,o,s,c,u=1,l=e.precision,d=Math.ceil(l/ie);for(le=!1,c=n.times(n),s=new e(r);;){if(o=Le(s.times(c),new e(t++*t++),l,1),s=i?r.plus(o):r.minus(o),r=Le(o.times(c),new e(t++*t++),l,1),o=s.plus(r),o.d[d]!==void 0){for(a=d;o.d[a]===s.d[a]&&a--;);if(a==-1)break}a=s,s=r,r=o,o=a,u++}return le=!0,o.d.length=d+1,o}function Ao(e,t){for(var n=e;--t;)n*=e;return n}function Th(e,t){var n,r=t.s<0,i=vn(e,e.precision,1),a=i.times(.5);if(t=t.abs(),t.lte(a))return Tn=r?4:1,t;if(n=t.divToInt(i),n.isZero())Tn=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(a))return Tn=_h(n)?r?2:3:r?4:1,t;Tn=_h(n)?r?1:4:r?3:2}return t.minus(i).abs()}function Zc(e,t,n,r){var i,a,o,s,c,u,l,d,m,g=e.constructor,p=n!==void 0;if(p?(Nt(n,1,zn),r===void 0?r=g.rounding:Nt(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())l=Eh(e);else{for(l=In(e),o=l.indexOf("."),p?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(l=l.replace(".",""),m=new g(1),m.e=l.length-o,m.d=bo(In(m),10,i),m.e=m.d.length),d=bo(l,10,i),a=c=d.length;d[--c]==0;)d.pop();if(!d[0])l=p?"0p+0":"0";else{if(o<0?a--:(e=new g(e),e.d=d,e.e=a,e=Le(e,m,n,r,0,i),d=e.d,a=e.e,u=xh),o=d[n],s=i/2,u=u||d[n+1]!==void 0,u=r<4?(o!==void 0||u)&&(r===0||r===(e.s<0?3:2)):o>s||o===s&&(r===4||u||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,u)for(;++d[--n]>i-1;)d[n]=0,n||(++a,d.unshift(1));for(c=d.length;!d[c-1];--c);for(o=0,l="";o<c;o++)l+=Hc.charAt(d[o]);if(p){if(c>1)if(t==16||t==8){for(o=t==16?4:3,--c;c%o;c++)l+="0";for(d=bo(l,i,t),c=d.length;!d[c-1];--c);for(o=1,l="1.";o<c;o++)l+=Hc.charAt(d[o])}else l=l.charAt(0)+"."+l.slice(1);l=l+(a<0?"p":"p+")+a}else if(a<0){for(;++a;)l="0"+l;l="0."+l}else if(++a>c)for(a-=c;a--;)l+="0";else a<c&&(l=l.slice(0,a)+"."+l.slice(a))}l=(t==16?"0x":t==2?"0b":t==8?"0o":"")+l}return e.s<0?"-"+l:l}function yh(e,t){if(e.length>t)return e.length=t,!0}function nI(e){return new this(e).abs()}function rI(e){return new this(e).acos()}function iI(e){return new this(e).acosh()}function aI(e,t){return new this(e).plus(t)}function oI(e){return new this(e).asin()}function sI(e){return new this(e).asinh()}function cI(e){return new this(e).atan()}function uI(e){return new this(e).atanh()}function lI(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,a=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=vn(this,a,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?vn(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=vn(this,a,1).times(.5),n.s=e.s):t.s<0?(this.precision=a,this.rounding=1,n=this.atan(Le(e,t,a,1)),t=vn(this,a,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Le(e,t,a,1)),n}function dI(e){return new this(e).cbrt()}function mI(e){return X(e=new this(e),e.e+1,2)}function pI(e,t,n){return new this(e).clamp(t,n)}function fI(e){if(!e||typeof e!="object")throw Error(vo+"Object expected");var t,n,r,i=e.defaults===!0,a=["precision",1,zn,"rounding",0,8,"toExpNeg",-Qr,0,"toExpPos",0,Qr,"maxE",0,Qr,"minE",-Qr,0,"modulo",0,9];for(t=0;t<a.length;t+=3)if(n=a[t],i&&(this[n]=Kc[n]),(r=e[n])!==void 0)if(Pt(r)===r&&r>=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(Zn+n+": "+r);if(n="crypto",i&&(this[n]=Kc[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(Ih);else this[n]=!1;else throw Error(Zn+n+": "+r);return this}function hI(e){return new this(e).cos()}function gI(e){return new this(e).cosh()}function Rh(e){var t,n,r;function i(a){var o,s,c,u=this;if(!(u instanceof i))return new i(a);if(u.constructor=i,Sh(a)){u.s=a.s,le?!a.d||a.e>i.maxE?(u.e=NaN,u.d=null):a.e<i.minE?(u.e=0,u.d=[0]):(u.e=a.e,u.d=a.d.slice()):(u.e=a.e,u.d=a.d?a.d.slice():a.d);return}if(c=typeof a,c==="number"){if(a===0){u.s=1/a<0?-1:1,u.e=0,u.d=[0];return}if(a<0?(a=-a,u.s=-1):u.s=1,a===~~a&&a<1e7){for(o=0,s=a;s>=10;s/=10)o++;le?o>i.maxE?(u.e=NaN,u.d=null):o<i.minE?(u.e=0,u.d=[0]):(u.e=o,u.d=[a]):(u.e=o,u.d=[a]);return}if(a*0!==0){a||(u.s=NaN),u.e=NaN,u.d=null;return}return _o(u,a.toString())}if(c==="string")return(s=a.charCodeAt(0))===45?(a=a.slice(1),u.s=-1):(s===43&&(a=a.slice(1)),u.s=1),Ph.test(a)?_o(u,a):eI(u,a);if(c==="bigint")return a<0?(a=-a,u.s=-1):u.s=1,_o(u,a.toString());throw Error(Zn+a)}if(i.prototype=E,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=fI,i.clone=Rh,i.isDecimal=Sh,i.abs=nI,i.acos=rI,i.acosh=iI,i.add=aI,i.asin=oI,i.asinh=sI,i.atan=cI,i.atanh=uI,i.atan2=lI,i.cbrt=dI,i.ceil=mI,i.clamp=pI,i.cos=hI,i.cosh=gI,i.div=bI,i.exp=_I,i.floor=yI,i.hypot=SI,i.ln=xI,i.log=vI,i.log10=AI,i.log2=II,i.max=PI,i.min=CI,i.mod=wI,i.mul=OI,i.pow=EI,i.random=TI,i.round=RI,i.sign=kI,i.sin=jI,i.sinh=NI,i.sqrt=DI,i.sub=UI,i.sum=FI,i.tan=MI,i.tanh=LI,i.trunc=BI,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 bI(e,t){return new this(e).div(t)}function _I(e){return new this(e).exp()}function yI(e){return X(e=new this(e),e.e+1,3)}function SI(){var e,t,n=new this(0);for(le=!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 le=!0,new this(1/0);n=t}return le=!0,n.sqrt()}function Sh(e){return e instanceof mn||e&&e.toStringTag===Ah||!1}function xI(e){return new this(e).ln()}function vI(e,t){return new this(e).log(t)}function II(e){return new this(e).log(2)}function AI(e){return new this(e).log(10)}function PI(){return Oh(this,arguments,-1)}function CI(){return Oh(this,arguments,1)}function wI(e,t){return new this(e).mod(t)}function OI(e,t){return new this(e).mul(t)}function EI(e,t){return new this(e).pow(t)}function TI(e){var t,n,r,i,a=0,o=new this(1),s=[];if(e===void 0?e=this.precision:Nt(e,1,zn),r=Math.ceil(e/ie),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));a<r;)i=t[a],i>=429e7?t[a]=crypto.getRandomValues(new Uint32Array(1))[0]:s[a++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);a<r;)i=t[a]+(t[a+1]<<8)+(t[a+2]<<16)+((t[a+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,a):(s.push(i%1e7),a+=4);a=r/4}else throw Error(Ih);else for(;a<r;)s[a++]=Math.random()*1e7|0;for(r=s[--a],e%=ie,r&&e&&(i=ct(10,ie-e),s[a]=(r/i|0)*i);s[a]===0;a--)s.pop();if(a<0)n=0,s=[0];else{for(n=-1;s[0]===0;n-=ie)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<ie&&(n-=ie-r)}return o.e=n,o.d=s,o}function RI(e){return X(e=new this(e),e.e+1,this.rounding)}function kI(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function jI(e){return new this(e).sin()}function NI(e){return new this(e).sinh()}function DI(e){return new this(e).sqrt()}function UI(e,t){return new this(e).sub(t)}function FI(){var e=0,t=arguments,n=new this(t[e]);for(le=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return le=!0,X(n,this.precision,this.rounding)}function MI(e){return new this(e).tan()}function LI(e){return new this(e).tanh()}function BI(e){return X(e=new this(e),e.e+1,1)}E[Symbol.for("nodejs.util.inspect.custom")]=E.toString;E[Symbol.toStringTag]="Decimal";var mn=E.constructor=Rh(Kc);yo=new mn(yo);So=new mn(So);var{PAYLOAD_BYTES:qI}={PAYLOAD_BYTES:20},{KSUID_EPOCH:VI}={KSUID_EPOCH:14e8},{getRandomBytes:$I}={getRandomBytes:({size:t})=>{let n=new Uint8Array(t);return globalThis.crypto.getRandomValues(n),n}},{ALPHABET:GI}={ALPHABET:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},{ENCODED_LENGTH:HI}={ENCODED_LENGTH:27},{base62Encode:KI}=(e=>({base62Encode:({bytes:n,padTo:r})=>{let i=[],a=new Uint8Array(n),o=!1;for(;!o;){o=!0;let s=0;for(let c=0;c<a.length;c++){let u=s*256+a[c];a[c]=Math.floor(u/62),s=u%62,a[c]!==0&&(o=!1)}i.push(s)}for(i.reverse();i.length<r;)i.unshift(0);return i.map(s=>e[s]).join("")}}))(GI),{generateKsuid:kh}=((e,t,n,r,i)=>({generateKsuid:({prefix:o=""}={})=>{let s=new Uint8Array(e),c=Math.floor(Date.now()/1e3)-t;s[0]=c>>>24&255,s[1]=c>>>16&255,s[2]=c>>>8&255,s[3]=c&255;let u=n({size:16});s.set(u,4);let l=r({bytes:s,padTo:i});return`${o}${l}`}}))(qI,VI,$I,KI,HI);var jh={randomSync:()=>({string:kh({})})};import{z as Ae}from"zod/v4";var WI=202,QI=502,ZI=400,zI=409,YI=100,JI=201,XI=417;var eA=403,tA=504,nA=410,rA=505,iA=418,aA=419,oA=507,sA=500,cA=411,uA=423,lA=420,dA=405,mA=301,pA=302,fA=207,hA=300,gA=511,bA=204,_A=203,yA=406,SA=404,xA=501,vA=304,IA=200,AA=206,PA=402,CA=308,wA=412,OA=428,EA=102,TA=407,RA=431,kA=408,jA=413,NA=414,DA=416,UA=205,FA=303,MA=503,LA=101,BA=307,qA=429,VA=401,$A=422,GA=415,HA=305,Nh={ACCEPTED:WI,BAD_GATEWAY:QI,BAD_REQUEST:ZI,CONFLICT:zI,CONTINUE:YI,CREATED:JI,EXPECTATION_FAILED:XI,FORBIDDEN:eA,GATEWAY_TIMEOUT:tA,GONE:nA,HTTP_VERSION_NOT_SUPPORTED:rA,IM_A_TEAPOT:iA,INSUFFICIENT_SPACE_ON_RESOURCE:aA,INSUFFICIENT_STORAGE:oA,INTERNAL_SERVER_ERROR:sA,LENGTH_REQUIRED:cA,LOCKED:uA,METHOD_FAILURE:lA,METHOD_NOT_ALLOWED:dA,MOVED_PERMANENTLY:mA,MOVED_TEMPORARILY:pA,MULTI_STATUS:fA,MULTIPLE_CHOICES:hA,NETWORK_AUTHENTICATION_REQUIRED:gA,NO_CONTENT:bA,NON_AUTHORITATIVE_INFORMATION:_A,NOT_ACCEPTABLE:yA,NOT_FOUND:SA,NOT_IMPLEMENTED:xA,NOT_MODIFIED:vA,OK:IA,PARTIAL_CONTENT:AA,PAYMENT_REQUIRED:PA,PERMANENT_REDIRECT:CA,PRECONDITION_FAILED:wA,PRECONDITION_REQUIRED:OA,PROCESSING:EA,PROXY_AUTHENTICATION_REQUIRED:TA,REQUEST_HEADER_FIELDS_TOO_LARGE:RA,REQUEST_TIMEOUT:kA,REQUEST_TOO_LONG:jA,REQUEST_URI_TOO_LONG:NA,REQUESTED_RANGE_NOT_SATISFIABLE:DA,RESET_CONTENT:UA,SEE_OTHER:FA,SERVICE_UNAVAILABLE:MA,SWITCHING_PROTOCOLS:LA,TEMPORARY_REDIRECT:BA,TOO_MANY_REQUESTS:qA,UNAUTHORIZED:VA,UNPROCESSABLE_ENTITY:$A,UNSUPPORTED_MEDIA_TYPE:GA,USE_PROXY:HA};var Dh={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"},Uh={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 KA(e){var t=Dh[e.toString()];if(!t)throw new Error("Status code does not exist: "+e);return t}function Fh(e){var t=Uh[e];if(!t)throw new Error("Reason phrase does not exist: "+e);return t}var Mh=KA;var Yn;(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"})(Yn||(Yn={}));var Po=function(){return Po=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},Po.apply(this,arguments)},L4=Po(Po({},Nh),{getStatusCode:Fh,getStatusText:Mh});var{generateId:zr}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(jh),{BILLING_CONTROL_KEYS:Co}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:WA}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:Lh}={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:Jt}={nullish:t=>t==null},{FeatureType:Ct}=(()=>{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:wo}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:ea}={Infinite:"inf"},{EntInterval:Yr}=(()=>{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:Rn}=(()=>{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:QA}={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:ZA}={usageCurrenciesToTiers:(t,n)=>{if(!t||n<=0)return;let r=Object.entries(t);if(r.length===0)return;let i=Array.from({length:n},()=>[]);for(let[a,o]of r)(o.usage_tiers??[]).forEach((s,c)=>{c<n&&i[c].push({currency:a,amount:s.amount,...s.flat_amount!==void 0?{flat_amount:s.flat_amount}:{}})});return i}},{TierInfinite:zc}={TierInfinite:"inf"},{FeatureUsageType:Jn}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:Jr}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Usage="usage"})(e||(e={})),{PriceType:e}})(),{BillingType:Xr}=(()=>{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:ta}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Xn}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:kn}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:ei}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{InternalError:zA}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=500,data:a}){super(n),this.name="InternalError",this.code=r||"internal_error",this.statusCode=i,this.data=a}}return{InternalError:e}})(),{getItemFeatureType:Bh}=((e,t)=>({getItemFeatureType:({item:r,features:i})=>{let a=i.find(o=>o.id===r.feature_id);if(a)return a.type===e.Boolean?t.Static:a.type===e.CreditSystem?t.SingleUse:a.config?.usage_type}}))(Ct,kn),{billingControlsFromColumns:qh}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(Co),{nullish:ti}={nullish:t=>t==null},{RecaseError:Dt}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=400,data:a}){super(n),this.name="RecaseError",this.code=r||"invalid_request",this.statusCode=i,this.data=a}}return{RecaseError:e}})(),{ErrCode:Vt}={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:YA}=((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})}}))(Dt,Vt),{notNullish:ni}=(e=>({notNullish:n=>!e(n)}))(ti),{keyToTitle:Vh}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:JA}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:XA}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ApiFeatureType:e1}=(()=>{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:Yc}=(()=>{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:$h}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:t1}={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:n1}=(e=>({COMMON_SET:new Set(e)}))($h),{hasNoDuplicateCurrencies:Gh}={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:Hh}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{TierBehavior:Oo}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:ri}=(()=>{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:na}=(()=>{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:Jc}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:r1}=(()=>{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:i1}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:a1}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Kh}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ae),{flatCreditRateShape:Wh}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(Ae),{CreditTierSchema:o1}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(Ae),{CreditMultiplierSchema:s1}=((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"})}))(Ae,Kh),{MarkupEntrySchema:Qh}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ae),{ModelMarkupsSchema:c1}=((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()}))(Ae,Qh),{isFeaturePriceItem:Xc}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(ni),{notNullish:vr}={notNullish:t=>t!=null},{isAiCreditSystem:eu}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(Ct),{VIOLATION_MESSAGES:u1}={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:l1}={sameSpecificity:(t,n)=>Object.keys(t.match).length===Object.keys(n.match).length&&(t.priority??null)===(n.priority??null)},{matchesCanCoexist:Zh}={matchesCanCoexist:(t,n)=>Object.entries(t).every(([r,i])=>{let a=Object.entries(n).find(([o])=>o===r)?.[1];return a===void 0||a===i})},{formatCreditMatch:d1}={formatCreditMatch:t=>Object.entries(t).map(([n,r])=>`${n}=${r}`).join(", ")},{validateMultiplierShape:m1}={validateMultiplierShape:({name:t,multiplier:n,invalidCreditSystem:r})=>{let i=n.factor!==void 0,a=n.add!==void 0;!i&&!a&&r(`Multiplier "${t}" needs a factor or an add.`);let o=Number(n.factor);i&&!(Number.isFinite(o)&&o>0)&&r(`Multiplier "${t}" factor must be greater than zero.`);let s=Number(n.add);a&&!Number.isFinite(s)&&r(`Multiplier "${t}" add must be a number.`),i&&(n.factor=o),a&&(n.add=s)}},{minimumCreditRateAmount:p1}={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:f1}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((a,o)=>{let s=[];for(let u of r){let l=u.factor!==void 0&&u.factor<1||u.add!==void 0&&u.add<0,d=s.every(m=>e(m.match,u.match));(l||u===o)&&e(o.match,u.match)&&d&&s.push(u)}let c=s.reduce((u,l)=>u.mul(l.factor!==void 0&&l.factor<1?l.factor:1).add(l.add!==void 0&&l.add<0?l.add:0),new t(i));return t.min(a,c)},new t(i))}))(Zh,mn),{validateCreditSystemSchemaReferences:h1}=((e,t,n,r)=>({validateCreditSystemSchemaReferences:({config:a,allFeatures:o,selfFeatureId:s})=>{let c=Array.isArray(a?.schema)?a.schema:[];if(c.length!==0)for(let u of c){let l=u.metered_feature_id;if(!l||l===s)continue;let d=o.find(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})}}}}))(Ct,Dt,Vt,Jn),{isPriceItem:tu}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(ni,ti),{isFeatureItem:Eo}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(ni,ti),{itemToBillingInterval:er}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(Jt,Rn),{rolloverConfigToIssue:g1}={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:To}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(Jt,Yr,kn),{itemToEntIntervalCount:Ro}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:ii}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:ko}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(vr,Jt),{toKey:zh}={toKey:t=>t.toLowerCase()},{priceOwnedStripePriceId:b1}=(e=>({priceOwnedStripePriceId:({price:n})=>{let r=n.config,i=r.stripe_prepaid_price_v2_id||r.stripe_price_id;return e(i)?null:i}}))(Jt),{UsageTierSchema:nu}=((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()}))}))(Ae,ea),{IgnoredFixedPriceMetadataSchema:_1}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(Ae),{hasCatalogCurrencies:y1}={hasCatalogCurrencies:t=>Object.keys(t??{}).length>0},{usageTiersToComparisonShape:S1}={usageTiersToComparisonShape:t=>t.map((n,r)=>({amount:n.amount,flat_amount:n.flat_amount??0,to:r===t.length-1?null:n.to}))},{normalizedAllocatedBillingBehavior:x1}=(e=>({normalizedAllocatedBillingBehavior:n=>n.allocated_billing_behavior??(n.should_prorate?e.Prorated:e.Arrear)}))(Xn),{getResetUsage:Yh}=((e,t,n,r)=>({getResetUsage:({item:a,feature:o})=>{if(a.feature_id)return e(a.reset_usage_when_enabled)&&(t(a)||n(a))&&o?o?.config?.usage_type===r.Single:a.reset_usage_when_enabled}}))(ti,Eo,Xc,Jn),{hasUnlimitedAllowanceType:v1}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(wo),{normalizedEntitlementInterval:Jh}=(e=>({normalizedEntitlementInterval:n=>n.interval??e.Lifetime}))(Yr),{normalizedEntitlementIntervalCount:I1}=((e,t)=>({normalizedEntitlementIntervalCount:r=>e(r)===t.Lifetime?1:r.interval_count??1}))(Jh,Yr),{normalizeOptionalId:A1}={normalizeOptionalId:t=>t||null},{rolloversAreSame:P1}=(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}))(Jc),{deterministicStringify:ru}=(()=>{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:C1}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:w1}={expiriesAreSame:(t,n)=>(t.expiry_duration??null)===(n.expiry_duration??null)&&(t.expiry_length??null)==(n.expiry_length??null)},{itemToFeature:Xh}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{isFeaturePriceItem:ai}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(vr),{ProductErrorCode:O1}={ProductErrorCode:{ProductNotFound:"product_not_found",ProductAlreadyExists:"product_already_exists",InvalidProductItem:"invalid_product_item"}},{buildUsagePriceCurrencies:E1}=(e=>({buildUsagePriceCurrencies:({baseTiers:n,itemTiers:r,flatCurrencies:i})=>{if(r?.length){let a=[...new Set(r.flatMap(s=>(s.additional_currencies??[]).map(c=>e(c.currency))))];if(a.length===0)return;let o={};for(let s of a)o[s]={usage_tiers:n.map((c,u)=>{let l=(r[u]?.additional_currencies??[]).find(d=>e(d.currency)===s);return{to:c.to,amount:l?.amount??0,...l?.flat_amount!==void 0?{flat_amount:l.flat_amount}:{}}})};return o}if(i?.length&&n.length>0){let a={};for(let{currency:o,amount:s}of i)a[e(o)]={usage_tiers:[{to:n[0].to,amount:s}]};return a}}}))(zh),{itemToFeature:T1}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{shouldProrate:R1}=((e,t)=>({shouldProrate:r=>r?r===e.ProrateNextCycle||r===e.ProrateImmediately||r===t.ProrateImmediately||r===t.ProrateNextCycle:!0}))(ri,na),{getBillingType:k1}=((e,t,n,r)=>({getBillingType:a=>{if(a.type===e.Fixed&&a.interval===t.OneOff)return n.OneOff;if(a.type===e.Fixed)return n.FixedCycle;let o=a;return o.bill_when===r.InAdvance||o.bill_when===r.StartOfPeriod?n.UsageInAdvance:o.bill_when===r.EndOfPeriod&&o.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Jr,Rn,Xr,ta),{stripeResourceFields:j1}={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:N1}={PREVIEW_STRIPE_PRICE_ID_PREFIX:"price_PREVIEW_"},{PREVIEW_STRIPE_PRODUCT_ID_PREFIX:D1}={PREVIEW_STRIPE_PRODUCT_ID_PREFIX:"prod_PREVIEW_"},{normalizeOptionalId:U1}={normalizeOptionalId:t=>t||null},{stripeProductOnlyFields:F1}={stripeProductOnlyFields:["stripe_product_id","stripe_meter_id"]},{copyField:M1}=(e=>({copyField:({fromConfig:n,toConfig:r,field:i})=>!e(r[i])||e(n[i])?!1:(r[i]=n[i],!0)}))(Jt),{stripeResourceFields:L1}={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:B1}={handleCustomProductItems:({newPrices:t,newEnts:n,updatedPrices:r,updatedEnts:i,samePrices:a,sameEnts:o,features:s})=>({prices:[...t,...r,...a],entitlements:[...n,...i,...o].map(c=>({...c,feature:s.find(u=>u.id===c.feature_id)})),customPrices:[...t,...r],customEnts:[...n,...i],features:s})},{validateLicenseBillingMode:q1}=((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})}}))(Dt,Vt),{PlanItemMatchPrecision:V1}=(()=>{var e;return(function(t){t.FeatureBillingMethodCadence="feature_billing_method_cadence",t.FeatureCadence="feature_cadence"})(e||(e={})),{PlanItemMatchPrecision:e}})(),{catalogPlanItemIdentity:$1}={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:G1}={applyPrice:(t,n)=>n===void 0?t:n===null?null:{...n}},{planItemMatchesFilter:H1}={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:K1}={isFreeNonResetEntitlement:t=>t.price==null&&t.reset==null},{toApiPlanItemPrice:W1}={toApiPlanItemPrice:t=>t?{...t,billing_units:t.billing_units??1,max_purchase:t.max_purchase??null}:null},{toApiPlanItemRollover:Q1}={toApiPlanItemRollover:t=>{if(t)return{...t,max:t.max??null}}},{applyFreeTrial:Z1}={applyFreeTrial:(t,n)=>{if(n===void 0)return t;if(n!==null)return{...n}}},{applyLicenseUpsert:z1}={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:eg}=(()=>{var e;return(function(t){t.Identity="identity",t.IdentityAndIncluded="identity_and_included"})(e||(e={})),{PlanItemFilterPrecision:e}})(),{additionalCurrenciesCompatible:iu}={additionalCurrenciesCompatible:(t,n)=>(t??[]).every(r=>{let i=(n??[]).find(a=>a.currency.toLowerCase()===r.currency.toLowerCase());return!i||(r.amount??null)===(i.amount??null)&&(r.flat_amount??null)===(i.flat_amount??null)})},{toBasePriceParams:Y1}={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:J1}=(e=>({tiersEqual:(n,r)=>!n?.length&&!r?.length?!0:!n||!r||n.length!==r.length?!1:n.every((i,a)=>{let o=r[a];return i.to===o.to&&(i.amount??0)===(o.amount??0)&&(i.flat_amount??null)===(o.flat_amount??null)&&e(i.additional_currencies,o.additional_currencies)})}))(iu),{rolloversEqual:X1}={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:eP}={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:tP}=(e=>({creditSchemaFingerprint:n=>e(Object.fromEntries((n??[]).map(r=>[r.metered_feature_id,{...r,billing_units:r.billing_units??1}])))}))(ru),{toCreatePlanItemParams:nP}={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:rP}=(e=>({buildRemoveFilter:({item:n,filterPrecision:r})=>{let i={feature_id:n.feature_id};n.price?.billing_method!==void 0&&(i.billing_method=n.price.billing_method);let a=n.price?.interval??n.reset?.interval;a!==void 0&&(i.interval=a);let o=n.price?.interval_count??n.reset?.interval_count;return a!==void 0&&(i.interval_count=o??1),r===e.IdentityAndIncluded&&typeof n.included=="number"&&n.unlimited!==!0&&(n.reset!=null||n.price!=null)&&(i.included=n.included),i}}))(eg),{FreeTrialDuration:iP}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{arraysEqual:aP}={arraysEqual:({left:t,right:n,equals:r})=>{if(!t?.length&&!n?.length)return!0;if(!t||!n||t.length!==n.length)return!1;let i=[...n];return t.every(a=>{let o=i.findIndex(s=>r(a,s));return o===-1?!1:(i.splice(o,1),!0)})}},{normalizeIntervalCount:oP}={normalizeIntervalCount:({interval:t,intervalCount:n})=>t?n??1:n??""},{hasLicenseCustomize:tg}={hasLicenseCustomize:t=>t!=null&&(t.price!==void 0||t.add_items!==void 0||t.remove_items!==void 0)},{byLicensePlanId:sP}={byLicensePlanId:(t,n)=>t.license_plan_id.localeCompare(n.license_plan_id)},{variantSettingKeys:cP}={variantSettingKeys:["name","description","group","add_on","config","billing_controls","metadata"]},{valuesEqual:uP}={valuesEqual:(t,n)=>JSON.stringify(t)===JSON.stringify(n)},{omitVariantOwnedSettings:W4}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:lP}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(Jt),{isPriceItem:jo}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(vr,Jt),{isDefaultTrialV2:Q4}=(e=>({isDefaultTrialV2:({freeTrial:n,items:r,isDefault:i})=>n?n.card_required===!1&&i&&!e({items:r}):!1}))(lP),{variantSettingsFields:dP}={variantSettingsFields:["description","group","is_add_on","is_default","config","billing_controls","metadata"]},{sortDeep:ng}=(()=>{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:mP}={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:pP}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:fP}={licenseParentTargetKey:({planId:t,version:n})=>`${t}@${n}`},{STRIPE_ZERO_DECIMAL_CURRENCIES:rg}={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:hP}={STRIPE_THREE_DECIMAL_CURRENCIES:new Set(["bhd","jod","kwd","omr","tnd"])},{currencyInputDecimals:ig}=(e=>({currencyInputDecimals:n=>e.has((n??"usd").toLowerCase())?0:2}))(rg),{entIntervalToValue:gP}=((e,t)=>({entIntervalToValue:(r,i)=>{if(!r)return new e(1e7);let o={[t.Minute]:1,[t.Hour]:60,[t.Day]:1440,[t.Week]:1440*7,[t.Month]:1440*30,[t.Quarter]:1440*90,[t.SemiAnnual]:1440*180,[t.Year]:1440*365,[t.Lifetime]:1e9}[r];return new e(o).mul(i??1)}}))(mn,Yr),{intervalToValue:bP}=(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)}))(Rn),{normalizeIncludedUsage:ag}={normalizeIncludedUsage:t=>t??0},{rolloversAreSame:og}={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:_P}=((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)}))(ri,na),{itemToExplicitAllocatedBillingBehavior:yP}=((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)}))(vr,Xn),{additionalCurrenciesAreSame:au}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let a=(c,u)=>c.currency.localeCompare(u.currency),o=[...r].sort(a),s=[...i].sort(a);return o.every((c,u)=>c.currency===s[u].currency&&(c.amount??null)===(s[u].amount??null)&&(c.flat_amount??null)===(s[u].flat_amount??null))}},{itemPricingTiers:SP}={itemPricingTiers:t=>t.tiers?.length?t.tiers:t.price!=null?[{amount:t.price,to:"inf"}]:null},{priceItemsAreSame:xP}=((e,t,n)=>({priceItemsAreSame:({item1:i,item2:a,logDifferences:o=!1})=>{let s=i.price===a.price&&e({item:i})==e({item:a})&&t({item:i})==t({item:a})&&n(i.additional_currencies,a.additional_currencies);return!s&&o&&console.log(`Price items different: ${i.price}`),s}}))(er,ii,au),{calculateProrationAmount:vP}=(e=>({calculateProrationAmount:({periodEnd:n,periodStart:r,now:i,amount:a,allowNegative:o=!1})=>{let s=new e(n).minus(i),c=new e(n).minus(r),u=s.div(c).mul(a);return u.lte(0)&&!o?0:u.toNumber()}}))(mn),{getResetUsage:IP}=((e,t,n,r)=>({getResetUsage:({item:a,feature:o})=>{if(a.feature_id)return e(a.reset_usage_when_enabled)&&(t(a)||n(a))&&o?o?.config?.usage_type===r.Single:a.reset_usage_when_enabled}}))(Jt,ko,ai,Jn),{compareDetails:AP}={compareDetails:({newProductV2:t,curProductV2:n})=>{let r={is_add_on:{condition:t?.is_add_on===n?.is_add_on,message:`Is add-on different: ${t?.is_add_on} !== ${n?.is_add_on}`},is_default:{condition:t?.is_default===n?.is_default,message:`Is default different: ${t?.is_default} !== ${n?.is_default}`},archived:{condition:t?.archived===n?.archived,message:`Archived different: ${t?.archived} !== ${n?.archived}`},group:{condition:t?.group==n?.group,message:`Group different: ${t?.group} !== ${n?.group}`},name:{condition:t?.name==n?.name,message:`Name different: ${t?.name} !== ${n?.name}`},id:{condition:t?.id===n?.id,message:`ID different: ${t?.id} !== ${n?.id}`}};return Object.values(r).every(a=>a.condition)}},{compareConfig:PP}={compareConfig:({newConfig:t,curConfig:n})=>{let r={ignore_past_due:{condition:!!t?.ignore_past_due==!!n?.ignore_past_due,message:`Ignore past due different: ${t?.ignore_past_due} !== ${n?.ignore_past_due}`}};return Object.values(r).every(a=>a.condition)}},{normalizeBillingControlsForCompare:CP}=(e=>({normalizeBillingControlsForCompare:n=>{if(!n)return;let r=n.spend_limits?.map(a=>{if(a.skip_overage_billing===!0)return a;let{skip_overage_billing:o,...s}=a;return s}),i=Object.fromEntries(e.flatMap(a=>{let o=a==="spend_limits"?r:n[a];return o==null||o.length===0?[]:[[a,o]]}));return Object.keys(i).length>0?i:void 0}}))(Co),{sortControls:wP}={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:OP}={compareMetadata:({newMetadata:t,curMetadata:n})=>{let r=i=>JSON.stringify(i??{},(a,o)=>o&&typeof o=="object"&&!Array.isArray(o)?Object.keys(o).sort().reduce((s,c)=>(s[c]=o[c],s),{}):o);return r(t)===r(n)}},{freeTrialsAreSame:EP}={freeTrialsAreSame:({ft1:t,ft2:n})=>{if(!t&&!n)return!0;if(!t||!n)return!1;let r={length:{condition:t.length!==n.length,message:`Length different: ${t.length} !== ${n.length}`},unique_fingerprint:{condition:t.unique_fingerprint!==n.unique_fingerprint,message:`Unique fingerprint different: ${t.unique_fingerprint} !== ${n.unique_fingerprint}`},duration:{condition:t.duration!==n.duration,message:`Duration different: ${t.duration} !== ${n.duration}`},card_required:{condition:t.card_required!==n.card_required,message:`Card required different: ${t.card_required} !== ${n.card_required}`},on_end:{condition:(t.on_end??"bill")!==(n.on_end??"bill"),message:`On end different: ${t.on_end??"bill"} !== ${n.on_end??"bill"}`}};return!Object.values(r).some(a=>a.condition)}},{prodOptionsAreSame:TP}={prodOptionsAreSame:({curProduct:t,newProduct:n})=>t.is_default===n.is_default&&t.is_add_on===n.is_add_on},{PurchaseLimitIntervalEnum:RP}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(Ae,WA),{entToItemInterval:sg}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))(Yr),{billingToItemInterval:cg}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(Rn),{isContUseFeature:ug}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(Jn),{getBillingType:ou}=((e,t,n,r)=>({getBillingType:a=>{if(a.type===e.Fixed&&a.interval===t.OneOff)return n.OneOff;if(a.type===e.Fixed)return n.FixedCycle;let o=a;return o.bill_when===r.InAdvance||o.bill_when===r.StartOfPeriod?n.UsageInAdvance:o.bill_when===r.EndOfPeriod&&o.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Jr,Rn,Xr,ta),{isAllocatedPrice:lg}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(ou,Xr),{priceToEnt:su}=(e=>{function t({price:n,entitlements:r,errorOnNotFound:i}){let a=r.filter(s=>s.id===n.entitlement_id),o=a.find(s=>s.internal_product_id===n.internal_product_id)??a[0];if(!o&&i)throw new e({message:`Entitlement not found for price ${n.id}`});return o}return{priceToEnt:t}})(zA),{isBooleanFeatureItem:dg}=((e,t)=>({isBooleanFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)&&t(r.interval)&&t(r.included_usage)}))(ni,ti),{constructBooleanFeature:kP}=((e,t,n)=>({constructBooleanFeature:({featureId:i,orgId:a,env:o,name:s})=>({internal_id:e("fe"),org_id:a,env:o,created_at:Date.now(),id:i,name:s||t(i),type:n.Boolean,config:null,archived:!1,event_names:[],model_markups:null})}))(zr,Vh,Ct),{constructMeteredFeature:jP}=((e,t,n,r)=>({constructMeteredFeature:({featureId:a,name:o,orgId:s,env:c,usageType:u,eventNames:l=[]})=>({internal_id:e("fe"),org_id:s,env:c,created_at:Date.now(),id:a,name:o||t(a),type:n.Metered,config:{filters:[{property:"event_name",operator:"eq",value:[]}],aggregate:{type:r.Sum,property:"value"},usage_type:u},archived:!1,event_names:l,model_markups:null})}))(zr,Vh,Ct,JA),{ApiFeatureV0Schema:NP}=((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."})})}))(Ae,e1),{CURRENCY_CODES:DP}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))($h,t1,n1),{RolloverConfigSchema:UP}=((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()})}))(Ae,Jc),{EntitlementExpirySchema:FP}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(Ae,r1),{CreditDimensionNameSchema:MP}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ae,i1,a1),{CreditDimensionBaseSchema:LP}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(Ae,Kh),{graduatedCreditRateShape:mg}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(Ae,o1),{ProviderMarkupsSchema:BP}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ae,Qh),{isAnyCreditSystem:qP}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(Ct,eu),{findCreditTierViolations:VP}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(u1),{findAmbiguousCreditDimensions:$P}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),a=[];for(let[o,[s,c]]of i.entries())for(let[u,l]of i.slice(o+1))e(c,l)&&t(c.match,l.match)&&a.push({names:[s,u],example:{...c.match,...l.match}});return a}}))(l1,Zh),{validateMultipliersKeepRatesNonNegative:GP}=((e,t)=>({validateMultipliersKeepRatesNonNegative:({schemaItem:r,invalidCreditSystem:i})=>{let a=Object.values(r.multipliers??{}),o=[r,...Object.values(r.dimensions??{})],s=Math.min(...o.map(e));t({multipliers:a,cheapestRate:s}).lt(0)&&i(`Multipliers on ${r.metered_feature_id} can take a rate below zero.`)}}))(p1,f1),{buildFixedPriceCurrencies:HP}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:a}of n)r[e(i)]={amount:a};return r}}))(zh),{PriceCurrencyConfigSchema:pg}=((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()})}))(Ae,nu),{baseCurrenciesAreCompatible:KP}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:a})=>(n??null)===(r??null)||e(i)!==e(a)}))(y1),{tiersAreSame:fg}=(e=>({tiersAreSame:(n,r)=>{if(n.length!==r.length)return!1;let i=e(n),a=e(r);return i.every((o,s)=>{let c=a[s];return o.amount===c?.amount&&o.flat_amount===c.flat_amount&&o.to===c.to})}}))(S1),{UsagePriceConfigSchema:WP}=((e,t,n,r,i,a)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(a).optional()})}))(Ae,ta,nu,Rn,pg,Xn),{toFeature:QP}=((e,t,n,r,i,a,o)=>({toFeature:({item:c,orgId:u,internalFeatureId:l,internalProductId:d,isCustom:m,newVersion:g,feature:p,curEnt:h})=>{let x=p?.type===e.Boolean,I=t({item:c,feature:p}),v={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:x?null:c.included_usage===r?i.Unlimited:i.Fixed,interval:x?null:a({item:c}),interval_count:o({item:c}),carry_from_previous:!I,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)&&(v={...v,id:n("ent"),created_at:Date.now()}),{price:null,ent:v}}}))(Ct,Yh,zr,ea,wo,To,Ro),{creditDimensionRulesEqual:ZP}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(ru),{markupRecordsAreSame:zP}=(e=>({markupRecordsAreSame:(n,r)=>[...new Set([...Object.keys(n??{}),...Object.keys(r??{})])].every(i=>e.every(a=>(n?.[i]?.[a]??null)===(r?.[i]?.[a]??null)))}))(C1),{itemToUsageType:YP}=((e,t,n)=>({itemToUsageType:({item:i,features:a})=>{let o=e({item:i,features:a});return!o||!o.config?null:o.type===t.Boolean?n.Static:o.type===t.CreditSystem?n.SingleUse:o.config.usage_type}}))(Xh,Ct,kn),{itemToUsageType:JP}=((e,t,n)=>({itemToUsageType:({item:i,features:a})=>{let o=e({item:i,features:a});return o?o.type==t.Boolean?n.Static:o.type==t.CreditSystem?n.SingleUse:o.config.usage_type:null}}))(T1,Ct,kn),{isPreviewStripeId:XP}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(N1,D1),{findPairedEntitlement:eC}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(su),{isConsumablePrice:tC}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(ou,Xr),{validateLicenseLink:Z4}=((e,t,n)=>({validateLicenseLink:({parentProduct:i,licenseProduct:a,prepaidOnly:o,licensePlanId:s})=>{if(o!==void 0&&e({prepaidOnly:o}),s&&a.archived)throw new t({message:`License plan ${s} is archived and cannot be linked.`,code:n.InvalidRequest,statusCode:400});if(a.base_internal_product_id)throw new t({message:`A variant cannot be used as a plan license (${s??a.id}).`,code:n.InvalidRequest});if(i&&a.id===i.id)throw new t({message:`A plan cannot be linked as a license to itself (${s??a.id}).`,code:n.InvalidRequest,statusCode:400})}}))(q1,Dt,Vt),{evaluateCatalogItemIdentity:nC}=(e=>({evaluateCatalogItemIdentity:({item:n,recipe:r=e})=>{let i=[];for(let a of r.components){let o;for(let c of a.paths){o=n;for(let u of c.split("."))o=o!==null&&typeof o=="object"?o[u]:void 0;if(o!=null)break}let s=a.defaultWhen&&i[a.defaultWhen.component]?a.defaultWhen.value:a.default;if(o!=null&&typeof o!="string"&&typeof o!="number")throw new Error("Catalog identity components must be strings or numbers");i.push(o??s)}return i}}))($1),{removeItems:rC}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(a=>e({item:i,filter:a})))}))(H1),{toApiPlanItem:iC}=((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)})}))(W1,Q1),{applyLicenses:aC}=(e=>({applyLicenses:({base:n,diff:r})=>{if(r.upsert_licenses===void 0&&r.remove_licenses===void 0)return;let i=new Set((r.remove_licenses??[]).map(s=>s.license_plan_id)),a=new Map((r.upsert_licenses??[]).map(s=>[s.license_plan_id,s])),o=[];for(let s of n.licenses??[]){if(i.has(s.license_plan_id))continue;let c=a.get(s.license_plan_id);if(c){o.push(e({existing:s,upsert:c})),a.delete(s.license_plan_id);continue}o.push(s)}for(let s of r.upsert_licenses??[])a.has(s.license_plan_id)&&o.push(e({upsert:s}));return o}}))(z1),{pricesEqual:hg}=(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)}))(iu),{itemPricesEqual:oC}=((e,t,n)=>({itemPricesEqual:(i,a)=>{if(i==null&&a==null)return!0;if(i==null||a==null)return!1;let o=i.tiers?.length?i.tier_behavior??e.Graduated:null,s=a.tiers?.length?a.tier_behavior??e.Graduated:null;return(i.amount??null)===(a.amount??null)&&t(i.additional_currencies,a.additional_currencies)&&n(i.tiers,a.tiers)&&o===s&&i.interval===a.interval&&(i.interval_count??1)===(a.interval_count??1)&&(i.billing_units??1)===(a.billing_units??1)&&i.billing_method===a.billing_method&&(i.max_purchase??null)===(a.max_purchase??null)}}))(Oo,iu,J1),{featureOverridesEqual:sC}=((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??{})}))(tP,ru),{freeTrialsEqual:cC}=(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")}))(iP),{planItemFiltersEqual:uC}=(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)}))(oP),{toUpsertLicense:lC}=(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}:{}})}))(tg),{getVariantSettingsPatch:z4}=((e,t)=>({getVariantSettingsPatch:({from:r,to:i})=>{let a={};for(let o of e)t(r[o],i[o])||(a[o]=i[o]);return a}}))(cP,uP),{isOneOffProductV2:Y4}=((e,t,n,r)=>({isOneOffProductV2:({items:a})=>{let o=a.filter(s=>e(s)||t(s));return o.length>0&&o.every(s=>n({item:s})===r.OneOff)}}))(jo,ai,er,Rn),{canonicalizeBillingControls:dC}=(e=>({canonicalizeBillingControls:n=>{let r=n??{},i={};for(let a of Object.keys(r)){let o=r[a];Array.isArray(o)&&o.length===0||(i[a]=Array.isArray(o)?[...o].sort((s,c)=>String(s?.feature_id??"").localeCompare(String(c?.feature_id??""))):o)}return JSON.stringify(e(i))}}))(ng),{ProductConfigSchema:mC}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(Ae,mP),{shouldApplyVariantUpdates:J4}=(e=>({shouldApplyVariantUpdates:({oldBase:n,latestBase:r,propagateToVariants:i,variantUpdates:a,updates:o})=>i.length>0||a.length>0||n.internal_id!==r.internal_id?!0:e.some(s=>o[s]!==void 0)}))(pP),{resolveLicenseParentTargets:X4}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:a,childPlanId:o})=>{let s=new Map(i.map(l=>[e({planId:l.parent.id,version:l.parent.version}),l])),c=new Set,u=[];for(let l of a){let d=e({planId:l.plan_id,version:l.version});if(c.has(d))throw new t({message:`Parent plan target ${d} was selected more than once.`,code:n.InvalidPropagationTarget,statusCode:400});let m=s.get(d);if(!m)throw new t({message:`Plan ${l.plan_id} v${l.version} does not offer ${o} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),u.push(m)}return u}}))(fP,Dt,Vt),{stripeMinorUnitFactor:No}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(rg,hP),{entIntervalsSame:pC}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),a=e(r.interval,r.intervalCount);return i.eq(a)}}))(gP),{intervalsDifferent:fC}=((e,t)=>({intervalsDifferent:({intervalA:r,intervalB:i})=>{if(e(r)&&e(i))return!1;if(e(r)||e(i))return!0;let a=t(r.interval,r.intervalCount),o=t(i.interval,i.intervalCount);return a!==o}}))(Jt,bP),{allocatedBillingBehaviorAreSame:hC}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),a=e(r);return i===a}}))(yP),{tiersAreSame:gC}=(e=>({tiersAreSame:(n,r)=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every((i,a)=>i.amount===r[a].amount&&i.to===r[a].to&&(i.flat_amount??null)===(r[a].flat_amount??null)&&e(i.additional_currencies,r[a].additional_currencies))}))(au),{itemToPriceOrTiers:bC}=(e=>({itemToPriceOrTiers:({item:n,proration:r,now:i})=>{if(i=i||Date.now(),n.price)return{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.price}):n.price,tiers:void 0};if(n.tiers)return n.tiers.length>1?{price:void 0,tiers:n.tiers.map(a=>({...a,amount:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:a.amount}):a.amount}))}:{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.tiers[0].amount}):n.tiers[0].amount,tiers:void 0}}}))(vP),{normalizeBillingControls:_C}=((e,t,n)=>({normalizeBillingControls:i=>{let a=e(i);return JSON.stringify(t.flatMap(o=>{let s=a?.[o];return s?.length?[[o,n(s)]]:[]}))}}))(CP,Co,wP),{AutoTopupPurchaseLimitSchema:yC}=((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."})})}))(Ae,RP),{toFeatureItem:SC}=((e,t,n,r)=>({toFeatureItem:({ent:a})=>{if(a.feature.type===e.Boolean)return{feature_id:a.feature.id,entity_feature_id:a.entity_feature_id,entitlement_id:a.id};let o=a.rollover||a.feature_override?{rollover:a.rollover??void 0,feature_override:a.feature_override??void 0}:void 0;return{feature_id:a.feature.id,included_usage:a.allowance_type===t.Unlimited?n:a.allowance,interval:r({entInterval:a.interval}),interval_count:a.interval_count??1,entity_feature_id:a.entity_feature_id,pooled:a.pooled??!1,reset_usage_when_enabled:!a.carry_from_previous,config:o,entitlement_id:a.id,created_at:a.created_at}}}))(Ct,wo,ea,sg),{toPriceItem:xC}=((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}}}))(cg,QA),{isPayPerUsePrice:gg}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(ou,Xr),{createFeaturesFromItems:vC}=((e,t,n,r,i,a,o,s,c,u)=>({createFeaturesFromItems:({items:d,curFeatures:m,orgId:g,env:p})=>{let h=[];for(let x of d){if(!x.feature_id)continue;let I=m.find(v=>v.id===x.feature_id);if(I){if(e(x.feature_type))continue;if(x.feature_type===t.Static){if(x.feature_type===t.Static&&I.type!==n.Boolean)throw new r({message:`Feature ${x.feature_id} already exists but is not a static feature`,code:i.InvalidRequest,statusCode:400})}else if(x.feature_type!==I.config?.usage_type)throw new r({message:`Feature ${x.feature_id} already exists but is not a ${x.feature_type} feature`,code:i.InvalidRequest,statusCode:400});continue}if(a(x.feature_id),o(x)){let v=s({featureId:x.feature_id,orgId:g,env:p});h.push(v)}else{if(!x.feature_type)throw new r({message:`Feature type is required for ${x.feature_id}. Either 'continuous_use' or 'single_use'`,code:i.InvalidRequest,statusCode:400});let v=c({featureId:x.feature_id,orgId:g,env:p,usageType:x.feature_type===t.ContinuousUse?u.Continuous:u.Single});h.push(v)}}return{allFeatures:[...m,...h],newFeatures:h}}}))(ti,kn,Ct,Dt,Vt,YA,dg,kP,jP,Jn),{SUPPORTED_SET:IC}=(e=>({SUPPORTED_SET:new Set(e)}))(DP),{CreditDimensionSchema:AC}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(Ae,LP,Wh,mg),{FeatureMarkupsOverrideSchema:PC}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(Ae,BP,c1),{validateCreditRate:bg}=(e=>({validateCreditRate:({rate:n,invalidCreditSystem:r})=>{if(n.tier_behavior==="graduated"){(!Array.isArray(n.tiers)||n.tiers.length===0)&&r("Graduated credit schemas require at least one tier.");let a=n.tiers??[];for(let s of a){let c=Number(s.credit_amount);(!Number.isFinite(c)||c<0)&&r("Tier credit costs must be zero or greater."),s.credit_amount=c,s.to!=="inf"&&(s.to=Number(s.to))}let[o]=e(a.map(s=>s.to));o&&r(o.message);return}let i=Number(n.credit_amount);(!Number.isFinite(i)||i<0)&&r("Credit cost must be zero or greater."),n.credit_amount=i}}))(VP),{validateDimensionsAreSeparable:CC}=((e,t)=>({validateDimensionsAreSeparable:({dimensions:r,invalidCreditSystem:i})=>{let[a]=e(r);if(!a)return;let[o,s]=a.names;i(`Dimensions "${o}" and "${s}" can both match the same event (${t(a.example)}). Give one more match keys or a priority.`)}}))($P,d1),{validateCreditMultipliers:wC}=((e,t)=>({validateCreditMultipliers:({schemaItem:r,invalidCreditSystem:i})=>{for(let[a,o]of Object.entries(r.multipliers??{}))e({name:a,multiplier:o,invalidCreditSystem:i});t({schemaItem:r,invalidCreditSystem:i})}}))(m1,GP),{FixedPriceConfigSchema:OC}=((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})}))(Ae,Rn,pg,nu,_1),{currenciesAreCompatible:EC}=(e=>({currenciesAreCompatible:(n,r)=>{let i=n??{},a=r??{};for(let o of Object.keys(i)){let s=a[o];if(!s)continue;let c=i[o];if((c?.amount??null)!==(s.amount??null)||!e(c?.usage_tiers??[],s.usage_tiers??[]))return!1}return!0}}))(fg),{creditSchemaItemsAreSame:TC}=(e=>({creditSchemaItemsAreSame:({left:n,right:r})=>(n.feature_amount??1)==(r.feature_amount??1)&&e({left:n,right:r})&&n.credit_amount==r.credit_amount&&(n.tier_behavior??null)===(r.tier_behavior??null)&&(n.tiers??[]).length===(r.tiers??[]).length&&(n.tiers??[]).every((i,a)=>i.to===r.tiers?.[a]?.to&&i.credit_amount==r.tiers?.[a]?.credit_amount)}))(ZP),{markupOverridesAreSame:RC}=(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)}))(zP),{resolveAllocatedBillingBehavior:kC}=((e,t,n,r)=>({resolveAllocatedBillingBehavior:({item:a,curPrice:o})=>{if(e(a.config?.allocated_billing_behavior))return a.config.allocated_billing_behavior;if(e(a.config?.on_increase)||e(a.config?.on_decrease))return t.Prorated;if(o&&n({price:o})){let c=o.config;return e(c.allocated_billing_behavior)?c.allocated_billing_behavior:r(o)?t.Prorated:t.Arrear}return t.Arrear}}))(vr,Xn,gg,lg),{itemCanBeProrated:jC}=((e,t,n)=>({itemCanBeProrated:({item:i,features:a})=>{let o=e({item:i,features:a});return o===t.SingleUse&&i.usage_model===n.Prepaid?!0:o===t.ContinuousUse}}))(JP,kn,ei),{priceHasPreviewStripeId:NC}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(a=>t({stripeId:i[a]}))}}))(j1,XP),{buildPlanItemKey:DC}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let a=t({item:r});return i===e.FeatureCadence&&a.splice(1,1),a.join("|")}}))(V1,nC),{itemsEqual:_g}=((e,t,n,r)=>({itemsEqual:(a,o)=>a.feature_id===o.feature_id&&(a.entity_feature_id??null)===(o.entity_feature_id??null)&&(a.pooled??!1)===(o.pooled??!1)&&(a.included??0)===(o.included??0)&&(a.unlimited??!1)===(o.unlimited??!1)&&(a.reset?.interval??null)===(o.reset?.interval??null)&&(a.reset?.interval_count??1)===(o.reset?.interval_count??1)&&e(a.price,o.price)&&t(a.rollover,o.rollover)&&n(a.proration,o.proration)&&r(a.feature_override,o.feature_override)}))(oC,X1,eP,sC),{licenseCustomizesAreSame:UC}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:a,right:o})=>{let s=a??{},c=o??{},u={price:!e(s.price,c.price),addItems:!t({left:s.add_items,right:c.add_items,equals:n}),removeItems:!t({left:s.remove_items,right:c.remove_items,equals:r})};return!Object.values(u).some(Boolean)}}))(hg,aP,_g,uC),{normalizeVariantSettingValue:FC}=((e,t,n)=>({normalizeVariantSettingValue:({field:i,value:a})=>{if(i==="group")return a||"";if(i==="description")return a||null;if(i==="billing_controls")return e(a);if(i==="config"){let o=t.safeParse(a??{});return JSON.stringify(n(o.success?o.data:a??{}))}return i==="metadata"?JSON.stringify(n(a??{})):a}}))(dC,mC,ng),{intervalsSame:MC}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(fC),{sanitizeItems:LC}=((e,t,n,r)=>({sanitizeItems:({items:a,features:o})=>a.map(s=>{let c=s.tiers?.length===1&&s.tiers[0].additional_currencies?.length?{price:void 0,tiers:s.tiers}:e({item:s}),u={...s,reset_usage_when_enabled:t({item:s,feature:o.find(l=>l.id===s.feature_id)}),...c};return u.config||(u.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),u})}))(bC,IP,ri,na),{compareBillingControls:BC}=(e=>({compareBillingControls:({newBillingControls:n,curBillingControls:r})=>e(n)===e(r)}))(_C),{AutoTopupSchema:qC}=((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."})})}))(Ae,yC),{toFeaturePriceItem:VC}=((e,t,n,r,i,a,o,s,c,u,l)=>({toFeaturePriceItem:({ent:m,price:g})=>{let p=g.config,h=e(p.currencies,p.usage_tiers.length),x=p.usage_tiers.map((j,T)=>({amount:j.amount,to:j.to===-1?t:j.to,flat_amount:j.flat_amount,...h?.[T]?.length?{additional_currencies:h[T]}:{}})),I={};return g.proration_config&&(I={...g.proration_config}),n({feature:m.feature})&&r({price:g})&&(I.allocated_billing_behavior=p.allocated_billing_behavior??(i(g)?a.Prorated:a.Arrear)),m.rollover&&(I.rollover=m.rollover),m.expiry_duration&&m.expiry_length!=null&&(I.expiry={duration:m.expiry_duration,length:m.expiry_length}),m.feature_override&&(I.feature_override=m.feature_override),p.threshold_billing&&(I.threshold_billing=p.threshold_billing),{feature_id:m.feature.id,feature_type:m.feature.config?.usage_type||o.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:x,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(I).length>0?I:void 0,usage_limit:m.usage_limit}}}))(ZA,zc,ug,gg,lg,Xn,kn,sg,cg,ta,ei),{isValidCurrencyCode:cu}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(IC),{CreditSchemaItemBaseSchema:yg}=((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()})}))(Ae,MP,AC,s1),{GraduatedCreditSchemaItemSchema:$C}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(yg,mg),{validateCreditDimensionRules:GC}=((e,t,n)=>({validateCreditDimensionRules:({schemaItem:i,invalidCreditSystem:a})=>{let o=i.dimensions??{};for(let[s,c]of Object.entries(o))c.priority!==void 0&&!Number.isInteger(c.priority)&&a(`Dimension "${s}" priority must be an integer.`),e({rate:c,invalidCreditSystem:a});t({dimensions:o,invalidCreditSystem:a}),n({schemaItem:i,invalidCreditSystem:a})}}))(bg,CC,wC),{pricesAreSame:Do}=((e,t,n,r,i,a,o,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 T=t.parse(m),P=t.parse(g),_e={amount:T.amount!==P.amount,interval:T.interval!==P.interval,intervalCount:(T.interval_count??1)!==(P.interval_count??1),baseCurrency:!n({base1:T.base_currency,base2:P.base_currency,currencies1:T.currencies,currencies2:P.currencies}),currencies:!r(T.currencies,P.currencies)};return!Object.values(_e).some(Boolean)}let p=i.parse(m),h=i.parse(g),x={shouldProrate:(p.should_prorate??!1)!==(h.should_prorate??!1),allocatedBillingBehavior:a(p)!==a(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:!o(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)},I=p.usage_tiers.length<=1&&h.usage_tiers.length<=1,v={onIncrease:u.proration_config?.on_increase!=l.proration_config?.on_increase,onDecrease:u.proration_config?.on_decrease!=l.proration_config?.on_decrease,tierBehavior:!I&&(u.tier_behavior??s.Graduated)!==(l.tier_behavior??s.Graduated)},j=Object.values(x).some(Boolean)||Object.values(v).some(Boolean);return j&&d&&console.log("Prices are different",{configDiffs:x,prorationDiffs:v}),!j}}))(Jr,OC,KP,EC,WP,x1,fg,Oo),{creditSchemasAreSame:HC}=(e=>({creditSchemasAreSame:({schema1:n,schema2:r})=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every(i=>{let a=r.find(o=>o.metered_feature_id===i.metered_feature_id);return a?e({left:i,right:a}):!1})}))(TC),{itemToAllocatedBillingBehavior:KC}=((e,t,n,r,i,a,o,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===a.Arrear){if(o(l.config?.on_increase)||o(l.config?.on_decrease))throw new s({message:`on_increase / on_decrease are not supported for allocated arrear billing (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400});if(o(l.config?.rollover))throw new s({message:`rollover is not supported for allocated arrear billing because the balance never resets (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400})}return h}}))(YP,kn,ai,ei,kC,Xn,vr,Dt,O1),{composeMatchKey:ra}=(e=>({composeMatchKey:n=>e({item:n})}))(DC),{applyItems:WC}=((e,t,n,r)=>({applyItems:(a,o)=>{let s=[...a];if(o.remove_items&&(s=e(s,o.remove_items)),o.add_items){let c=new Set;for(let u of s)t(u)&&c.add(n(u));for(let u of o.add_items){let l=n(u);t(u)&&c.has(l)||(s.push(r(u)),t(u)&&c.add(l))}}return s}}))(rC,K1,ra,iC),{dedupeItemsByMatchKey:QC}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(ra),{planLicensesAreSame:ZC}=(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)}}))(UC),{dedupeItemsByMatchKey:zC}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(ra),{validateVariantSettingsUpdate:eL}=((e,t,n,r)=>({validateVariantSettingsUpdate:({allowVariantSettingsUpdate:a,fullProduct:o,currentProduct:s,updates:c})=>{if(a||o.base_internal_product_id==null)return;let u=e.find(l=>c[l]===void 0?!1:t({field:l,value:c[l]})!==t({field:l,value:s[l]}));if(u)throw new n({message:`Cannot update ${u} directly on a variant plan.`,code:r.InvalidPropagationTarget,statusCode:400})}}))(dP,FC,Dt,Vt),{findSimilarItem:uu}=((e,t,n,r,i,a,o,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&&a({intervalA:{interval:o({item:m}),intervalCount:s({item:m})},intervalB:{interval:o({item:l}),intervalCount:s({item:l})}})&&l.usage_model==m.usage_model):c(l)?d.find(m=>c(m)&&m.price==l.price&&o({item:m})==o({item:l})&&s({item:m})==s({item:l})):null}))(ko,pC,To,Ro,ai,MC,er,ii,jo),{stripAutoTopupCountsForStorage:YC}=(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}))}))(qC),{toProductItem:Sg}=((e,t,n,r)=>({toProductItem:({ent:a,price:o})=>e(o)?t({ent:a}):e(a)?n({price:o}):r({ent:a,price:o})}))(Jt,SC,xC,VC),{CurrencyCodeSchema:xg}=((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')."})}))(Ae,cu),{AdditionalCurrencyPriceSchema:JC}=((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."})})}))(Ae,xg),{FlatCreditSchemaItemSchema:XC}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(yg,Wh),{validateCreditSystem:ew}=((e,t,n,r,i,a,o,s)=>({validateCreditSystem:(u,l=e.CreditSystem)=>{let d=Array.isArray(u?.schema)?u.schema:[],m=v=>{throw new t({message:v,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(v=>v.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:a.Single},x=h.default_markup;if(x!=null){let v=Number(x);if(Number.isNaN(v)||v<-100)throw new t({message:"Default markup must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});h.default_markup=v}let I=h.provider_markups;if(I!=null)for(let[v,j]of Object.entries(I)){let T=Number(j?.markup);if(!v||Number.isNaN(T)||T<-100)throw new t({message:"Provider markups must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});j.markup=T}for(let v of h.schema){if(v.feature_amount!==void 0){let j=Number(v.feature_amount);(!Number.isFinite(j)||j<=0)&&m("Billing units must be greater than zero."),v.feature_amount=j}o({rate:v,invalidCreditSystem:m}),s({schemaItem:v,invalidCreditSystem:m})}return h}}))(Ct,Dt,Vt,Yn,eu,Jn,bg,GC),{stripePriceIdForInitializedPrice:vg}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:a,newPrice:o})=>{if(!e(i)&&(!a||i!==t({price:a})||n(a,o)))return i}}))(Jt,b1,Do),{featureOverridesAreSame:lu}=((e,t)=>({featureOverridesAreSame:({override1:r,override2:i})=>e({schema1:r?.schema,schema2:i?.schema})&&t({markups1:r?.markups,markups2:i?.markups})}))(HC,RC),{applyDiff:Ig}=((e,t,n,r)=>({applyDiff:({base:a,diff:o})=>{let s={price:e(a.price,o.price),items:t(a.items,o),free_trial:n(a.free_trial,o.free_trial)},c=r({base:a,diff:o});return c===void 0?s:{...s,licenses:c}}}))(G1,WC,Z1,aC),{diffPlanLicenses:tw}=((e,t,n,r)=>({diffPlanLicenses:({from:a,to:o,includeAdds:s=!1,includeRemoves:c=!1})=>{let u=new Map((a??[]).map(g=>[g.license_plan_id,g])),l=new Map((o??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of l.values()){let 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)}:{}}}}))(ZC,lC,tg,sP),{applyDiffToVariantPlan:tL}=((e,t)=>({applyDiffToVariantPlan:({plan:r,diff:i,settingsPatch:a={}})=>{let o=e({base:r,diff:i});return{...r,...o,...a,items:t(o.items)}}}))(Ig,zC),{mapToProductItems:Ag}=((e,t,n,r)=>({mapToProductItems:({prices:a,entitlements:o,features:s})=>{let c=[];a??=[],o??=[];for(let u of o){let l=e({ent:u,prices:a}),d=t({ent:u,price:l});c.push(d)}for(let u of a)n({price:u,entitlements:o})||c.push(t({price:u}));for(let u of c)s.find(d=>d.id===u.feature_id)&&(u.feature_type=r({item:u,features:s}));return c}}))(Lh,Sg,su,Bh),{featureItemsAreSame:nw}=((e,t,n)=>({featureItemsAreSame:({item1:i,item2:a,logDifferences:o=!1})=>{let s={feature_id:{condition:i.feature_id===a.feature_id,message:`Feature ID different: ${i.feature_id} != ${a.feature_id}`},included_usage:{condition:e(i.included_usage)==e(a.included_usage),message:`Included usage different: ${i.included_usage} != ${a.included_usage}`},interval:{condition:i.interval==a.interval,message:`Interval different: ${i.interval} != ${a.interval}`},interval_count:{condition:(i.interval_count||1)==(a.interval_count||1),message:`Interval count different: ${i.interval_count} != ${a.interval_count}`},entity_feature_id:{condition:i.entity_feature_id==a.entity_feature_id,message:`Entity feature ID different: ${i.entity_feature_id} != ${a.entity_feature_id}`},pooled:{condition:(i.pooled??!1)===(a.pooled??!1),message:`Pooled different: ${i.pooled} != ${a.pooled}`},reset_usage_when_enabled:{condition:(i.reset_usage_when_enabled??!1)===(a.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${i.reset_usage_when_enabled} !== ${a.reset_usage_when_enabled}`},rollover_config:{condition:t({rollover1:i.config?.rollover||void 0,rollover2:a.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(i.config?.rollover)} !== ${JSON.stringify(a.config?.rollover)}`},feature_override:{condition:n({override1:i.config?.feature_override,override2:a.config?.feature_override}),message:`Feature override different: ${JSON.stringify(i.config?.feature_override)} !== ${JSON.stringify(a.config?.feature_override)}`},threshold_billing:{condition:(i.config?.threshold_billing?.threshold??null)===(a.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(i.config?.threshold_billing)} !== ${JSON.stringify(a.config?.threshold_billing)}`}},c=Object.values(s).every(u=>u.condition);return!c&&o&&console.log("Feature items different:",Object.values(s).filter(u=>!u.condition).map(u=>u.message)),c}}))(ag,og,lu),{featurePriceItemsAreSame:rw}=((e,t,n,r,i,a,o,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:a({item:d})==a({item:m}),message:`Billing interval different: ${a({item:d})} != ${a({item:m})}`},interval_count:{condition:o({item:d})==o({item:m}),message:`Billing interval count different: ${o({item:d})} != ${o({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}`}},x=Object.values(h).every(v=>v.condition)&&Object.values(p).every(v=>v.condition),I=Object.values(h).some(v=>!v.condition);return!x&&g&&console.log("Feature price items different:",Object.values(p).filter(v=>!v.condition).map(v=>v.message),Object.values(h).filter(v=>!v.condition).map(v=>v.message)),{same:x,pricesChanged:I}}}))(ag,_P,hC,og,lu,er,ii,gC,SP,au),{pickBillingControlColumns:iw}=((e,t)=>({pickBillingControlColumns:r=>{if(!r)return{};let i=Object.fromEntries(e.flatMap(a=>r[a]===void 0?[]:[[a,r[a]]]));return i.auto_topups!==void 0&&(i.auto_topups=t(i.auto_topups)),i}}))(Co,YC),{mapToProductV2:nL}=((e,t,n,r,i)=>({mapToProductV2:({product:o,features:s})=>{let c=[];for(let l of o.entitlements){let d=e({ent:l,prices:o.prices});c.push(t({ent:l,price:d}))}for(let l of o.prices)n({price:l,entitlements:o.entitlements})||c.push(t({price:l}));s||(s=o.entitlements.map(l=>l.feature));for(let l of c)l.feature_type=r({item:l,features:s});return{internal_id:o.internal_id,id:o.id,name:o.name,description:o.description??null,is_add_on:o.is_add_on,is_default:o.is_default,version:o.version,version_slug:o.version_slug??null,active:o.active??!1,group:o.group||null,free_trial:o.free_trial,created_at:o.created_at,env:o.env,items:c,stripe_id:o.processor?.id||null,archived:o.archived||!1,config:o.config??void 0,billing_controls:i(o),metadata:o.metadata??{}}}}))(Lh,Sg,su,Bh,qh),{AdditionalCurrencyTierSchema:aw}=((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"]})}))(Ae,xg),{AdditionalCurrencyPriceArraySchema:ow}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ae,JC,Gh,Hh),{CreditSchemaItemSchema:sw}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(Ae,XC,$C),{validateItemFeatureOverride:cw}=((e,t,n,r,i,a,o,s,c)=>({validateItemFeatureOverride:({item:l,feature:d,features:m})=>{let g=l.config?.feature_override;if(!g)return;let p=x=>{throw new e({message:`${x} (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&&!a(d.type)&&p("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let h={schema:g.schema,usage_type:o.Single};s(h,d.type),c({config:h,allFeatures:m});for(let x of g.schema)if(!m.find(v=>v.id===x.metered_feature_id))throw new e({message:`feature_override on ${d.id} references unknown feature ${x.metered_feature_id}`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})}}))(Dt,Vt,Yn,qP,Ct,eu,Jn,ew,h1),{toPrice:uw}=((e,t,n,r,i,a,o)=>({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 x=c.base_currency??(h?g?.config?.base_currency:void 0);x&&(p.base_currency=x);let I={id:c.price_id||g?.id||a("pr"),created_at:c.created_at||Date.now(),org_id:u,internal_product_id:l,is_custom:d,config:p,proration_config:null};return(d||m)&&(I={...I,id:a("pr"),created_at:Date.now()}),p.stripe_price_id=o({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:I}),{price:I,ent:null}}}))(Jr,ni,er,ii,HP,zr,vg),{entsAreSame:du}=((e,t,n,r,i,a,o)=>({entsAreSame:(c,u)=>{if(c.internal_feature_id!==u.internal_feature_id||e(c)!==e(u))return!1;let l=e(c),d={interval:t(c)!==t(u),intervalCount:n(c)!==n(u),allowance:!l&&c.allowance!=u.allowance,carryFromPrevious:(c.carry_from_previous??!1)!==(u.carry_from_previous??!1),entityFeatureId:r(c.entity_feature_id)!==r(u.entity_feature_id),pooled:(c.pooled??!1)!==(u.pooled??!1),usageLimit:c.usage_limit!=u.usage_limit,rollover:!i({rollover1:c.rollover,rollover2:u.rollover}),featureOverride:!a({override1:c.feature_override,override2:u.feature_override}),expiry:!o(c,u)};return!Object.values(d).some(Boolean)}}))(v1,Jh,I1,A1,P1,lu,w1),{toFeatureAndPrice:lw}=((e,t,n,r,i,a,o,s,c,u,l,d,m,g,p,h,x,I,v,j,T,P,_e,nt,Ze,je,ue,V)=>({toFeatureAndPrice:({item:Z,orgId:mt,internalFeatureId:fe,internalProductId:ce,isCustom:$t,curPrice:ze,curEnt:Gt,newVersion:jn,features:Xt})=>{let wg=e({item:Z,feature:Xt.find(Et=>Et.id===Z.feature_id)}),Uo=t({item:Z,features:Xt,curPrice:ze}),fu=Uo===n.Arrear,Ir={id:Z.entitlement_id||Gt?.id||r("ent"),org_id:mt,created_at:Z.created_at||Date.now(),is_custom:$t,internal_product_id:ce,internal_feature_id:fe,feature_id:Z.feature_id,allowance:Z.included_usage||0,allowance_type:i.Fixed,interval:a({item:Z}),interval_count:o({item:Z}),carry_from_previous:!wg,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};(!Gt||$t&&!s(Gt,Ir)||jn)&&(Ir={...Ir,id:r("ent"),created_at:Date.now()});let Og=a({item:Z}),oi={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:Og===d.Lifetime&&!fu,...Uo?{allocated_billing_behavior:Uo}:{},internal_feature_id:fe,feature_id:Z.feature_id,usage_tiers:m(Z.price)?[{amount:Z.price,to:g}]:Z.tiers?.map(Et=>({to:Et.to,amount:Et.amount??0,...Et.flat_amount!=null?{flat_amount:Et.flat_amount}:{}})),interval:p({item:Z}),interval_count:h({item:Z}),stripe_price_id:void 0},hu=x({baseTiers:oi.usage_tiers,itemTiers:Z.tiers,flatCurrencies:Z.additional_currencies});hu&&(oi.currencies=hu,oi.base_currency=Z.base_currency??ze?.config?.base_currency??void 0);let Eg=I({item:Z,features:Xt})&&!fu,gu=null;if(Eg){let Et=Z.config?.on_increase||v.ProrateImmediately,tr=Z.config?.on_decrease||j.Prorate;(T(tr)||tr===j.Prorate)&&(tr=Et===v.ProrateImmediately||Et===v.BillImmediately?j.ProrateImmediately:j.ProrateNextCycle),gu={on_increase:Et,on_decrease:tr}}let An={id:Z.price_id||ze?.id||r("pr"),created_at:Z.created_at||Date.now(),org_id:mt,internal_product_id:ce,is_custom:$t,config:oi,entitlement_id:Ir.id,proration_config:gu,tier_behavior:Z.tier_behavior??null},bu=P(An.config);if((bu===_e.UsageInArrear||bu===_e.InArrearProrated)&&An.config.interval===nt.OneOff)throw new Ze({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${Z.feature_id})`,code:je.InvalidPrice,statusCode:400});let Tg=ze&&!ue(ze,An,!0)||Gt&&!s(Gt,Ir);if(ze&&(Tg||jn)){let Et=An.config,tr=ze.config;Et.stripe_meter_id=tr.stripe_meter_id,Et.stripe_product_id=tr.stripe_product_id,An.config=Et}return($t||jn)&&(An={...An,id:r("pr"),created_at:Date.now()}),oi.stripe_price_id=V({requestedStripePriceId:Z.stripe_price_id,currentPrice:ze,newPrice:An}),{price:An,ent:Ir}}}))(Yh,KC,Xn,zr,wo,To,Ro,du,Jr,ei,ta,Yr,ni,zc,er,ii,E1,jC,ri,na,R1,k1,Xr,Rn,Dt,Vt,Do,vg),{getPriceStripeReuseLevel:dw}=((e,t,n,r,i,a)=>({getPriceStripeReuseLevel:({newPrice:s,candidatePrice:c,newEntitlements:u,candidateEntitlements:l})=>{if(e({price:c})||s.config?.type!==c.config?.type)return"none";if(t(c,s,!1)){if(s.config?.type!==n.Usage)return"full";let h=r({price:s,entitlements:u}),x=r({price:c,entitlements:l});if(!h&&!x)return"full";if(!h||!x)return"none";if(i(x,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||a(g.entity_feature_id)!==a(p.entity_feature_id)?"none":"stripeProductOnly"}}))(NC,Do,Jr,eC,du,U1),{applyLicenseCustomizeToBasePlan:rL}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:a})=>{let o=new Set((a.add_items??[]).map(u=>e(u))),s={...i,items:i.items.filter(u=>!o.has(e(u)))},c=t({base:s,diff:a});return{...s,...c,items:n(c.items)}}}))(ra,Ig,QC),{diffPlanV1:mw}=((e,t,n,r,i,a,o,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 x=new Map(l.items.map(T=>[r(T),T])),I=new Map(d.items.map(T=>[r(T),T])),v=[];for(let T of d.items){let P=x.get(r(T));(!P||!i(P,T))&&v.push(a(T))}v.length>0&&(h.add_items=v);let j=[];for(let T of l.items){let P=I.get(r(T));(!P||!i(T,P))&&j.push(o({item:T,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:T,...P}=d.free_trial;h.free_trial=T==null?P:{...P,on_end:T}}return Object.assign(h,c({from:l.licenses,to:d.licenses,includeAdds:m,includeRemoves:g})),h}}))(eg,hg,Y1,ra,_g,nP,rP,cC,tw),{currentItemsOf:Pg}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))(Ag),{itemsAreSame:Cg}=((e,t,n,r,i,a,o,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:x}=r({item1:u,item2:l,logDifferences:m});g=h,i({item:u,features:d||[]})?.config?.usage_type===a.Continuous?p=!0:p=x}return o(u)&&(g=s({item1:u,item2:l,logDifferences:m}),g||(p=!0)),{same:g,pricesChanged:!g&&p}}}))(ko,nw,ai,rw,Xh,Jn,jo,xP),{productsAreSame:iL}=((e,t,n,r,i,a,o,s,c,u,l,d,m)=>({productsAreSame:({newProductV1:p,newProductV2:h,curProductV1:x,curProductV2:I,features:v})=>{if(!p&&!h)throw new Error("productsAreSame error: product1 not provided");if(!x&&!I)throw new Error("productsAreSame error: product2 not provided");let j=h?.items||e({prices:p?.prices||[],entitlements:p?.entitlements||[],features:v}),T=I?.items||e({prices:x?.prices||[],entitlements:x?.entitlements||[],features:v});j=t({items:j,features:v}),T=t({items:T,features:v});let P=!0,_e=!1,nt=!0,Ze=!0,je=!0,ue=[],V=[];nt=n({newProductV2:h,curProductV2:I}),Ze=r({newConfig:h?.config,curConfig:I?.config}),je=i({newBillingControls:h?.billing_controls??(p?a(p):void 0),curBillingControls:I?.billing_controls??(x?a(x):void 0)});let De=o({newMetadata:h?.metadata,curMetadata:I?.metadata});j.length!==T.length&&(P=!1),j.length!==T.length&&(P=!1);for(let ze of j){let Gt=s({item:ze,items:T});if(!Gt){(c(ze)||u(ze))&&(_e=!0),P=!1,ue.push(ze);continue}let{same:jn,pricesChanged:Xt}=l({item1:ze,item2:Gt,features:v,logDifferences:!1});jn||(P=!1,ue.push(ze)),Xt&&(_e=!0)}for(let ze of T)s({item:ze,items:j})||(P=!1,(c(ze)||u(ze))&&(_e=!0),V.push(ze));let Z=x?.free_trial||I?.free_trial,mt=p?.free_trial||h?.free_trial,fe=d({ft1:Z,ft2:mt}),ce=m({curProduct:I||x,newProduct:h||p});return{itemsSame:P,freeTrialsSame:fe,onlyEntsChanged:!_e,newItems:ue,removedItems:V,detailsSame:nt,optionsSame:ce,configSame:Ze,billingControlsSame:je,metadataSame:De,same:P&&nt&&fe&&Ze&&De&&je}}}))(Ag,LC,AP,PP,BC,qh,OP,uu,ai,jo,Cg,EP,TP),{constructProduct:aL}=((e,t)=>({constructProduct:({productData:r,version:i=1,orgId:a,env:o,processor:s,baseInternalProductId:c})=>({id:r.id,name:r.name,description:r.description??null,is_add_on:r.is_add_on,is_default:r.is_default,version:i,version_slug:`v${i}`,active:!0,group:r.group||"",env:o,internal_id:e("prod"),org_id:a,created_at:Date.now(),processor:s,base_variant_id:null,base_internal_product_id:c??r.base_internal_product_id??null,archived:r.archived??!1,deleted_at:null,previous_version_slug:null,config:{...r.config,ignore_past_due:r.config?.ignore_past_due??!1},...t(r.billing_controls),metadata:r.metadata??{}})}))(zr,iw),{AdditionalCurrencyTierArraySchema:pw}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ae,aw,Gh,Hh),{FeatureConfigOverrideSchema:fw}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(Ae,sw,PC),{itemToPriceAndEnt:hw}=((e,t,n,r,i,a,o,s,c,u)=>({itemToPriceAndEnt:({item:d,orgId:m,internalProductId:g,feature:p,curPrice:h,curEnt:x,isCustom:I,newVersion:v,features:j})=>{let T=null,P=null,_e=null,nt=null,Ze=null,je=null;if(e(d)){let{price:ue}=t({item:d,orgId:m,internalProductId:g,isCustom:I,newVersion:v,curPrice:h});!h||v?T=ue:n(h,ue,!0)?Ze=h:_e=ue}else if(r(d)){if(!p)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let ue=p?.type===o.Boolean,{ent:V}=s({item:d,orgId:m,internalFeatureId:p.internal_id,internalProductId:g,isCustom:I,newVersion:v,feature:p,curEnt:x});!x||v?P=V:c(x,V)?je=x:nt=V}else{if(!p)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let{price:ue,ent:V}=u({item:d,orgId:m,internalFeatureId:p.internal_id,internalProductId:g,isCustom:I,curPrice:h,curEnt:x,newVersion:v,features:j}),De=x&&c(x,V);!h||v?T=ue:!De||!n(h,ue,!1)?_e=ue:Ze=h,!x||v?P=V:De?je=x:nt=V}return{newPrice:T,newEnt:P,updatedPrice:_e,updatedEnt:nt,samePrice:Ze,sameEnt:je}}}))(tu,uw,Do,Eo,Dt,Vt,Ct,QP,du,lw),{copyStripeResourcesToMatchingPrice:gw}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:o,candidatePrices:s,targetEntitlements:c,candidateEntitlements:u})=>{let l=s.map(I=>({candidatePrice:I,level:e({newPrice:o,candidatePrice:I,newEntitlements:c,candidateEntitlements:u})})),d=l.find(I=>I.level==="full"),g=(d??l.find(I=>I.level==="stripeProductOnly"))?.candidatePrice,p=d?.candidatePrice,h=o.config,x=[];if(g){let I=g.config;for(let v of t)v==="stripe_meter_id"&&(!n(o)||!n(g))||r({fromConfig:I,toConfig:h,field:v})&&x.push(v)}if(p){let I=p.config;for(let v of i)t.includes(v)||r({fromConfig:I,toConfig:h,field:v})&&x.push(v)}return{copiedFields:x}}}))(dw,F1,tC,M1,L1),{getApiPlanDiff:oL}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(mw),{backfillExistingItemIds:bw}=((e,t)=>({backfillExistingItemIds:({items:r,currentFullProduct:i,features:a})=>{let o=e({currentFullProduct:i,features:a});return r.map(s=>{if(s.entitlement_id||s.price_id)return s;let c=t({item:s,items:o});return c?{...s,...c.entitlement_id?{entitlement_id:c.entitlement_id}:{},...c.price_id?{price_id:c.price_id}:{}}:s})}}))(Pg,uu),{PriceTierSchema:_w}=((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}))}))(Ae,zc,pw),{ProductItemConfigSchema:yw}=((e,t,n,r,i,a,o)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:a.nullish(),feature_override:o.nullish()})}))(Ae,Xn,ri,na,UP,FP,fw),{carryForwardStripeResources:Sw}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:a})=>{for(let o of n)e({targetPrice:o,candidatePrices:i,targetEntitlements:r,candidateEntitlements:a})}}))(gw),{resolveInPlaceEdit:sL}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:a,items:o,currentFullProduct:s,features:c})=>{let u=e({items:o,currentFullProduct:s,features:c}),l=t({currentFullProduct:s,features:c}),d=[],m=[];for(let h of l){let x=n({item:h,items:u}),I=!x,v=x&&!r({item1:x,item2:h,features:c}).same;(I||v)&&(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 x=h.entitlement_id&&g.has(h.entitlement_id),I=h.price_id&&g.has(h.price_id);return x||I?{...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))}}}))(bw,Pg,uu,Cg),{ProductItemSchema:xw}=((e,t,n,r,i,a,o,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(Ae,XA,kn,NP,ea,Yc,ei,_w,ow,Oo,yw),{validateProductItem:vw}=((e,t,n,r,i,a,o,s,c,u,l,d,m,g,p,h,x,I,v,j)=>({validateProductItem:({item:P,features:_e,multiCurrencyEnabled:nt,validateRollover:Ze})=>{P=e.parse(P);let je=_e.find(fe=>fe.id===P.feature_id);if(t(P.feature_id)&&t(P.price)&&t(P.tiers))throw new n({message:"Either 'feature_id', 'price', or both should be set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let ue=P.pooled&&je?.type===a.Boolean,V=o(P)||s(P.included_usage)&&P.included_usage!==0||s(P.interval)||s(P.config?.rollover);if(ue&&V)throw new n({message:"Pooled boolean items cannot include balance or pricing fields",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(c({item:P,feature:je,features:_e}),o(P)&&P.included_usage===u)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(P.pooled&&o(P)&&P.usage_model===l.PayPerUse)throw new n({message:"Pooled items cannot use usage-based pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(P.price)&&s(P.tiers))throw new n({message:"Either 'price' or 'tiers' should be set, not both",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let De=(P.additional_currencies?.length??0)>0||(P.tiers?.some(fe=>(fe.additional_currencies?.length??0)>0)??!1);if(De&&!nt)throw new n({message:"Multi-currency is not enabled for this organization",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(De&&t(P.base_currency))throw new n({message:"'base_currency' is required when 'additional_currencies' are set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if((P.additional_currencies?.length??0)>0){if(s(P.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(P.price)&&P.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(P)&&P.price&&P.price.toString().split(".")[1]?.length>2)throw new n({message:"One off prices can have at most 2 decimal places",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(P)||m(P)){if(typeof P.included_usage!="number"&&P.included_usage!==u&&s(P.included_usage))throw new n({message:`Included usage for feature ${P.feature_id} must be a number or '${u}'`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(t(P.included_usage)&&(P.included_usage=0),typeof P.included_usage=="number"&&P.included_usage<0)throw new n({message:"Included usage must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(P)||d(P)){let fe=g({item:P});if(String(fe)===p.Day||String(fe)===p.Minute||String(fe)===p.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(P)&&t(P.usage_model))throw new n({message:`Usage model is required for priced features. Please select one for the feature ${P.feature_id}`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(P)&&P.tiers){if(P.included_usage===u)throw new n({message:`Included usage can't be '${u}' for tiered prices`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(P.billing_units&&P.billing_units<=0)throw new n({message:"Billing units must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(P.tier_behavior===h.VolumeBased&&P.tiers.length>1&&P.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(P.tiers.some(ce=>ce.flat_amount!=null&&ce.flat_amount>0)){if(P.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(P.tiers.length<=1)throw new n({message:"flat_amount is not supported on single-tier pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(P.tiers.some(ce=>ce.flat_amount!=null&&ce.flat_amount<0))throw new n({message:"flat_amount must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(P.usage_model===l.Prepaid&&P.config?.on_increase===x.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(P.config?.expiry&&je&&(je.type===a.Boolean||I({feature:je})))throw new n({message:`expiry is only supported on consumable features (feature: ${P.feature_id})`,code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(!P.config?.rollover)return;let Z=P.config.rollover;if(Z.duration===v.Forever&&(Z.length=0),!Ze)return;if(P.included_usage===u)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let mt=j({rollover:Z});if(mt)throw new n({message:mt,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(Z.duration===v.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(P.usage_limit)&&P.usage_limit<=0)throw new n({message:"Usage limit must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}}))(xw,Jt,Dt,Vt,Yn,Ct,Xc,vr,cw,ea,ei,tu,Eo,er,Yc,Oo,ri,ug,Jc,g1),{validateProductItems:Iw}=((e,t,n,r,i,a,o,s,c,u,l,d,m,g,p)=>({validateProductItems:({newItems:x,features:I,orgId:v,env:j,multiCurrencyEnabled:T,validateRollover:P=!0})=>{let{allFeatures:_e,newFeatures:nt}=e({items:x,curFeatures:I,orgId:v,env:j});I=_e;for(let ue=0;ue<x.length;ue++){t({item:x[ue],features:I,multiCurrencyEnabled:T,validateRollover:P});let V=I.find(De=>De.id===x[ue].feature_id);V&&V.type===n.Metered&&(x[ue].feature_type=V.config?.usage_type)}for(let ue=0;ue<x.length;ue++){let V=x[ue],De=r({item:V}),Z=i({item:V});if(a(V)&&x.find((ce,$t)=>ce.feature_id===V.feature_id&&$t!==ue&&V.entity_feature_id===ce.entity_feature_id))throw new o({message:`Feature ${V.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let mt=x.find((fe,ce)=>fe.feature_id===V.feature_id&&ce!==ue&&r({item:fe})===De&&i({item:fe})===Z&&fe.entity_feature_id===V.entity_feature_id);if(mt){if(u(mt)&&u(V))throw new o({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===mt?.usage_model)throw new o({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)&&x.find((ce,$t)=>d({item:ce})===d({item:V})&&m({item:ce})===m({item:V})&&$t!==ue))throw new o({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let Ze=x.some(ue=>(l(ue)||g(ue))&&String(d({item:ue}))===p.Week),je=x.some(ue=>(l(ue)||g(ue))&&String(d({item:ue}))===p.Month);if(Ze&&je)throw new o({message:"Can't have both weekly and monthly price items in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(x.filter(l).length>1)throw new o({message:"Can't have more than one price item in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});return{allFeatures:_e,newFeatures:nt}}}))(vC,vw,Ct,To,Ro,dg,Dt,Vt,Yn,Eo,tu,er,ii,Xc,Yc),{handleNewProductItems:cL}=((e,t,n,r,i)=>({handleNewProductItems:async({db:o,curPrices:s,curEnts:c,newItems:u,features:l,product:d,logger:m,isCustom:g,newVersion:p,saveToDb:h=!0,multiCurrencyEnabled:x})=>{if(!u)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:l};let{allFeatures:I,newFeatures:v}=e({newItems:u,features:l,orgId:d.org_id,env:d.env,multiCurrencyEnabled:x,validateRollover:!g});l=I;let j=[],T=[],P=[],_e=[],nt=s.filter(V=>{let De=u.find(Z=>Z.price_id===V.id);return De?t(De):!0}),Ze=c.filter(V=>!u.some(De=>De.entitlement_id===V.id)),je=[],ue=[];for(let V of u){let De=l.find(Xt=>Xt.id===V.feature_id),Z=c.find(Xt=>Xt.id===V.entitlement_id),mt=s.find(Xt=>Xt.id===V.price_id),{newPrice:fe,newEnt:ce,updatedPrice:$t,updatedEnt:ze,samePrice:Gt,sameEnt:jn}=n({item:V,orgId:d.org_id,internalProductId:d.internal_id,feature:De,curPrice:mt,curEnt:Z,isCustom:g,newVersion:p,features:l});fe&&j.push(fe),ce&&T.push(ce),$t&&P.push($t),ze&&_e.push(ze),Gt&&je.push(Gt),jn&&ue.push(jn)}return r({targetPrices:[...j,...P],targetEntitlements:[...T,..._e,...ue],candidatePrices:s,candidateEntitlements:c}),(g||p)&&h?{...i({newPrices:j,newEnts:T,updatedPrices:P,updatedEnts:_e,samePrices:je,sameEnts:ue,features:l}),samePrices:je,sameEnts:ue,newFeatures:v,retiredPriceIds:nt.map(V=>V.id),retiredEntitlementIds:Ze.map(V=>V.id)}:{prices:[...j,...P],entitlements:[...T,..._e].map(V=>({...V,feature:l.find(De=>De.id===V.feature_id)})),customPrices:[],customEnts:[],features:l,samePrices:je,sameEnts:ue,newFeatures:v,retiredPriceIds:nt.map(V=>V.id),retiredEntitlementIds:Ze.map(V=>V.id)}}}))(Iw,ko,hw,Sw,B1);var Aw=mn.clone({precision:40});function mu(e){if(!cu(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function pu(e){let t=new Aw(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function mL(e,t){let n=mu(t),i=pu(e).toDecimalPlaces(ig(n),mn.ROUND_HALF_CEIL).mul(No(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 pL(e,t){let n=mu(t),r=pu(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(No(n)).toString()}function fL(e,t){let n=pu(e).mul(No(mu(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()}export{O_ as a,xl as b,is as c,Al as d,_a as e,R_ as f,as as g,k_ as h,Pl as i,os as j,Gw as k,j_ as l,Cl as m,Hw as n,wl as o,Kw as p,pi as q,cs as r,ya as s,Un as t,Q as u,nr as v,Yw as w,Jw as x,El as y,nO as z,Tl as A,U_ as B,F_ as C,rO as D,us as E,ut as F,Y as G,Sa as H,en as I,Xe as J,Dl as K,L_ as L,B_ as M,q_ as N,lO as O,ds as P,ms as Q,ps as R,V_ as S,$_ as T,Ul as U,G_ as V,bO as W,gn as X,PO as Y,Fl as Z,CO as _,Ml as $,H_ as aa,Ll as ba,wO as ca,OO as da,K_ as ea,Bl as fa,fs as ga,EO as ha,TO as ia,tn as ja,rr as ka,xa as la,Z_ as ma,jO as na,FO as oa,z_ as pa,Y_ as qa,Hl as ra,$O as sa,wr as ta,nn as ua,Kl as va,J_ as wa,Wl as xa,GO as ya,HO as za,KO as Aa,WO as Ba,QO as Ca,ZO as Da,fi as Ea,va as Fa,Jl as Ga,bs as Ha,Or as Ia,ey as Ja,ty as Ka,ny as La,ry as Ma,Fn as Na,Xl as Oa,ed as Pa,td as Qa,nd as Ra,Ia as Sa,rd as Ta,id as Ua,ad as Va,od as Wa,ay as Xa,sd as Ya,oy as Za,sy as _a,cy as $a,cd as ab,_s as bb,uy as cb,gi as db,ud as eb,ld as fb,dd as gb,ly as hb,md as ib,pd as jb,_i as kb,yi as lb,ar as mb,Aa as nb,Ss as ob,dy as pb,hd as qb,gd as rb,Si as sb,Pa as tb,bd as ub,fE as vb,hE as wb,gE as xb,bE as yb,my as zb,_E as Ab,yE as Bb,vs as Cb,IE as Db,AE as Eb,xi as Fb,wE as Gb,OE as Hb,py as Ib,fy as Jb,_d as Kb,EE as Lb,hy as Mb,TE as Nb,gy as Ob,yd as Pb,by as Qb,RE as Rb,kE as Sb,jE as Tb,xd as Ub,_y as Vb,DE as Wb,Sd as Xb,yy as Yb,Id as Zb,As as _b,xy as $b,UE as ac,or as bc,FE as cc,ME as dc,vy as ec,Iy as fc,Ay as gc,Py as hc,VE as ic,$E as jc,Ad as kc,Ps as lc,YE as mc,JE as nc,Cy as oc,nT as pc,rT as qc,Ca as rc,Pi as sc,Cs as tc,cr as uc,Od as vc,wa as wc,Ed as xc,Ci as yc,wy as zc,kd as Ac,ws as Bc,jd as Cc,Nd as Dc,Dd as Ec,Oy as Fc,Ud as Gc,Os as Hc,Fd as Ic,yT as Jc,Md as Kc,ST as Lc,xT as Mc,Oa as Nc,Ld as Oc,wi as Pc,Ye as Qc,Bd as Rc,qd as Sc,Ea as Tc,Vd as Uc,jy as Vc,$d as Wc,Hd as Xc,Kd as Yc,Rs as Zc,Ny as _c,Wd as $c,DT as ad,Qd as bd,Zd as cd,MT as dd,LT as ed,Dy as fd,Uy as gd,Bn as hd,zd as id,Fy as jd,My as kd,ks as ld,js as md,qn as nd,iS as od,Ns as pd,Rr as qd,hm as rd,dr as sd,jS as td,NS as ud,bm as vd,Ti as wd,kr as xd,Ra as yd,_m as zd,ym as Ad,Ds as Bd,DS as Cd,US as Dd,FS as Ed,Sm as Fd,Us as Gd,xm as Hd,vm as Id,Im as Jd,ka as Kd,oR as Ld,sR as Md,Am as Nd,ja as Od,MS as Pd,ki as Qd,Na as Rd,Pm as Sd,BS as Td,Ms as Ud,pR as Vd,wm as Wd,Om as Xd,qS as Yd,Ls as Zd,Tm as _d,Rm as $d,Ua as ae,Fa as be,VS as ce,$S as de,GS as ee,km as fe,jm as ge,Nm as he,Dm as ie,Um as je,Fm as ke,Mm as le,Lm as me,jr as ne,Vn as oe,Bm as pe,KS as qe,qs as re,mr as se,NR as te,Gs as ue,WS as ve,QS as we,ji as xe,ZS as ye,YS as ze,JS as Ae,Ni as Be,FR as Ce,Ma as De,$s as Ee,XS as Fe,Vm as Ge,$m as He,e0 as Ie,MR as Je,LR as Ke,Gm as Le,t0 as Me,BR as Ne,n0 as Oe,Nr as Pe,Ba as Qe,qa as Re,Km as Se,ZR as Te,Wm as Ue,Ur as Ve,Qm as We,r0 as Xe,Hs as Ye,Zm as Ze,Va as _e,$a as $e,Ga as af,tk as bf,nk as cf,i0 as df,zm as ef,Ym as ff,o0 as gf,Xm as hf,ok as if,ep as jf,Ks as kf,tp as lf,uk as mf,s0 as nf,cn as of,Ui as pf,Fe as qf,c0 as rf,u0 as sf,Qs as tf,np as uf,Fi as vf,rp as wf,l0 as xf,d0 as yf,ap as zf,m0 as Af,p0 as Bf,f0 as Cf,h0 as Df,g0 as Ef,pr as Ff,b0 as Gf,_0 as Hf,y0 as If,S0 as Jf,x0 as Kf,v0 as Lf,I0 as Mf,A0 as Nf,P0 as Of,C0 as Pf,w0 as Qf,O0 as Rf,op as Sf,E0 as Tf,R0 as Uf,k0 as Vf,Zs as Wf,_k as Xf,j0 as Yf,yk as Zf,wt as _f,Sk as $f,Tt as ag,_n as bg,zs as cg,D0 as dg,Fr as eg,xk as fg,vk as gg,M0 as hg,Ys as ig,Ik as jg,L0 as kg,Mi as lg,Ak as mg,Pk as ng,cp as og,On as pg,q0 as qg,Ha as rg,Ka as sg,G0 as tg,H0 as ug,up as vg,Uk as wg,Fk as xg,Mk as yg,Lk as zg,lp as Ag,Wa as Bg,mp as Cg,Js as Dg,pp as Eg,fp as Fg,hp as Gg,bp as Hg,gp as Ig,Xs as Jg,K0 as Kg,nj as Lg,W0 as Mg,_p as Ng,Q0 as Og,br as Pg,yp as Qg,xp as Rg,vp as Sg,Ip as Tg,Ap as Ug,Pp as Vg,Z0 as Wg,Cp as Xg,z0 as Yg,Y0 as Zg,J0 as _g,X0 as $g,Ep as ah,nc as bh,Rp as ch,ex as dh,tx as eh,gj as fh,bj as gh,_j as hh,jp as ih,Np as jh,Dp as kh,Up as lh,Fp as mh,Mp as nh,yj as oh,Sj as ph,rx as qh,ix as rh,xj as sh,vj as th,yn as uh,rc as vh,ax as wh,Bi as xh,ox as yh,Pj as zh,Bp as Ah,qp as Bh,Cj as Ch,Vp as Dh,$p as Eh,ic as Fh,ac as Gh,ux as Hh,lx as Ih,dx as Jh,wj as Kh,oc as Lh,Lr as Mh,za as Nh,Hp as Oh,Br as Ph,qr as Qh,_r as Rh,yr as Sh,Vr as Th,Kp as Uh,mx as Vh,px as Wh,sc as Xh,Wp as Yh,Qp as Zh,Zp as _h,cc as $h,zp as ai,uc as bi,Dj as ci,Uj as di,Yp as ei,Jp as fi,fx as gi,Xp as hi,ef as ii,tf as ji,lc as ki,hx as li,nf as mi,Hj as ni,rf as oi,dc as pi,af as qi,qi as ri,of as si,Kj as ti,gx as ui,RN as vi,D as wi,bx as xi,_x as yi,yx as zi,kN as Ai,N as Bi,jN as Ci,pc as Di,lf as Ei,df as Fi,LN as Gi,BN as Hi,qN as Ii,tt as Ji,$N as Ki,pf as Li,mf as Mi,Xa as Ni,HN as Oi,ff as Pi,YN as Qi,Ax as Ri,Px as Si,JN as Ti,XN as Ui,hf as Vi,Cx as Wi,nD as Xi,wx as Yi,gf as Zi,bf as _i,Ox as $i,rD as aj,iD as bj,aD as cj,oD as dj,Ex as ej,uD as fj,lD as gj,pD as hj,fD as ij,yf as jj,_D as kj,yD as lj,Ki as mj,Sf as nj,hc as oj,Wi as pj,to as qj,Qi as rj,un as sj,CD as tj,bc as uj,wD as vj,Gn as wj,no as xj,ro as yj,_c as zj,vf as Aj,ao as Bj,yc as Cj,Nx as Dj,Af as Ej,Pf as Fj,FD as Gj,MD as Hj,LD as Ij,BD as Jj,qD as Kj,VD as Lj,Dx as Mj,$D as Nj,Sc as Oj,Ux as Pj,xc as Qj,ZD as Rj,zD as Sj,YD as Tj,Cf as Uj,n2 as Vj,Fx as Wj,Mx as Xj,vc as Yj,o2 as Zj,Lx as _j,Bx as $j,Of as ak,m2 as bk,Ac as ck,Pc as dk,Gx as ek,Cc as fk,wc as gk,Gr as hk,Hx as ik,Kx as jk,C2 as kk,Ef as lk,D2 as mk,Ec as nk,Tc as ok,U2 as pk,F2 as qk,M2 as rk,L2 as sk,Wx as tk,Tf as uk,Bt as vk,jf as wk,Nf as xk,Rf as yk,Qx as zk,Zx as Ak,Zi as Bk,zx as Ck,Nc as Dk,Jx as Ek,cU as Fk,uU as Gk,lU as Hk,Dc as Ik,Xx as Jk,ev as Kk,Uc as Lk,Ff as Mk,OU as Nk,Mf as Ok,UU as Pk,FU as Qk,qf as Rk,rv as Sk,iv as Tk,WU as Uk,$f as Vk,av as Wk,Fc as Xk,Mc as Yk,Lc as Zk,ov as _k,sv as $k,oF as al,sF as bl,cF as cl,uF as dl,mF as el,hF as fl,Hf as gl,yF as hl,SF as il,cv as jl,uv as kl,lv as ll,dv as ml,mv as nl,pv as ol,AF as pl,fv as ql,PF as rl,CF as sl,TF as tl,hv as ul,gv as vl,uo as wl,bv as xl,_v as yl,jF as zl,MF as Al,LF as Bl,BF as Cl,yv as Dl,qF as El,HF as Fl,KF as Gl,Nv as Hl,Dv as Il,Uv as Jl,aM as Kl,ih as Ll,Fv as Ml,cM as Nl,ah as Ol,pM as Pl,fM as Ql,yM as Rl,SM as Sl,Mv as Tl,AM as Ul,PM as Vl,oh as Wl,sh as Xl,kM as Yl,jM as Zl,Bv as _l,VM as $l,qv as am,$M as bm,Vv as cm,HM as dm,uh as em,KM as fm,WM as gm,lh as hm,dh as im,JM as jm,XM as km,$v as lm,a4 as mm,Gv as nm,o4 as om,s4 as pm,fh as qm,hh as rm,m4 as sm,p4 as tm,f4 as um,h4 as vm,ph as wm,g4 as xm,Hv as ym,y4 as zm,v4 as Am,Wv as Bm,bh as Cm,I4 as Dm,P4 as Em,C4 as Fm,mL as Gm,pL as Hm,fL as Im};