@tinkerlandai/indiana-sdk 0.3.1 → 0.4.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.
@@ -0,0 +1,11 @@
1
+ import{e as ja}from"./chunk-TZ6REIUE.js";import{z as on}from"zod";import{z as A}from"zod/v4";import{z as Yg}from"zod/v4";var mu=Yg.registry();var{AppEnv:eo}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:fu}={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:Jg}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:Xg}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(A),{ResetInterval:ii}=(()=>{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:eh}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:th}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:nh}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:rh}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:ih}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(A),{BALANCE_BASES:oh}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:gu}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:Na}=(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:Sr}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(A),{findDuplicate:ah}={findDuplicate:t=>{let n=new Set;for(let r of t){if(n.has(r))return r;n.add(r)}}},{BillingInterval:kn}=(()=>{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:Da}=(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:oi}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(mu),{COMMON:hu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:sh}={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:ch}=(e=>({COMMON_SET:new Set(e)}))(hu),{hasNoDuplicateCurrencies:bu}={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:_u}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:Fa}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(A),{Infinite:to}={Infinite:"inf"},{TierBehavior:ai}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:no}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:yu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:uh}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:ro}=(()=>{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:io}=(()=>{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:Ua}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:Su}=(()=>{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:lh}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:dh}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ma}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(A),{ApiCreditTierSchema:xu}=(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:ph}={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:vu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(A),{ModelMarkupsSchema:La}=((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,vu),{additionalCurrencyPlanItemIssues:Iu}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let n=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&n.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let r=t.tiers;if(r&&r.length>0){let i=a=>(a.additional_currencies??[]).map(s=>s.currency.toLowerCase()),o=new Set(r.flatMap(i));o.size>0&&(r.every(s=>{let c=new Set(i(s));return c.size===o.size&&[...o].every(u=>c.has(u))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:Ba}=((e,t,n,r,i)=>({PlanItemFilterSchema:e.object({feature_id:e.string().optional().meta({description:"Match items linked to this feature."}),billing_method:e.enum(t).optional().meta({description:"Match items with this billing method (prepaid or usage_based)."}),interval:e.union([e.enum(n),e.enum(r)]).optional().meta({description:"Match items with this interval. Accepts either a BillingInterval (price-side) or a ResetInterval (reset-side, includes day/hour/minute) so price-less items keyed by reset.interval can be disambiguated."}),interval_count:e.number().int().positive().optional().meta({description:"Match items with this interval_count. Disambiguates between items that share an interval but differ in count."}),included:i.optional().meta({description:"Match items whose grant equals this included usage. Omitted is a wildcard."})}).refine(a=>a.feature_id!==void 0||a.billing_method!==void 0||a.interval!==void 0||a.interval_count!==void 0,{message:"PlanItemFilter must have at least one field set."}).meta({title:"PlanItemFilter",description:"Filter for matching plan items. All provided fields must match (AND)."})}))(A,no,kn,ii,Fa),{UpdatePlanItemParamsV1Schema:mh}=((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,Ba,ii),{FreeTrialDuration:si}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:fh}=((e,t)=>({laneParam:({schema:r,description:i})=>e({schema:t.array(r).optional(),defaultValue:[],description:i})}))(oi,A),{findDuplicateInControls:gh}={findDuplicateInControls:({controlKey:t,controls:n,rule:r})=>{let i=new Set;for(let[o,a]of n.entries()){let s=r.identityOf(a);if(s!==void 0){if(i.has(s))return{code:"custom",message:r.message,input:a[r.field],path:[t,o,r.field]};i.add(s)}}}},{featureIdIdentity:hh}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:Au}={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:bh}=((e,t)=>({usageAlertIdentity:r=>[r.feature_id??"",r.basis??e,t(r.filter),r.threshold_type,r.threshold].join("|")}))(gu,Au),{RemovePlanLicenseSchema:_h}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(A),{ApiStripePriceProcessorSchema:yh}=(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:Sh}=(()=>{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:xh}=(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:vh}=(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:oo}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:Ih}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:Ah}=(()=>{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:wh}=(()=>{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:Oh}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(A),{UsageWindowScopeSchema:Ph}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(A),{EntInterval:wu}=(()=>{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:Ch}=(()=>{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:Eh}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(A),{FreeTrialSchema:Th}=((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,si,oo),{BillingType:Rh}=(()=>{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:qa}=((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,to),{IgnoredFixedPriceMetadataSchema:kh}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(A),{BillWhen:jh}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Ou}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:Nh}=((e,t,n)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(n).default(n.ProrateImmediately)})}))(A,ro,io),{AllowanceType:Dh}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Pu}=((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,Ua),{CreditDimensionBaseSchema:Fh}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(A,Ma),{flatCreditRateShape:Cu}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(A),{CreditTierSchema:Uh}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(A),{CreditMultiplierSchema:Mh}=((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,Ma),{idRegex:ao}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Eu}={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:Lh}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:Bh}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:qh}=(()=>{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:Vh}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:$h}={TierInfinite:"inf"},{CreateFreeTrialSchema:Tu}=((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,si,oo),{ProductConfigParamsSchema:Va}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(A,oi,fu),{CREATE_PRODUCT_EXAMPLE:Gh}={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:Kh}=((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,si,oo),{CreateProductSchema:pO}=(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:zh}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:Ru}=(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:ku}=(()=>{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:ju}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:Nu}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(A,ju),{RewardTriggerEvent:Hh}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:Wh}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:so}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(A,fu),{PurchaseLimitIntervalEnum:Qh}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(A,Jg),{DbSpendLimitSchema:$a}=((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,Xg),{USAGE_LIMIT_INTERVALS:Zh}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(ii),{UsageLimitAnchorSchema:Du}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(A,eh),{UsageLimitFilterValueSchema:Yh}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(A,nh),{USAGE_ALERT_BASES:Jh}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(oh),{licensePatchIssues:Xh}=(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"]}]}}))(ah),{BasePriceSchema:eb}=((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,kn,Da),{CURRENCY_CODES:tb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(hu,sh,ch),{AllocatedBillingFieldSchema:Fu}=((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,yu),{EntitlementExpirySchema:co}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(A,Su),{CreditDimensionNameSchema:Uu}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(A,lh,dh),{ApiCreditMatchSchema:Mu}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ma),{findCreditTierViolations:nb}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(ph),{ApiCreditMultiplierSchema:rb}=((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,Mu),{ProviderMarkupsSchema:Lu}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(A,vu),{planItemParamsIssues:ib}=((e,t,n,r,i)=>({planItemParamsIssues:a=>{let s=[],c=a.reset?.interval,u=a.price?.interval,l=a.reset?.interval_count??1,d=a.price?.interval_count??1;if(c&&u&&(String(c)!==String(u)||l!==d)&&a.price?.billing_method!==e.Prepaid&&s.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:a}),a.threshold_billing&&(!a.price||a.unlimited)&&s.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing}),a.expiry&&(a.price?.billing_method===e.Prepaid&&String(a.price.interval)===String(t.OneOff)||s.push({message:"expiry is only supported on one-off prepaid items. Recurring items are already bounded by their reset cadence.",input:a.expiry}),a.entity_feature_id&&s.push({message:"expiry is not supported on entity-scoped items; each entity's balance would have to expire on its own clock.",input:a.expiry}),a.pooled&&s.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:a.expiry}),a.expiry.length<=0&&s.push({message:"expiry.length must be greater than 0",input:a.expiry})),a.price){a.threshold_billing&&a.price.billing_method!==e.UsageBased&&s.push({message:"threshold_billing requires a finite usage-based price",input:a.threshold_billing});let{amount:g,tiers:f}=a.price;a.threshold_billing&&f?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:a.threshold_billing});let h=a.price.billing_method===e.UsageBased&&a.price.allocated_billing===n.ProratedLegacy;a.proration&&a.price.billing_method!==e.Prepaid&&!h&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:a.proration});let v=typeof g=="number",I=Array.isArray(f)&&f.length>0;v||I?v&&I&&s.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:a.price}):s.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:a.price})}if(a.price?.tiers){let g=a.price.tiers.some(f=>f.flat_amount&&f.flat_amount>0);g&&a.price.tier_behavior!==r.VolumeBased&&s.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:a.price}),g&&a.price.tiers.length<=1&&s.push({message:"flat_amount is not supported on single-tier pricing.",input:a.price}),a.price.tiers.some(f=>f.flat_amount!=null&&f.flat_amount<0)&&s.push({message:"flat_amount must be 0 or greater.",input:a.price}),a.price?.tier_behavior===r.VolumeBased&&a.price?.billing_method!==e.Prepaid&&s.push({message:"volume-based pricing is only supported for prepaid features.",input:a.price}),a.price?.tiers.length===0?s.push({message:"tiers cannot be empty.",input:a.price}):a.included&&typeof a.price?.tiers[0].to=="number"&&a.price?.tiers[0].to<=a.included&&s.push({message:"tiers[0].to must be greater than included.",input:a.price})}for(let g of i(a.price))s.push({message:g,input:a.price});return s}}))(no,kn,yu,ai,Iu),{FreeTrialParamsV1Schema:Ga}=((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,si,oi),{duplicateCheck:ob}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(gh),{usageLimitIdentity:Ka}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(Au),{ApiPriceProcessorsSchema:Bu}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(A,yh),{ApiFeatureV0Schema:qu}=((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,Sh),{ApiRevenueCatPlanProcessorSchema:ab}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(A,vh),{ApiFreeTrialV2Schema:sb}=((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,si,oo),{CustomerEligibilitySchema:cb}=((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,Ih,Ah,wh),{UsageWindowLimitSchema:mO}=((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,Oh,Ph,wu,Du),{FeatureSchema:ub}=((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,eo,Ch,La,Eh),{PriceCurrencyConfigSchema:Vu}=((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,qa),{UsagePriceConfigSchema:lb}=((e,t,n,r,i,o)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(o).optional()})}))(A,jh,qa,kn,Vu,Ou),{graduatedCreditRateShape:$u}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(A,Uh),{FeatureMarkupsOverrideSchema:db}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(A,Lu,La),{usageAlertTargetLimitIdentity:pb}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(Ka),{DiscountConfigSchema:Gu}=((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,ju),{RewardEntitlementSchema:Ku}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(A,co),{UpdateRewardSchema:fO}=((e,t,n,r,i,o)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(n).optional(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()})}))(A,Ru,ku,Gu,Nu,Ku),{CreateRewardProgram:gO}=((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,Hh,Wh),{AutoTopupPurchaseLimitSchema:zu}=((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,Qh),{UsageLimitFilterSchema:Hu}=((e,t,n,r)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),n).meta({description:"Event property equality conditions. A usage event counts toward this cap only when every listed property matches (AND)."}).check(o=>{let a=Object.keys(o.value).length;(a<1||a>r)&&o.issues.push({code:"custom",message:`filter.properties must have between 1 and ${r} keys`,input:o.value})})})}))(A,th,Yh,rh),{UsageAlertBasisSchema:mb}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(A,Jh),{refineCustomizePlanV1Schema:Wu}=(e=>({refineCustomizePlanV1Schema:(n,{includeItems:r=!0,includeFreeTrial:i=!0,includeUpdateItems:o=!0,includeLicenses:a=!0}={})=>{let s=["price",r&&"items","add_items","remove_items",o&&"update_items",i&&"free_trial","billing_controls",a&&"upsert_licenses",a&&"remove_licenses"].filter(Boolean),c=u=>u==="update_items"?"deprecated update_items":u;return n.refine(u=>s.some(l=>u[l]!==void 0),{message:`When using customize, at least one of ${s.map(c).join(", ")} must be provided`}).superRefine((u,l)=>{if(a)for(let d of e({upsertLicenses:u.upsert_licenses}))l.addIssue({code:"custom",...d})}).refine(u=>!(u.items!==void 0&&(u.add_items!==void 0||u.remove_items!==void 0||o&&u.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",o?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(Xh),{SUPPORTED_SET:fb}=(e=>({SUPPORTED_SET:new Set(e)}))(tb),{ApiCreditDimensionBaseSchema:gb}=((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,Mu),{refineGraduatedTiers:Qu}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(o=>o.to));for(let{index:o,message:a}of i)r.addIssue({code:"custom",message:a,path:["tiers",o,"to"]})}}))(nb),{ApiFeatureMarkupsOverrideSchema:hb}=((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,Lu,La),{AutoTopupPurchaseLimitParamsSchema:bb}=((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."})})}))(zu,A),{DUPLICATE_CHECKS:_b}=((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"})]}))(ob,hh,Ka,bh),{ApiPlanProcessorsSchema:yb}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(A,xh,ab),{FixedPriceConfigSchema:Sb}=((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,kn,Vu,qa,kh),{CreditDimensionSchema:xb}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(A,Fh,Cu,$u),{filterUnresolvableUsageLimitAlerts:vb}=((e,t,n)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:o})=>{let a=new Set(o.flatMap(s=>(s??[]).map(e)));return i.flatMap((s,c)=>t(s)&&!a.has(n(s))?[{index:c,usageAlert:s}]:[])}}))(Ka,zh,pb),{CreateRewardSchema:hO}=((e,t,n,r,i,o)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(n).nullish(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(o).nullish()}).refine(s=>s.type!==n.FeatureGrant?!0:s.entitlements&&s.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(s=>s.type!==n.FeatureGrant?!0:s.promo_codes.some(c=>c.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(A,Ru,ku,Gu,Nu,Ku),{AutoTopupSchema:za}=((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,zu),{DbUsageLimitSchema:Ha}=((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,Zh,Du,Hu),{DbUsageAlertSchema:Wa}=((e,t,n,r,i)=>({DbUsageAlertSchema:e.object({feature_id:e.string().optional().meta({description:"The feature ID this alert applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage alert is enabled."}),threshold:e.number().min(0).meta({description:"The threshold value that triggers the alert. For usage or remaining, this is an absolute count. For usage_percentage or remaining_percentage, this is a percentage (0-100)."}),threshold_type:t.meta({description:"Whether the threshold is an absolute count or a percentage of the usage allowance or remaining balance."}),basis:n.default(r).meta({description:"What 100% means. balance: every grant on the feature. included: the plan allowance only. recurring: grants that reset. usage_limit: the cap of the usage limit with the same feature and filter."}),filter:i.optional().meta({description:"Only valid with basis usage_limit. Points the alert at the usage limit carrying the same filter."}),name:e.string().optional().meta({description:"Optional user-defined label to distinguish multiple alerts on the same feature."})}).check(a=>{let{feature_id:s,threshold_type:c,threshold:u,basis:l,filter:d}=a.value;c==="remaining_percentage"&&u>100&&a.issues.push({code:"custom",input:u,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),l==="usage_limit"&&!s&&a.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&l!=="usage_limit"&&a.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(A,ih,mb,gu,Hu),{isValidCurrencyCode:Ib}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(fb),{ApiCreditDimensionSchema:Ab}=((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,gb,xu,Qu),{AutoTopupParamsSchema:wb}=((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."})})}))(za,bb),{findDuplicateBillingControlIssue:Ob}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(_b),{CustomerBillingControlsSchema:Qa}=((e,t,n,r,i,o)=>({CustomerBillingControlsSchema:e.object({auto_topups:e.array(t).optional().meta({description:"List of auto top-up configurations per feature."}),spend_limits:e.array(n).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(r).optional().meta({description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:e.array(i).optional().meta({description:"List of usage alert configurations per feature."}),overage_allowed:e.array(o).optional().meta({description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})})}))(A,za,$a,Ha,Wa,Na),{PriceSchema:Pb}=((e,t,n,r,i,o)=>({PriceSchema:e.object({id:e.string(),internal_product_id:e.string().nullable(),org_id:e.string().optional(),created_at:e.number().optional(),billing_type:e.nativeEnum(t).nullish(),tier_behavior:e.nativeEnum(n).nullish(),is_custom:e.boolean().optional(),config:r.or(i),entitlement_id:e.string().nullish(),proration_config:o.nullable()})}))(A,Rh,ai,Sb,lb,Nh),{CreditSchemaItemBaseSchema:Zu}=((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,Uu,xb,Mh),{GraduatedCreditSchemaItemSchema:Cb}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(Zu,$u),{UpdateProductSchema:bO}=((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,so,Qa),{DbBillingControlsSchema:Eb}=((e,t,n,r,i,o)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(n).nullish(),usage_limits:e.array(r).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(o).nullish()})}))(A,za,$a,Ha,Wa,Na),{CurrencyCodeSchema:Yu}=((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,Ib),{AdditionalCurrencyTierSchema:Tb}=((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,Yu),{ApiCreditSchemaItemBaseSchema:Ju}=((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,Uu,Ab,rb),{ApiFlatCreditSchemaItemSchema:Rb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Ju,A),{rejectDuplicateBillingControls:kb}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(Ob),{FlatCreditSchemaItemSchema:jb}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(Zu,Cu),{ProductSchema:Nb}=((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,eo,so,Eb,Sr),{AdditionalCurrencyPriceSchema:Db}=((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,Yu),{AdditionalCurrencyTierArraySchema:Xu}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(A,Tb,bu,_u),{ApiGraduatedCreditSchemaItemSchema:Fb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Ju,A,xu,Qu),{CustomerBillingControlsParamsSchema:uo}=((e,t,n,r,i,o,a,s)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:n,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:r,description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:t({schema:i,description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:t({schema:o,description:"List of usage alert configurations per feature."}),overage_allowed:t({schema:a,description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})}).check(s)}))(A,fh,wb,$a,Ha,Wa,Na,kb),{CreditSchemaItemSchema:Ub}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(A,jb,Cb),{PriceTierSchema:Mb}=((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,$h,Xu),{PlanBillingControlsParamsSchema:Lb}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(r=>{let i=t({usageAlerts:r.value.usage_alerts??[],usageLimitLists:[r.value.usage_limits??[]]});for(let{index:o,usageAlert:a}of i)r.issues.push({code:"custom",message:`No usage limit on this plan matches the usage_limit alert for feature ${a.feature_id}`,input:a,path:["usage_alerts",o,"basis"]})})}))(uo,vb),{AdditionalCurrencyPriceArraySchema:ci}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(A,Db,bu,_u),{ApiUsageTierWithCurrenciesSchema:el}=((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,to,Xu),{ApiCreditSchemaItemSchema:Bb}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(A,Fb,Rb),{FeatureConfigOverrideSchema:tl}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(A,Ub,db),{ProductItemConfigSchema:qb}=((e,t,n,r,i,o,a)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:o.nullish(),feature_override:a.nullish()})}))(A,Ou,ro,io,Pu,co,tl),{BasePriceParamsSchema:lo}=((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."})}))(eb,oi,A,ci),{PlanItemPriceParamsSchema:Vb}=((e,t,n,r,i,o,a)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(o).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:a,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(A,ci,el,ai,kn,no,Fu),{ApiFeatureOverrideSchema:nl}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(A,Bb,hb),{ApiPlanItemV1Schema:$b}=((e,t,n,r,i,o,a,s,c,u,l,d,p,g,f,h,v)=>({ApiPlanItemV1Schema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature this item configures."}),feature:t.optional().meta({description:"The full feature object if expanded."}),included:e.number().meta({description:"Number of free units included. For consumable features, balance resets to this number each interval."}),unlimited:e.boolean().meta({description:"Whether the customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"The interval at which the feature balance resets (e.g. 'month', 'year'). For consumable features, usage resets to 0 and included units are restored."}),interval_count:e.number().optional().meta({description:"Number of intervals between resets. Defaults to 1."})}).nullable().meta({description:"Reset configuration for consumable features. Null for non-consumable features like seats where usage persists across billing cycles."}),price:e.object({amount:e.number().optional().meta({description:"Price per billing_units after included usage is consumed. Mutually exclusive with tiers."}),additional_currencies:r.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers' (tiered prices carry per-currency amounts on each tier)."}),tiers:e.array(i).optional().meta({description:"Tiered pricing configuration. Each tier's 'to' INCLUDES the included amount. Either 'tiers' or 'amount' is required."}),tier_behavior:e.enum(o).optional(),interval:e.enum(a).meta({description:"Billing interval for this price. For consumable features, should match reset.interval."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().meta({description:"Number of units per price increment. Usage is rounded UP to the nearest billing_units when billed (e.g. billing_units=100 means 101 usage rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:c,max_purchase:e.number().nullable().meta({description:"Maximum units a customer can purchase beyond included. E.g. if included=100 and max_purchase=300, customer can use up to 400 total before usage is capped. Null for no limit."}),processors:u.optional().meta({description:"Payment processors this item price is connected to. Omitted when unset."})}).nullable().meta({description:"Pricing configuration for usage beyond included units. Null if feature is entirely free."}),display:l.optional().meta({description:"Display text for showing this item in pricing pages."}),rollover:e.object({max:e.number().nullable().meta({description:"Maximum rollover units. Null for unlimited rollover."}),max_percentage:e.number().nullable().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(d).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover configuration for unused units. If set, unused included units roll over to the next period."}),proration:e.object({on_increase:e.enum(p).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(g).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry:f.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:h.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),mapping_identity:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})}).check(S=>{let R=S.value.reset?.interval,D=S.value.price?.interval,P=S.value.reset?.interval_count??1,be=S.value.price?.interval_count??1;if(R&&D&&(String(R)!==String(D)||P!==be)&&S.value.price?.billing_method!==s.Prepaid&&S.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:S.value}),S.value!==void 0&&S.value.price!==void 0&&S.value.price!==null){S.value.price.amount&&S.value.price.tiers&&S.value.price.tiers.length>0&&S.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:S.value});for(let Qe of v(S.value.price))S.issues.push({code:"custom",message:Qe,input:S.value.price})}})}))(A,qu,ii,ci,el,ai,kn,no,Fu,Bu,Da,Ua,ro,io,co,nl,Iu),{EntitlementSchema:Gb}=((e,t,n,r,i,o)=>({EntitlementSchema:e.object({id:e.string(),created_at:e.number(),internal_feature_id:e.string(),internal_product_id:e.string().nullable(),internal_reward_id:e.string().nullish(),is_custom:e.boolean().default(!1),allowance_type:e.nativeEnum(t).optional().nullable(),allowance:e.number().nullish(),interval:e.nativeEnum(n).optional().nullable(),interval_count:e.number().default(1),carry_from_previous:e.boolean().default(!1).optional(),entity_feature_id:e.string().nullish(),pooled:e.boolean().default(!1).optional(),org_id:e.string().optional(),feature_id:e.string().optional(),usage_limit:e.number().nullable().optional().default(null),expiry_duration:e.nativeEnum(r).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:o.nullish()})}))(A,Dh,wu,Su,Pu,tl),{ProductItemSchema:rl}=((e,t,n,r,i,o,a,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},e.enum(o).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(a).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(o).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(A,Lh,Bh,qu,to,qh,Vh,Mb,ci,ai,qb),{ProductV2Schema:il}=((e,t,n,r,i,o,a)=>({ProductV2Schema:e.object({internal_id:e.string().nullish(),id:e.string(),name:e.string(),description:e.string().nullish(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number().default(1),version_slug:e.string().nullable().optional(),active:e.boolean().optional(),group:e.string().nullable(),env:e.nativeEnum(t),free_trial:n.nullish(),items:e.array(r),created_at:e.number(),stripe_id:e.string().nullish(),archived:e.boolean().default(!1).nullish(),base_internal_product_id:e.string().nullish(),base_id:e.string().nullish(),config:i.partial().optional(),billing_controls:o.optional(),metadata:a.optional()})}))(A,eo,Kh,rl,so,Qa,Sr),{PlanItemParamsObjectSchema:Kb}=((e,t,n,r,i,o,a,s,c,u,l)=>({PlanItemParamsObjectSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature to configure."}),included:t.optional().meta({description:"Number of free units included. Balance resets to this each interval for consumable features."}),unlimited:e.boolean().optional().meta({description:"If true, customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:r({schema:e.number().optional(),defaultValue:1,description:"Number of intervals between resets. Defaults to 1."})}).optional().meta({description:"Reset configuration for consumable features. Omit for non-consumable features like seats."}),price:i.optional().meta({description:o}),proration:e.object({on_increase:e.enum(a).meta({description:"Billing behavior when quantity increases mid-cycle."}),on_decrease:e.enum(s).meta({description:"Credit behavior when quantity decreases mid-cycle."})}).optional().meta({description:"Proration settings for prepaid features. Controls mid-cycle quantity change billing."}),rollover:e.object({max:e.number().optional().meta({description:"Max rollover units. Omit for unlimited rollover."}),max_percentage:e.number().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(c).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover config for unused units. If set, unused included units carry over."}),expiry:u.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:l.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})})}))(A,Fa,ii,oi,Vb,uh,ro,io,Ua,co,nl),{FullProductWithoutLicensesSchema:_O}=((e,t,n,r,i,o)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(n),entitlements:t.array(r.extend({feature:i})),free_trial:o.nullish(),free_trials:t.array(o).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(Nb,A,Pb,Gb,ub,Th),{CreateProductItemParamsSchema:ol}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))(rl,Fa,A,to),{CreatePlanItemParamsV1Schema:Za}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(r=>{for(let{message:i,input:o}of t(r.value))r.issues.push({code:"custom",message:i,input:o})}).meta({title:"PlanItem",description:"Configuration for a feature item in a plan, including usage limits, pricing, and rollover settings."})}))(Kb,ib),{LicenseCustomizeSchema:al}=((e,t,n,r)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(n).optional(),remove_items:e.array(r).optional()})}))(A,lo,Za,Ba),{PlanLicenseParamsSchema:Ya}=((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,al),{UpdateProductV2ParamsSchema:yO}=((e,t,n,r,i,o,a,s,c)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:n.id}),name:e.string().refine(l=>l.length>0,{message:"name must be a non-empty string"}).optional().meta({description:n.name}),is_add_on:e.boolean().optional().meta({description:n.is_add_on}),is_default:e.boolean().optional().meta({description:n.is_default}),base_plan_id:e.string().nonempty().regex(t).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."}),description:e.string().nullish().optional().meta({description:n.description}),group:e.string().nonempty().nullable().optional().meta({description:n.group}),archived:e.boolean().optional().meta({description:n.archived}),items:e.array(r).optional(),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.nullish().meta({description:n.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata})})}))(A,ao,Eu,ol,Ya,Tu,Va,uo,Sr),{CreatePlanParamsV1Schema:zb}=((e,t,n,r,i,o,a,s,c)=>({CreatePlanParamsV1Schema:e.object({id:e.string().nonempty().regex(t).meta({description:"Unique identifier for the plan."}),group:e.string().default("").meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),name:e.string().nonempty().meta({description:"Display name of the plan."}),description:e.string().nullable().default(null).meta({description:"Optional description of the plan."}),add_on:e.boolean().default(!1).meta({description:"If true, this plan can be attached alongside other plans. Otherwise, attaching replaces existing plans in the same group."}),auto_enable:e.boolean().default(!1).meta({description:"If true, plan is automatically attached when a customer is created. Use for free tiers."}),price:n.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(r).optional().meta({description:"Feature configurations for this plan. Each item defines included units, pricing, and reset behavior."}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.optional().meta({description:"Free trial configuration. Customers can try this plan before being charged."}),config:a.optional().meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:"Arbitrary key-value metadata defined by you for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Shared across all versions of the plan."}),create_in_stripe:e.boolean().default(!0).meta({internal:!0})})}))(A,ao,lo,Za,Ya,Ga,Va,Lb,Sr),{UpdatePlanParamsV1Schema:SO}=((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."})})}))(zb,A,lo,Ga,ao),{CustomizePlanLicenseSchema:Ja}=((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,al),{CreateProductV2ParamsSchema:xO}=((e,t,n,r,i,o,a,s,c,u)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:n.id}),name:e.string().refine(d=>d.length>0,{message:"name must be a non-empty string"}).meta({description:n.name}),description:e.string().nullish().meta({description:n.description}),is_add_on:e.boolean().default(!1).meta({description:n.is_add_on}),is_default:e.boolean().default(!1).meta({description:n.is_default}),group:e.string().nullable().default("").meta({description:n.group}),items:e.array(r).optional().meta({description:n.items}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:o.nullish().default(null).meta({description:n.free_trial}),config:a.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata}),create_in_stripe:e.boolean().optional().meta({internal:!0}),archived:e.boolean().optional().meta({internal:!0}),base_internal_product_id:e.string().nullable().optional().meta({internal:!0})}).meta({examples:[u]})}))(A,ao,Eu,ol,Ya,Tu,Va,uo,Sr,Gh),{CustomizePlanV1BaseSchema:sl}=((e,t,n,r,i,o,a,s,c)=>({CustomizePlanV1BaseSchema:e.object({price:t.nullable().optional().meta({description:"Override the base price of the plan. Pass null to remove the base price."}),items:e.array(n).optional().meta({description:"Override the items in the plan (PUT-style \u2014 replaces all existing items). Mutually exclusive with add_items / remove_items / deprecated update_items."}),add_items:e.array(n).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(r).optional().meta({description:"Filters selecting items to remove from the plan."}),update_items:e.array(i).optional().meta({description:"Deprecated. Use remove_items and add_items to replace matched plan items.",internal:!0,deprecated:!0}),free_trial:o.nullable().optional().meta({description:"Override the plan's default free trial. Pass an object to set a custom trial, or null to remove the trial entirely."}),billing_controls:a.optional().meta({description:"Override the plan's billing controls (auto top-ups, spend limits, usage limits, usage alerts, overage allowed) for this customer."}),upsert_licenses:e.array(s).optional().meta({description:"License links to add or override for this customer, keyed by license_plan_id. Omitted fields inherit the plan catalog link (included defaults to 1 when the license is not in the catalog). A bare entry restores the license to pure catalog inheritance."}),remove_licenses:e.array(c).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(A,lo,Za,Ba,mh,Ga,uo,Ja,_h),{VariantCustomizeSchema:Hb}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(Wu,sl),{DiffedCustomizePlanV1Schema:vO}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(Wu,sl),{ApiPlanV1Schema:IO}=((e,t,n,r,i,o,a,s,c,u,l,d,p,g)=>({ApiPlanV1Schema:e.object({id:e.string().meta({description:"Unique identifier for the plan."}),internal_id:e.string().nullable().optional().meta({description:"Stable row id. Survives renames of plan_id and version_slug, so config files address rows by it.",internal:!0}),name:e.string().meta({description:"Display name of the plan."}),description:e.string().nullable().meta({description:"Optional description of the plan."}),group:e.string().nullable().meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),version:e.number().meta({description:"Version number of the plan. Incremented when plan configuration changes."}),version_slug:e.string().nullable().optional().meta({description:"User-facing version identity. Defaults to v{n} when the version is minted."}),active:e.boolean().optional().meta({description:"Whether this is the active version of the plan. At most one version is active."}),add_on:e.boolean().meta({description:"Whether this is an add-on plan that can be attached alongside a main plan."}),auto_enable:e.boolean().meta({description:"If true, this plan is automatically attached when a customer is created. Used for free plans."}),price:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),additional_currencies:t.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),interval:e.enum(n).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0}),display:r.optional().meta({description:"Display text for showing this price in pricing pages."}),processors:i.optional().meta({description:"Payment processors this base price is connected to. Omitted when unset."})}).nullable().meta({description:"Base recurring price for the plan. Null for free plans or usage-only plans."}),items:e.array(o).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:a.optional().meta({description:"Payment processors this plan is connected to. Omitted when unset."}),free_trial:s.optional().meta({description:"Free trial configuration. If set, new customers can try this plan before being charged."}),created_at:e.number().meta({description:"Unix timestamp (ms) when the plan was created."}),env:e.enum(c).meta({description:"Environment this plan belongs to ('sandbox' or 'live')."}),archived:e.boolean().meta({description:"Whether the plan is archived. Archived plans cannot be attached to new customers."}),config:u.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:l.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:p.optional(),base_variant_id:e.string().nullable().meta({description:"Deprecated. Use variant_details.base_plan_id instead. If this is a variant, the ID of the base plan it was created from.",deprecated:!0}),variant_details:e.object({base_plan_id:e.string().meta({description:"The ID of the base plan this variant was derived from."}),customize:g.optional().meta({description:"The customization that transforms the base plan into this variant."})}).optional().meta({description:"Details about how this variant relates to its latest base plan."})})}))(A,ci,kn,Da,Bu,$b,yb,sb,eo,so,Qa,Sr,cb,Hb);import{z as C}from"zod";var Wb=C.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),ll=C.enum(["single_use","continuous_use"]),Xa=C.record(C.string(),C.union([C.string(),C.number(),C.boolean()]).transform(String).pipe(C.string())),cl=C.string().min(1).max(64).refine(e=>!e.includes("::")),dl={credit_amount:C.number(),tier_behavior:C.never().optional(),tiers:C.never().optional()},pl={credit_amount:C.never().optional(),tier_behavior:C.literal("graduated"),tiers:C.array(C.strictObject({to:C.union([C.number(),C.literal("inf")]),credit_amount:C.number()}))},Qb=C.union([C.strictObject({match:Xa,priority:C.number().int().optional(),...dl}),C.strictObject({match:Xa,priority:C.number().int().optional(),...pl})]),Zb=C.strictObject({match:Xa,factor:C.number().positive().optional(),add:C.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),ul={metered_feature_id:C.string(),feature_amount:C.number().optional(),dimensions:C.record(cl,Qb).optional(),multipliers:C.record(cl,Zb).optional()},es=C.union([C.strictObject({...ul,...dl}),C.strictObject({...ul,...pl})]),mo=C.number().min(-100),ml=C.record(C.string(),C.strictObject({markup:mo})).nullish(),fo=C.record(C.string().regex(/.+\/.+/),C.strictObject({markup:mo.optional(),input_cost:C.number().min(0).optional(),output_cost:C.number().min(0).optional()})).nullish(),Yb=C.strictObject({default_markup:mo.optional(),provider_markups:ml,model_markups:fo}),ts=C.strictObject({schema:C.array(es).optional(),markups:Yb.optional()}),Jb=C.strictObject({filters:C.array(C.strictObject({property:C.string(),operator:C.string(),value:C.array(C.string())})),aggregate:C.strictObject({type:C.string(),property:C.string().nullable()}),usage_type:ll}),fl=C.strictObject({schema:C.array(es).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:C.boolean().optional(),usage_type:ll.default("single_use").overwrite(()=>"single_use"),default_markup:mo.optional(),provider_markups:ml}),ns=fl.safeExtend({schema:C.array(es).length(0)}),po={id:Wb,name:C.string().min(1),display:C.strictObject({singular:C.string().optional(),plural:C.string().optional()}).nullish(),event_names:C.array(C.string()).default([]),model_markups:fo,stripe_meter:C.strictObject({id:C.string(),event_name:C.string()}).nullish(),stripe_product_id:C.string().nullish()},rs=e=>C.discriminatedUnion("type",[C.strictObject({...po,...e,type:C.literal("boolean"),config:C.null()}),C.strictObject({...po,...e,type:C.literal("metered"),config:Jb}),C.strictObject({...po,...e,type:C.literal("credit_system"),config:fl}),C.strictObject({...po,...e,type:C.literal("ai_credit_system"),config:ns})]),OO=rs({}),Xb=C.strictObject({id:C.boolean(),type:C.boolean(),usage_type:C.boolean()}),e_={internal_id:C.uuid(),org_id:C.uuid(),created_at:C.number(),env:C.enum(["sandbox","live"]),archived:C.boolean(),project_id:C.uuid(),environment_id:C.uuid(),revision:C.number().int().nonnegative(),update_rules:Xb},gl=rs(e_),PO=C.strictObject({rows:C.array(gl).max(200),nextCursor:C.uuid().nullable()}),hl=C.strictObject({features:C.array(gl).max(500),limited:C.boolean()}),CO=C.union([rs({action:C.literal("save"),internal_id:C.uuid().nullable(),revision:C.number().int().nonnegative()}),C.strictObject({action:C.enum(["archive","restore","delete"]),internal_id:C.uuid(),revision:C.number().int().nonnegative()})]);import{z as xr}from"zod";var bl=xr.number().int().min(0).max(1e8),ui=xr.strictObject({kind:xr.enum(["graduated","volume"]),tiers:xr.array(xr.strictObject({upTo:xr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:bl,flatAmountMinor:bl.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>t.upTo!==null&&(n===0||t.upTo>e.tiers[n-1].upTo)),"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 is(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?ui.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let o of n.tiers){let a=o.upTo??1e4;if(n.kind==="volume"){if(t<=a){r=BigInt(t)*BigInt(o.unitAmountMinor)+BigInt(o.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,a)-i)*BigInt(o.unitAmountMinor));i=a}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function go(e){return is({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as j}from"zod";import{z as K}from"zod";import{z as mn}from"zod";import{z as t_}from"zod";var jn=["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"],W=t_.enum(jn);function Jn(e){let t=W.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function jO(e,t){let n=Jn(t),r=e.trim().match(/^(\d+)(?:\.(\d+))?$/);if(!r||(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 NO(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=Jn(t),r=String(e).padStart(n+1,"0");return n?`${r.slice(0,-n)}.${r.slice(-n)}`:r}function _l(e,t,n="en",r={}){let i=W.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**Jn(i))}import{z as In}from"zod";var MO={plans:jn,creditPacks:jn,paidSeats:jn,postpaid:jn},yl=In.partialRecord(In.enum(jn),In.number().int().min(1).max(1e8)),n_=In.strictObject({currency:In.enum(jn),automaticTax:In.boolean()}),r_=In.strictObject({projectId:In.uuid(),environmentId:In.uuid()}),LO=r_.extend({settings:n_});var i_=mn.string().regex(/^[a-z][a-z0-9_]{0,63}$/),Sl=mn.number().int().min(0).max(1e4),os=mn.object({key:i_,featureId:mn.uuid(),planVersionId:mn.uuid(),includedQuantity:Sl,maximumQuantity:Sl,unitAmountCents:mn.number().int().min(0).max(1e8),currency:W,currencyOptions:yl.optional(),stripePriceId:mn.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:mn.array(mn.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:mn.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 Oe}from"zod";import{z as mt}from"zod";import{z as He}from"zod";var ut=He.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Y=He.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),ho=He.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}),as=Y.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),xl=He.string().min(1).max(64),tn=He.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),vl=He.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Xe=He.record(xl,He.union([He.string().max(120),He.number().finite(),He.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)]))),Il=He.record(xl,He.union([He.string().max(120),He.number().finite(),He.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),vr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split("."),i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},Al=He.array(He.object({upTo:as.nullable(),cost:Y}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>t.upTo!==null&&(n===0||vr(t.upTo)>vr(e[n-1].upTo))),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),o_=He.object({key:vl,match:Il,priority:He.number().int().default(0),cost:Y.optional(),tiers:Al.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),a_=He.object({key:vl,match:Il,factor:as.optional(),add:ho.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"})),s_=He.object({units:as.default("1"),cost:Y,tiers:Al.optional(),dimensions:He.array(o_).max(12).optional(),multipliers:He.array(a_).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(a=>a.key)).size!==n.length||new Set(r.map(a=>a.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let a=0;a<n.length;a++)for(let s=a+1;s<n.length;s++){let c=n[a],u=n[s];Object.keys(c.match).length===Object.keys(u.match).length&&c.priority===u.priority&&!Object.keys(c.match).some(l=>u.match[l]!==void 0&&u.match[l]!==c.match[l])&&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(a=>a.cost),...n.flatMap(a=>[...a.cost===void 0?[]:[a.cost],...(a.tiers??[]).map(s=>s.cost)])],o=vr(e.units);for(let a of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((f,h)=>s&1<<h);if(c.some((f,h)=>c.slice(h+1).some(v=>Object.keys(f.match).some(I=>v.match[I]!==void 0&&v.match[I]!==f.match[I]))))continue;let u=vr(a),l=BigInt("1"),d=BigInt("0");for(let f=0;f<r.length;f++)s&1<<f&&(u*=vr(r[f].factor??"1"),l*=BigInt("1000000"),d+=vr(r[f].add??"0"));let p=(u+d*l)*BigInt("1000000"),g=l*o;(p<BigInt("0")||p%g!==BigInt("0")||p/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"})}}),zO=s_.safeExtend({featureKey:tn});var ss=mt.object({days:mt.number().int().min(1).max(730),cardRequired:mt.boolean(),featureAllowances:mt.record(mt.uuid(),mt.number().int().min(0).max(1e9)),creditAmounts:mt.record(mt.uuid(),Y)}).strict(),cs=mt.object({id:mt.uuid(),planVersionId:mt.uuid(),slot:mt.string(),cardRequired:mt.boolean(),status:mt.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:mt.iso.datetime().nullable(),endsAt:mt.iso.datetime().nullable(),createdAt:mt.iso.datetime()}).strict();var us=Oe.object({group:Oe.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:Oe.enum(["main","addon"]).default("main")}).strict(),c_=Oe.enum(["immediate","end_of_cycle"]),u_=Oe.enum(["attach","change","cancel","resume","cancel_change"]),wl=Oe.object({id:Oe.uuid(),subscriptionId:Oe.uuid().nullable(),targetPlanVersionId:Oe.uuid().nullable(),action:u_,timing:c_,status:Oe.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:Oe.iso.datetime().nullable(),createdAt:Oe.iso.datetime()}),l_=Oe.object({id:Oe.uuid(),planVersionId:Oe.uuid(),planId:Oe.uuid(),basePlanId:Oe.uuid().nullable(),name:Oe.string(),group:Oe.string(),kind:Oe.enum(["main","addon"]),source:Oe.enum(["subscription","assignment","license","apple","google"]),status:Oe.string(),accessEnabled:Oe.boolean(),startsAt:Oe.iso.datetime().nullable(),endsAt:Oe.iso.datetime().nullable(),cancelAtPeriodEnd:Oe.boolean(),scheduledChange:wl.nullable(),trial:cs.nullable().optional()}),XO=Oe.object({customerId:Oe.uuid(),evaluatedAt:Oe.iso.datetime(),holdings:Oe.array(l_),changes:Oe.array(wl),trials:Oe.array(cs).optional()});import{z as ls}from"zod";var ds=ls.enum(["sandbox","live"]),Fe=ls.object({projectId:ls.string().min(1),environment:ds}).strict();var fn=K.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),uP=K.record(K.string().min(1).max(80),K.union([K.string().max(500),K.number().finite(),K.boolean(),K.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),Ol=K.object({key:fn,name:K.string().trim().min(1).max(80),description:K.string().trim().max(240),type:K.enum(["boolean","metered"]),usageType:K.enum(["consumable","non_consumable"]).optional()}),lP=Ol.extend({...Fe.shape,id:K.string().min(1),archived:K.boolean(),createdAt:K.iso.datetime()}),Pl=K.object({amountCents:K.number().int().min(0).max(1e8),currency:W,interval:K.enum(["free","month","year"]),currencyOptions:K.partialRecord(W,K.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C"),d_=K.object({featureId:K.string().min(1),allowance:K.number().int().min(0).max(1e9).nullable(),pooled:K.boolean().optional()}),Cl=K.object({name:K.string().trim().min(1).max(80),description:K.string().trim().max(240),price:Pl,membership:us.optional(),trial:ss.nullable().optional(),licenses:K.array(os).max(20).optional(),items:K.array(d_).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")}),dP=K.object({key:fn,config:Cl}),pP=Fe.extend({id:K.string().min(1),key:fn,draft:Cl,status:K.enum(["draft","published","archived"]),publishedVersionId:K.string().nullable(),isDefault:K.boolean(),updatedAt:K.iso.datetime()}),p_=Ol.pick({key:!0,name:!0,type:!0}).extend({featureId:K.string(),allowance:K.number().int().min(0).max(1e9).nullable(),pooled:K.boolean().optional()}).refine(e=>e.type==="boolean"?e.allowance===null:e.allowance!==null,"\u5F00\u5173\u578B\u65E0\u6570\u91CF\uFF0C\u8BA1\u91CF\u578B\u5FC5\u987B\u6307\u5B9A\u989D\u5EA6"),El=Fe.extend({id:K.string().min(1),planId:K.string().min(1),variant:K.object({basePlanId:K.uuid(),baseVersionId:K.uuid()}).nullable(),version:K.number().int().positive(),name:K.string(),description:K.string(),price:Pl,membership:us.optional(),trial:ss.nullable().optional(),licenses:K.array(os).optional(),items:K.array(p_),publishedAt:K.iso.datetime()}).strict(),ps=K.object({startsAt:K.iso.datetime(),endsAt:K.iso.datetime().nullable()}).refine(e=>e.endsAt===null||Date.parse(e.endsAt)>Date.parse(e.startsAt),"\u5230\u671F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u751F\u6548\u65F6\u95F4"),mP=Fe.extend({id:K.string(),customerId:K.string(),planVersionId:K.string(),assignedAt:K.iso.datetime(),source:K.literal("demo"),validity:ps.nullable().default(null),used:K.record(K.string(),K.number().int().min(0))}),fP=Fe.extend({id:K.string(),customerId:K.string(),at:K.iso.datetime(),message:K.string()});import{z as b}from"zod";import{z as se}from"zod";import{z as w}from"zod";var _e=w.json().superRefine((e,t)=>{let n=0;function r(i,o){if(++n>1e4||o>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(a=>r(a,o+1));else if(i&&typeof i=="object")for(let[a,s]of Object.entries(i))(a.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(a)||["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,o+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Ut=w.record(w.string().min(1).max(128),_e).superRefine((e,t)=>{(!_e.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),m_=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),xt=Ut.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r)){if(i==="$savedGroup"&&!w.strictObject({id:w.uuid(),attributeKey:w.string().min(1).max(128).optional()}).safeParse(o).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(a=>["__proto__","prototype","constructor"].includes(a))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!m_.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof o=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(o)||[...o.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(a=>Number(a[1])>255||Number(a[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(o.replace(/\\u([0-9a-f]{4})/gi,(a,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(o)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(o)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),bo=w.discriminatedUnion("type",[w.strictObject({type:w.literal("condition"),condition:xt}),w.strictObject({type:w.literal("list"),attributeKey:w.string().min(1).max(128),values:w.array(w.union([w.string(),w.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function li(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.id=="string"?t.add(o.id):["$inGroup","$notInGroup"].includes(i)&&typeof o=="string"?t.add(o):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(o)}return n(e),[...t]}var f_=w.record(w.uuid(),bo).superRefine((e,t)=>{let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(o),a.type==="condition"&&li(a.condition).forEach(i),n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),fs=w.tuple([w.number().min(0).max(1),w.number().min(0).max(1)]).refine(([e,t])=>e<=t),Tl=w.strictObject({attribute:w.string().optional(),seed:w.string().min(1),hashVersion:w.literal(2),ranges:w.array(fs).min(1).max(100)}),g_=w.strictObject({id:w.string().min(1).max(128),condition:xt,gate:w.boolean().optional()}),ms={id:w.string().max(128).optional(),condition:xt.optional(),parentConditions:w.array(g_).max(50).optional(),filters:w.array(Tl).max(20).optional()},h_=w.union([w.strictObject({...ms}),w.strictObject({...ms,force:_e,coverage:w.number().min(0).max(1).optional(),range:fs.optional(),seed:w.string().min(1).optional(),hashAttribute:w.string().optional(),hashVersion:w.literal(2).optional()}),w.strictObject({...ms,type:w.literal("experiment-ref"),experimentId:w.uuid(),values:w.record(w.string().min(1),_e),meta:w.record(w.string().min(1),w.strictObject({passthrough:w.boolean()})).optional()})]),b_=w.strictObject({defaultValue:_e,rules:w.array(h_).max(100)}),Rl=w.record(w.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),b_).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(o){if(n.has(o)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${o}`});return}if(r.has(o))return;let a=e[o];if(!a){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${o}`});return}n.add(o);for(let s of a.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(o),r.add(o)}Object.keys(e).forEach(i)}),__=w.strictObject({name:w.string().max(80),reason:w.string().max(500),dateStarted:w.iso.datetime({offset:!0}),dateEnded:w.iso.datetime({offset:!0}).nullable(),coverage:w.number().min(0).max(1),variationWeights:w.array(w.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:xt,savedGroups:w.array(w.strictObject({match:w.enum(["any","all","none"]),ids:w.array(w.uuid()).min(1)})).max(50),namespace:w.strictObject({id:w.uuid(),ranges:w.array(fs).min(1)}).nullable(),seed:w.string().min(1).max(128)}),Ir=w.strictObject({key:w.string().min(1).max(128),name:w.string().min(1).max(80),hypothesis:w.string().max(2e3),status:w.enum(["draft","running","stopped"]),hashAttribute:w.string().min(1).max(128),fallbackAttribute:w.string().max(128).nullable(),hashVersion:w.literal(2),disableStickyBucketing:w.boolean(),bucketVersion:w.number().int().min(0).max(1e3),minBucketVersion:w.number().int().min(0).max(1e3),variations:w.array(w.strictObject({id:w.string().min(1),key:w.string().min(1),name:w.string().max(80),description:w.string().max(500)})).min(2).max(20),phases:w.array(__).min(1).max(100),releasedVariationId:w.string().nullable(),excludeFromPayload:w.boolean(),statusSchedule:w.strictObject({startAt:w.iso.datetime({offset:!0}).nullable(),stopAt:w.iso.datetime({offset:!0}).nullable(),stopAfter:w.strictObject({value:w.number().int().positive().max(36500),unit:w.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>r>0&&(Date.parse(n.dateStarted)<Date.parse(e.phases[r-1].dateStarted)||!e.phases[r-1].dateEnded||Date.parse(e.phases[r-1].dateEnded)>Date.parse(n.dateStarted)))||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],o,a)=>r>=i||a.some(([s,c],u)=>u!==o&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});function xP(e,t,n=Date.now()){return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{defaultValue:i.defaultValue,rules:i.rules.flatMap(o=>{if(!("experimentId"in o))return[{...o,hashVersion:2}];let a=t[o.experimentId];if(!a)throw new Error(`Missing experiment: ${o.experimentId}`);let s=a.phases[a.phases.length-1],c=a.statusSchedule?.startAt?Date.parse(a.statusSchedule.startAt):null,u=kl(a),l=a.status!=="stopped"&&(a.status==="running"||c!==null&&n>=c)&&(c===null||n>=c)&&(u===null||n<u),{type:d,experimentId:p,values:g,meta:f,...h}=o;if(a.variations.some(S=>!Object.hasOwn(g,S.key))||Object.keys(g).length!==a.variations.length||Object.keys(f??{}).some(S=>!a.variations.some(R=>R.key===S)))throw new Error("Every variation needs a Feature value");let v={$and:[s.condition,...h.condition?[h.condition]:[],...s.savedGroups.map(S=>{let R=S.ids.map(D=>({$savedGroup:{id:D}}));return S.match==="all"?{$and:R}:S.match==="none"?{$nor:R}:{$or:R}})]},I=a.variations.find(S=>S.id===a.releasedVariationId);return I&&!a.excludeFromPayload?f?.[I.key]?.passthrough?[{...h,condition:v}]:[{...h,condition:v,force:g[I.key]}]:[{...h,condition:v,key:a.key,variations:a.variations.map(S=>g[S.key]),meta:a.variations.map(S=>({key:S.key,name:S.name,...f?.[S.key]})),weights:s.variationWeights,coverage:l?s.coverage:0,seed:s.seed,hashVersion:2,hashAttribute:a.hashAttribute,fallbackAttribute:a.fallbackAttribute??void 0,disableStickyBucketing:!l||a.disableStickyBucketing,bucketVersion:a.bucketVersion,minBucketVersion:a.minBucketVersion,filters:[...h.filters??[],...a.filters??[]]}]})}]))}function kl(e){if(e.statusSchedule?.stopAt)return Date.parse(e.statusSchedule.stopAt);let t=e.statusSchedule?.stopAfter;return!t||e.status==="draft"&&!e.statusSchedule?.startAt?null:Date.parse(e.statusSchedule?.startAt??e.phases[e.phases.length-1].dateStarted)+t.value*(t.unit==="days"?864e5:36e5)}function vP(e,t=Date.now()){let n=Object.values(e).filter(r=>r.status!=="stopped"&&!(r.releasedVariationId&&!r.excludeFromPayload)).flatMap(r=>[r.statusSchedule?.startAt?Date.parse(r.statusSchedule.startAt):null,kl(r)]).filter(r=>r!==null&&r>t);return n.length?new Date(Math.min(...n)).toISOString():null}var y_=Ir.safeExtend({filters:w.array(Tl).optional()}),S_=w.strictObject({experiments:w.record(w.uuid(),y_),savedGroups:f_}),x_=w.strictObject({attributeName:w.string(),attributeValue:w.string(),assignments:w.record(w.string(),w.string())}),IP=w.strictObject({snapshot:S_,attributes:Ut,results:Ut,stickyBucketAssignmentDocs:w.record(w.string(),x_)}),AP=w.strictObject({variantKey:w.string().nullable(),bucketVersion:w.number().int().min(0),source:w.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:w.number().min(0).max(1).optional(),stickyBucketUsed:w.boolean().optional(),hashUsed:w.boolean().optional()});import{z as v_}from"zod";var Nl=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,nn=v_.string().max(16).regex(Nl,"\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 Xn(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),o=[n,r,i].filter(Boolean).join("-");return Nl.test(o)?o:null}catch{return null}}var I_=new Set(["TW","HK","MO"]);function jl(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,o=n?.length===4?r:n;return i?`zh-${i}`:o&&I_.has(o)?"zh-Hant":"zh-Hans"}function _o(e,t,n){let r=t.map(i=>({code:nn.parse(i),normalized:i}));for(let i of e){let o=Xn(i);if(!o)continue;let a=r.find(u=>u.normalized===o);if(a)return a.code;let s=jl(o),c=r.filter(u=>jl(u.normalized)===s);if(c.length>0)return(c.find(u=>!u.normalized.includes("-")||u.normalized===s)??c[0]).code}return n}var A_=[{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 PP(e){return A_.find(t=>t.code===e)?.label??e}var gs={"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"}},RP=["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=Xn(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(i=>["TW","HK","MO"].includes(i))?"zh-Hant":"zh-Hans":n[0];return gs[r]?{locale:t,copy:gs[r]}:{locale:"en",copy:gs.en}}function w_(e,t,n="zh-CN"){let r=Jn(t);return _l(e,t,hs(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function O_(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):w_(e.amountOffCents,e.currency,n)}var Dl={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 Fl(e,t="zh-CN",n="month"){let r=hs(t),i=O_(e.discount,r.locale),o=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",a=r.locale.split("-")[0],s=a==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":a,c=e.duration.type==="repeating"&&n!=="month"?Dl[s]??Dl.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],u=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return c.replace("{discount}",i).replace("{months}",o).replace("{period}",u)}var UP=se.enum(["draft","active","paused","archived"]),Ar=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:W}).strict()]),rn=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()]),Ul=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()]),P_=se.strictObject({firstPurchaseOnly:se.boolean(),condition:xt}),Ml=se.object({name:se.string().trim().min(1).max(80),description:se.string().max(500),discount:Ar,duration:rn,appliesTo:Ul,eligibility:P_,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"]}),MP=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:W.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function LP(){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 bs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function BP(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return bs(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),bs(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),bs(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 C_=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function qP(e,t="zh-CN"){return Fl(e,t)}function VP(e){return C_(e)}function $P(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var di=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:Ar,duration:rn,appliesTo:Ul}).strict()}).strict(),yo=se.enum(["inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var $l=b.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),pi=b.string().regex(/^(0|[1-9]\d{0,14})$/),wr=b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),E_=b.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),mi=E_,An=Y.refine(e=>/[1-9]/.test(e)),vt=b.iso.datetime({offset:!0}),er=e=>{let[t,n=""]=e.split(".");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},T_=b.array(b.object({upTo:An.nullable(),unitAmountMinor:$l,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)=>t.upTo!==null&&(n===0||er(t.upTo)>er(e[n-1].upTo)))}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),R_=b.discriminatedUnion("kind",[b.object({kind:b.literal("flat"),units:An,unitAmountMinor:$l}).strict(),b.object({kind:b.enum(["graduated","volume"]),units:An,tiers:T_}).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"),k_=b.strictObject({interval:b.enum(["month","year"]),count:b.number().int().min(1).max(12),anchor:b.enum(["membership","calendar"])}),Nn=b.object({currency:W,pricing:R_,billingCycle:k_.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function Gl(e){return e.pricing.kind==="flat"&&er(e.pricing.units)>0n&&er(e.pricing.unitAmountMinor)===er(e.pricing.units)*BigInt(10**Jn(e.currency))}var Ll={requestId:b.uuid(),productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:W},Kl=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)}),zl=b.discriminatedUnion("kind",[b.object({...Ll,kind:b.literal("auto_topup"),threshold:ho,quantity:An.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Kl.optional()}).strict(),b.object({...Ll,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:mi,maxOutstandingMinor:mi}).strict()]),Bl={productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:W},Hl=b.discriminatedUnion("kind",[b.object({...Bl,kind:b.literal("auto_topup"),threshold:ho,quantity:An.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Kl.optional(),purchaseAmountMinor:mi,purchaseUnits:An}).strict(),b.object({...Bl,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:mi,maxOutstandingMinor:mi,cashPrice:Nn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),So=b.object({id:b.uuid(),terms:Hl,status:b.enum(["prepared","active","revoked","blocked"]),createdAt:vt,acceptedAt:vt.nullable(),effectiveAt:vt.nullable(),revokedAt:vt.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"),Wl=b.object({authorizationId:b.uuid(),terms:Hl,setupUrl:b.url().nullable()}).strict(),Ql=b.object({authorizationId:b.uuid(),accepted:b.literal(!0)}).strict(),Zl=b.object({authorizationId:b.uuid(),requestId:b.uuid()}).strict(),Yl=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),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(An).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>n===0||t>e.thresholds[n-1])&&(e.includedThresholds??[]).every((t,n,r)=>n===0||t>r[n-1])&&(e.absoluteThresholds??[]).every((t,n,r)=>n===0||er(t)>er(r[n-1])),"Notification thresholds must increase"),j_=Yl.safeExtend({requestId:b.uuid()}),ql={control:b.literal("overage"),requestId:b.uuid(),internal_feature_id:b.uuid(),entityId:b.uuid().nullable()},N_=b.discriminatedUnion("action",[b.strictObject({...ql,action:b.literal("set"),allowed:b.boolean().nullable(),overageLimit:Y.nullable(),skipOverageBilling:b.boolean()}),b.strictObject({...ql,action:b.literal("remove")})]),Jl=b.union([j_,N_]),D_=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:vt,endsAt:vt,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()}),F_=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),basis:b.enum(["usage","credits"]),filter:Xe.optional(),startsAt:vt,endsAt:vt,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(An).max(8).optional(),notifiedAbsoluteThresholds:b.array(An).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"),U_=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:vt.nullable(),attemptCount:b.number().int().nonnegative(),failedAttemptCount:b.number().int().nonnegative(),suspendedAt:vt.nullable(),nextAttemptAt:vt.nullable(),failureReason:b.string().min(1).max(240).nullable()}).strict(),Xl=b.object({internal_feature_id:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),_s=b.object({authorizations:b.array(So).max(100),limits:b.array(Yl).max(100),overages:b.array(D_).max(100).optional(),windows:b.array(F_).max(200),autoTopups:b.array(U_).max(100),limited:b.boolean()}).strict(),M_=b.object({id:b.uuid(),internal_feature_id:b.uuid(),productVersionId:b.uuid(),authorizationId:b.uuid(),entityId:b.uuid().nullable(),units:Y,amountMinor:wr,cashPrice:Nn}).strict(),fi=b.object({id:b.uuid(),sourceKind:b.enum(["product","usage"]),providerInvoiceId:b.string().min(1).max(240).nullable(),status:b.enum(["accruing","open","pending","paid","failed","void"]),currency:W,startsAt:vt.nullable(),endsAt:vt.nullable(),amountMinor:pi,grossAmountMinor:pi,discountMinor:pi,paidAmountMinor:pi,refundedAmountMinor:pi,createdAt:vt,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:vt.nullable()}).strict().nullable(),lines:b.array(M_).max(100),linesLimited:b.boolean()}).strict(),ed=b.object({invoiceId:b.uuid(),accepted:b.literal(!0)}).strict(),td=b.object({after:b.uuid().nullable(),limit:b.number().int().min(1).max(100)}).strict(),nd=b.object({rows:b.array(fi).max(100),nextCursor:b.uuid().nullable()}).strict(),Vl=b.strictObject({id:b.string(),coupon:b.string(),start:b.number().nonnegative(),end:b.number().nullable()}),L_=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(Vl).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:Vl.optional()})).max(20)})).max(100)}),rd=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")}),id=b.strictObject({membershipId:b.uuid(),operationId:b.uuid(),status:b.enum(["pending","effective"]),execution:L_.nullable(),grants:b.array(b.strictObject({id:b.uuid(),couponId:b.uuid(),name:b.string(),discount:Ar,duration:rn,startedAt:vt.nullable()})).max(20)});import{z as gi}from"zod";var hi=gi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),bi=gi.number().int().min(1).max(1e3),tr=gi.object({cap:Y.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:gi.number().positive().max(1e4).nullable(),cycles:gi.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:fn,name:j.string().trim().min(1).max(80),description:j.string().trim().max(240)},od=Y.refine(e=>/[1-9]/.test(e)),xo=j.array(j.object({currency:W,amountMinor:j.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=j.strictObject({units:od,prices:j.array(j.strictObject({currency:W,amountMinor:j.number().int().min(0).max(1e8),pricing:ui.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:j.number().int().min(0).max(1e4),maximumQuantity:j.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&&is(t,n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),B_=j.discriminatedUnion("kind",[j.object({kind:j.literal("access"),internal_feature_id:j.uuid()}).strict(),j.object({kind:j.literal("metered"),internal_feature_id:j.uuid(),usageUnit:j.enum(["count","micro_usd"]),amount:Y.nullable(),reset:hi,resetCount:bi,pooled:j.boolean(),rollover:tr.nullable().optional(),cashPrice:Nn.nullable().optional(),prepaidPrice:Ss.optional(),feature_override:ts.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"),j.object({kind:j.literal("credit"),internal_feature_id:j.uuid(),amount:Y,reset:hi,resetCount:bi,rollover:tr.nullable(),pooled:j.boolean(),feature_override:ts.nullish(),cashPrice:Nn.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&Gl(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=j.array(B_).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),ad=j.object({days:j.number().int().min(1).max(730),cardRequired:j.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"),sd=j.object({key:fn,internal_feature_id:j.uuid(),productVersionId:j.uuid(),includedQuantity:j.number().int().min(0).max(1e4),maximumQuantity:j.number().int().min(0).max(1e4),prices:xo,pooled_internal_feature_ids:j.array(j.uuid()).max(100),requireAssignment:j.boolean()}).strict().refine(e=>e.maximumQuantity>=e.includedQuantity,"Capacity cannot be less than included seats").refine(e=>new Set(e.pooled_internal_feature_ids).size===e.pooled_internal_feature_ids.length,"Shared entitlements must be unique"),_i=j.discriminatedUnion("kind",[j.object({...ys,kind:j.literal("membership"),groupId:j.uuid(),membershipType:j.enum(["main","addon"]),interval:j.enum(["free","week","month","year","one_time"]),intervalCount:j.number().int().min(1).max(156).optional(),prices:xo,allowances:xs,trial:ad.nullable(),licenses:j.array(sd).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"),j.object({...ys,kind:j.literal("topup"),interval:j.literal("one_time"),prices:xo,internal_feature_id:j.uuid(),amount:od,expiresDays:j.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),vo=j.object({interval:j.enum(["free","week","month","year","one_time"]).optional(),intervalCount:j.number().int().min(1).max(156).nullable().optional(),prices:xo.optional(),allowances:j.object({upsert:xs,remove:j.array(j.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:ad.nullable().optional(),licenses:j.array(sd).max(20).optional()}).strict(),cd=j.object({...ys,kind:j.literal("variant"),baseProductVersionId:j.uuid(),overrides:vo}).strict(),cC=j.union([_i,cd]);function uC(e,t){let n=cd.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...o}=n.overrides,a=new Map(e.allowances.map(c=>[c.internal_feature_id,c]));for(let c of r?.remove??[])if(!a.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])a.delete(c.internal_feature_id);for(let c of r?.upsert??[])a.set(c.internal_feature_id,c);let s={...structuredClone(e),...structuredClone(o),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...a.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),_i.parse(s)}function lC(e,t){if(e.kind!=="membership"||t.kind!=="membership"||e.groupId!==t.groupId||e.membershipType!==t.membershipType)throw new Error("Variant group and membership type must match the base");let n={};for(let s of["interval","intervalCount","prices","trial","licenses"])(s==="intervalCount"&&["week","month","year"].includes(t.interval)?(e.intervalCount??1)===(t.intervalCount??1):JSON.stringify(e[s])===JSON.stringify(t[s]))||Object.assign(n,{[s]:s==="intervalCount"&&t[s]===void 0?null:structuredClone(t[s])});let r=new Map(e.allowances.map(s=>[s.internal_feature_id,s])),i=new Set(t.allowances.map(s=>s.internal_feature_id)),o=t.allowances.filter(s=>JSON.stringify(r.get(s.internal_feature_id))!==JSON.stringify(s)),a=e.allowances.filter(s=>!i.has(s.internal_feature_id)).map(s=>s.internal_feature_id);return(o.length||a.length)&&(n.allowances={upsert:o,remove:a}),vo.parse(n)}var dC=j.object({products:j.array(j.object({id:j.uuid(),productId:j.string().min(1),name:j.string(),kind:j.enum(["membership","topup"]),version:j.number().int().positive()}).strict()).max(500),limited:j.boolean()}).strict(),q_=il.and(j.object({internal_id:j.uuid(),revision:j.number().int().nonnegative(),licenses:j.array(Ja)})),pC=j.strictObject({rows:j.array(q_).max(200),nextCursor:j.uuid().nullable()}),mC=j.object({groups:j.array(j.object({id:j.uuid(),name:j.string(),defaultProductVersionId:j.uuid().nullable()}).strict()).max(500),features:hl.shape.features,products:j.array(j.object({id:j.uuid(),productId:j.uuid(),version:j.number().int().positive(),configuration:_i,baseProductVersionId:j.uuid().nullable()}).strict()).max(500),limited:j.boolean()}).strict();function vs(e,t,n){let r=a=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(a))throw new Error("Invalid quantity");let[s,c=""]=a.split(".");return BigInt(s)*1000000n+BigInt(c.padEnd(6,"0"))};if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let i=r(e)+r(t)*BigInt(n);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let o=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(o?"."+o:"")}var bC=on.object({requestId:on.uuid(),baseProductVersionId:on.uuid(),name:on.string().trim().min(1).max(80),description:on.string().trim().max(240),overrides:vo}).strict(),_C=on.object({productId:on.uuid(),productVersionId:on.uuid(),bindingStatus:on.enum(["ready","requires_binding"]),missingCurrencies:on.array(on.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();import{z as ot}from"zod";var yi=ot.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"]),xC=ot.enum([...yi.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),vC=ot.enum([...yi.options,"stale_revision"]),V_=ot.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"]),$_=ot.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),ud={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 IC(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 G_(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=yi.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:ud[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function AC(e,t){let n=yi.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):ud[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)}function K_(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 ld=ot.object({retryable:ot.boolean(),recovery:V_,reason:$_.optional(),retryAfterSeconds:ot.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),z_=ot.object({requestId:ot.uuid().optional(),error:ot.object({code:ot.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:ot.string(),...ld.partial().shape})}),wC=ot.object({error:z_.shape.error.extend({requestId:ot.uuid().optional()})}),OC=ot.object({error:ot.string(),code:ot.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:ot.uuid(),...ld.shape});function PC(e,t,n={}){let r=G_(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,o=r.retryable&&n.retryable!==!1&&i!=="recover_operation",a=o?K_(n.retryAfter??null):void 0;return{...r,retryable:o,recovery:i,...a===void 0?{}:{retryAfterSeconds:a},...n.reason?{reason:n.reason}:{}}}var pd="X-Indiana-Protocol",H_="X-Indiana-SDK-Version",EC="X-Indiana-Supported-Protocols",dd={stableSupportMonths:12,retirementNoticeDays:180,documentation:"/docs/release-notes#support-policy"},W_={current:"0.4",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:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]}]},md=/^(?:0\.(?:0|[1-9]\d*)|[1-9]\d*)$/,Q_=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function fd(e){let t=Q_.exec(e);return t?t[1]==="0"?`0.${t[2]}`:t[1]:null}var As=e=>/^[1-9]\d*$/.test(e);function Z_(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 TC(e){let t=[],n=new Set;for(let r of e.releases){let i=r.protocol;(!md.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 o=new Set;for(let a of r.baselines)(fd(a.version)!==i||o.has(a.version))&&t.push(`${i}: invalid/duplicate baseline ${a.version}`),o.add(a.version),(!/^sha512-[A-Za-z0-9+/]{86}==$/.test(a.integrity)||!/^[a-f0-9]{64}$/.test(a.sha256))&&t.push(`${i}: unpinned baseline ${a.version}`);if(As(i)&&r.sunsetAt!==null){let a=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];a?Date.parse(r.sunsetAt)<Z_(a.firstReleasedAt,dd.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)<dd.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 nr=class extends Error{constructor(n,r,i=400){super(r);this.code=n;this.status=i}code;status};function RC(e,t=W_,n=Date.now()){let r=e.get(pd)??t.unversioned;if(!md.test(r))throw new nr("INVALID_PROTOCOL_VERSION","Invalid Indiana protocol version");let i=t.releases.find(a=>a.protocol===r);if(!i)throw new nr("UNSUPPORTED_PROTOCOL_VERSION","Indiana protocol version is not supported");if(!As(r)&&r!==t.current)throw new nr("UNSUPPORTED_PROTOCOL_VERSION","Only the current pre-1.0 Indiana protocol is supported");if(i.sunsetAt&&n>=Date.parse(i.sunsetAt))throw new nr("PROTOCOL_RETIRED","Indiana protocol version has retired; follow the published migration notice",410);let o=e.get(H_);if(o!==null&&fd(o)!==r)throw new nr("INVALID_PROTOCOL_VERSION","SDK version and protocol version do not match");return i}function kC(e,t=Date.now()){let n={[pd]: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 Ke}from"zod";var Y_=Ke.object({minAccountAgeDays:Ke.number().int().min(0).max(3650),paymentStatus:Ke.enum(["all","unpaid","paid"])}),J_=Ke.object({percentOff:Ke.number().int().min(1).max(100),redemptionWindowHours:Ke.number().int().min(1).max(2160)}),X_=Ke.object({title:Ke.string().trim().min(1).max(80),description:Ke.string().trim().min(1).max(240),buttonLabel:Ke.string().trim().min(1).max(30)}),ey=Ke.object({name:Ke.string().trim().min(1).max(80),audience:Y_,offer:J_,popup:X_}),FC=ey.extend({id:Ke.string().min(1),projectId:Ke.string().min(1),environment:ds,status:Ke.enum(["draft","active","paused"]),updatedAt:Ke.iso.datetime()}),UC=Fe.extend({id:Ke.string().min(1),externalUserId:Ke.string().min(1),name:Ke.string().min(1),email:Ke.union([Ke.email(),Ke.literal("")]),createdAt:Ke.iso.datetime(),paymentStatus:Ke.enum(["unpaid","paid"]),stripeCustomerId:Ke.string().nullable()});import{z as Dn}from"zod";var gd=Dn.strictObject({itemKey:Dn.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:Dn.uuid(),includedAmount:Dn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Dn.number().int().min(0).max(1e4),terms:Ss,pricing:ui.optional(),unitAmountMinor:Dn.number().int().min(0).max(1e8),productId:Dn.string().min(1).max(255).nullable(),priceId:Dn.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),go(e)}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z}from"zod";var ws=z.object({id:z.uuid(),productVersionId:z.uuid(),connectionId:z.uuid(),currency:z.string().regex(/^[A-Z]{3}$/),productId:z.string().min(1).max(255),priceId:z.string().min(1).max(255),enabled:z.boolean()}).strict(),KC=z.object({productId:z.uuid(),name:z.string(),environment:z.enum(["sandbox","live"]),versions:z.array(z.object({id:z.uuid(),version:z.number().int().positive(),configuration:_i}).strict()),connections:z.array(z.object({id:z.uuid(),accountId:z.string()}).strict()),bindings:z.array(ws),seatBindings:z.array(ws.extend({key:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:z.array(ws.extend({internal_feature_id:z.uuid()}).strict()),limited:z.boolean()}).strict(),zC=z.discriminatedUnion("action",[z.strictObject({action:z.literal("bind_feature"),requestId:z.uuid(),productId:z.uuid(),productVersionId:z.uuid(),connectionId:z.uuid(),currency:z.string().regex(/^[A-Z]{3}$/),internal_feature_id:z.uuid(),priceId:z.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}),z.strictObject({action:z.literal("disable_feature"),productId:z.uuid(),bindingId:z.uuid()}),z.object({action:z.literal("bind_seat"),requestId:z.uuid(),productId:z.uuid(),productVersionId:z.uuid(),connectionId:z.uuid(),currency:z.string().regex(/^[A-Z]{3}$/),key:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),priceId:z.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),z.object({action:z.literal("disable_seat"),productId:z.uuid(),bindingId:z.uuid()}).strict(),z.object({action:z.literal("bind"),requestId:z.uuid(),productId:z.uuid(),productVersionId:z.uuid(),connectionId:z.uuid(),currency:z.string().regex(/^[A-Z]{3}$/),priceId:z.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),z.object({action:z.literal("disable"),productId:z.uuid(),bindingId:z.uuid()}).strict()]);import{z as he}from"zod";var hd=he.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),bd=he.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Si=he.enum(["apple","google"]),ty=he.strictObject({id:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:Si,provider:Si,namespace:he.string().min(1).max(255),currency:W,productId:hd,basePlanId:bd.nullable(),enabled:he.boolean()}),ZC=he.strictObject({productId:he.uuid(),publicId:he.string().min(1),name:he.string().min(1).max(80),environment:he.enum(["sandbox","live"]),versions:he.array(he.strictObject({id:he.uuid(),version:he.number().int().positive(),prices:he.array(he.strictObject({id:he.uuid(),currency:W,amount:he.number().nonnegative(),interval:he.string().nullable()})).max(50),recurring:he.boolean()})).max(100),connections:he.array(he.strictObject({id:Si,provider:Si,applicationId:he.string().min(1).max(255)})).max(2),bindings:he.array(ty).max(500),limited:he.boolean()}),YC=he.discriminatedUnion("action",[he.strictObject({action:he.literal("bind"),requestId:he.uuid(),productId:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:Si,storeProductId:hd,basePlanId:bd.nullable()}),he.strictObject({action:he.literal("disable"),productId:he.uuid(),bindingId:he.uuid()})]);import{z as G}from"zod";var rr=Y.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),xi=G.string().min(1).max(120),Io=G.enum(["cap","overflow"]),Mt=(e,t)=>{let[n,r=""]=e.split(".");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},vi=e=>{try{return e()}catch{return!1}},Ii=G.discriminatedUnion("operation",[G.object({operation:G.literal("quote"),overageBehavior:Io.optional(),internal_feature_id:G.uuid(),entityId:G.uuid().optional(),quantity:rr,properties:Xe}).strict(),G.object({operation:G.literal("consume"),overageBehavior:Io.optional(),occurredAt:G.iso.datetime({offset:!0}).optional(),internal_feature_id:G.uuid(),entityId:G.uuid().optional(),quantity:Y,properties:Xe,idempotencyKey:xi}).strict(),G.object({operation:G.literal("reserve"),occurredAt:G.iso.datetime({offset:!0}).optional(),internal_feature_id:G.uuid(),entityId:G.uuid().optional(),quantity:rr,properties:Xe,idempotencyKey:xi,expiresInSeconds:G.number().int().min(1).max(86400)}).strict(),G.object({operation:G.literal("confirm"),operationId:G.uuid(),quantity:rr,properties:Xe.optional(),idempotencyKey:xi}).strict(),G.object({operation:G.literal("refund"),operationId:G.uuid(),quantity:rr,idempotencyKey:xi}).strict(),G.object({operation:G.literal("release"),operationId:G.uuid(),idempotencyKey:xi}).strict()]),Os=G.object({internal_credit_feature_id:G.uuid().nullable(),internal_metered_feature_id:G.uuid(),dimension:G.string().min(1).max(64),counterKey:G.string().min(1).max(240),cycleStart:G.iso.datetime({offset:!0}),unitCost:Y,units:rr,amount:ut,tier:G.number().int().min(1).max(12).nullable()}).strict(),ir=G.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function _d(e,t){let n=e.reduce((r,i)=>r+Mt(i.units,12),0n)-Mt(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var yd=G.discriminatedUnion("funding",[G.strictObject({funding:G.literal("balance"),sourceId:G.uuid(),rolloverId:G.uuid().nullable(),units:ir.refine(e=>/[1-9]/.test(e)),amount:ut}),G.strictObject({funding:G.literal("unbilled"),units:ir.refine(e=>/[1-9]/.test(e))}),G.object({funding:G.literal("prepaid"),sourceId:G.uuid(),units:rr,amount:ut,pricing:G.array(Os).min(1).max(12)}).strict().refine(e=>vi(()=>e.pricing.reduce((t,n)=>t+Mt(n.units,6),0n)===Mt(e.units,6)&&e.pricing.reduce((t,n)=>t+Mt(n.amount,12),0n)===Mt(e.amount,12)&&e.pricing.every(t=>Mt(t.unitCost,6)*Mt(t.units,6)===Mt(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),G.object({funding:G.literal("postpaid"),invoiceLineId:G.uuid().nullable(),units:rr,authorizationId:G.uuid()}).strict()]),Ao=G.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Sd=G.object({allowed:G.boolean(),internal_feature_id:G.uuid(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:Io.optional(),reason:Ao.nullable(),allocations:G.array(yd).max(500)}).strict().refine(e=>vi(()=>e.allowed?e.reason===null&&_d(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>vi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&Mt(e.requestedQuantity,6)>=Mt(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Ai=G.object({id:G.uuid(),internal_feature_id:G.uuid(),kind:G.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:G.uuid().nullable(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:Io.optional(),accepted:G.boolean(),reason:G.enum([...Ao.options,"expired"]).nullable(),createdAt:G.iso.datetime({offset:!0}),reservationStatus:G.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:G.iso.datetime({offset:!0}).nullable(),allocations:G.array(yd).max(500)}).strict().refine(e=>vi(()=>e.accepted?e.reason===null&&_d(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>vi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&Mt(e.requestedQuantity,6)>=Mt(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 or=Se.iso.datetime({offset:!0}),xd=Y.refine(e=>/[1-9]/.test(e)),vd=Se.strictObject({interval:hi.exclude(["lifetime"]),count:bi}),ny=Se.strictObject({action:Se.literal("create"),requestId:Se.uuid(),internal_feature_id:Se.uuid(),entityId:Se.uuid().nullable(),amount:xd.nullable(),expiresAt:or.nullable(),reset:vd.nullable(),rollover:tr.nullable(),nextResetAt:or.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"),Id=Se.discriminatedUnion("action",[ny,Se.strictObject({action:Se.literal("update"),requestId:Se.uuid(),grantId:Se.uuid(),revision:Se.number().int().nonnegative(),amount:xd.nullable(),expiresAt:or.nullable(),rollover:tr.nullable(),nextResetAt:or.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()})]),Ps=Se.strictObject({id:Se.uuid(),internal_feature_id:Se.uuid(),entityId:Se.uuid().nullable(),amount:Y.nullable(),reset:vd.nullable(),rollover:tr.nullable(),nextResetAt:or.nullable(),startsAt:or,expiresAt:or.nullable(),revision:Se.number().int().nonnegative(),revoked:Se.boolean(),available:ut,held:ut,spent:ut}),Ad=Se.strictObject({customerId:Se.uuid(),after:Se.uuid().nullable(),limit:Se.number().int().min(1).max(100)}),wd=Se.strictObject({rows:Se.array(Ps).max(100),nextCursor:Se.uuid().nullable()});import{z as H}from"zod";var gn=H.iso.datetime({offset:!0}),Od=H.strictObject({invoiceId:H.uuid(),after:H.string().min(1).max(180).nullable(),limit:H.number().int().min(1).max(100)}),ry=H.strictObject({kind:H.literal("product"),key:H.string(),productVersionId:H.uuid(),productName:H.string(),itemKey:H.string(),entityId:H.uuid().nullable(),quantity:H.number().int().positive(),subtotalMinor:H.string().regex(/^-?\d+$/),discountMinor:H.string().regex(/^\d+$/),taxMinor:H.string().regex(/^-?\d+$/).nullable(),totalMinor:H.string().regex(/^-?\d+$/),startsAt:gn.nullable(),endsAt:gn.nullable(),providerLineId:H.string().nullable(),providerItemId:H.string()}),Pd=H.strictObject({invoice:fi,items:H.array(H.discriminatedUnion("kind",[ry,H.strictObject({kind:H.literal("invoice_credit"),key:H.string(),internal_feature_id:H.uuid(),internal_credit_feature_id:H.uuid(),name:H.string(),units:Y,reserved:Y,amountMinor:wr,grossAmountMinor:wr,creditsAppliedMinor:wr,properties:Xe,cashPrice:Nn,providerItemId:H.string().nullable(),creditProviderItemId:H.string().nullable()}),H.strictObject({kind:H.literal("usage"),key:H.string(),internal_feature_id:H.uuid(),name:H.string(),units:Y,reserved:Y,amountMinor:wr,cashPrice:Nn})])).max(100),nextCursor:H.string().min(1).max(180).nullable()}),iy=H.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Cs=H.strictObject({from:gn,to:gn,entityId:H.uuid().optional(),snapshotAt:gn.nullable(),after:H.strictObject({at:gn,id:H.uuid(),position:H.number().int().nonnegative()}).nullable(),limit:H.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"),Cd=H.strictObject({customerId:H.uuid(),entityId:H.uuid().nullable(),from:gn,to:gn,snapshotAt:gn,totals:H.array(H.strictObject({internal_credit_feature_id:H.uuid(),name:H.string(),consumed:ut,refunded:ut,net:iy})).max(1e3),rows:H.array(H.strictObject({operationId:H.uuid(),position:H.number().int().nonnegative(),kind:H.enum(["consume","confirm","refund"]),originalId:H.uuid().nullable(),occurredAt:gn,internal_feature_id:H.uuid(),entitlementName:H.string(),sourceId:H.uuid(),internal_credit_feature_id:H.uuid(),creditName:H.string(),units:ir,amount:ut,pricing:H.array(Os).max(12),properties:Xe})).max(100),nextCursor:Cs.shape.after});import{z as Lt}from"zod";var mE=Lt.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"]),Ed=Lt.object({operationId:Lt.uuid(),windowId:Lt.uuid(),customerId:Lt.uuid(),entityId:Lt.uuid().nullable(),internal_feature_id:Lt.uuid(),entitlementKey:tn,basis:Lt.enum(["usage","credits"]),interval:Lt.enum(["day","week","month","year"]),filter:Xe,startsAt:Lt.iso.datetime({offset:!0}),endsAt:Lt.iso.datetime({offset:!0}),limit:Y.refine(e=>/[1-9]/.test(e)),used:ut,reserved:ut,threshold:Lt.number().positive().max(1)}).strict(),fE=Ed.omit({threshold:!0,limit:!0}).extend({alertThreshold:Y.refine(e=>/[1-9]/.test(e)),limit:Y.nullable()}),gE=Ed.omit({limit:!0}).extend({includedAllowance:Lt.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z as O}from"zod";import{z as an}from"zod";var oy=an.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),ay=an.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),wo=an.strictObject({internal_feature_id:an.uuid(),entityId:an.uuid().nullable()}),Td=wo.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=wo.extend({operationId:an.uuid().nullable(),usage:Y,capacity:oy.nullable(),remaining:ay.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("-"),[o,a=""]=(i?r.slice(1):r).split(".");return(i?-1n:1n)*(BigInt(o)*10n**12n+BigInt(a.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=O.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),sn=O.iso.datetime({offset:!0}),sy=O.enum(["access","metered","credit"]),Oi={internal_feature_id:O.uuid(),key:tn,name:O.string().min(1).max(120),kind:sy},Rd=O.object({customerId:O.uuid(),snapshotAt:sn,memberships:O.array(O.object({id:O.uuid(),productId:O.string().min(1).max(255),productVersionId:O.uuid(),billingProductVersionId:O.uuid(),version:O.number().int().positive(),key:O.string().min(1).max(64),name:O.string().min(1).max(120),groupId:O.string().max(255).nullable(),membershipType:O.enum(["main","addon"]),status:O.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:O.boolean(),accessEnabled:O.boolean(),renewalChange:O.object({productVersionId:O.uuid(),name:O.string().min(1).max(120),version:O.number().int().positive(),effectiveAt:sn,benefitsAppliedAt:sn.nullable(),timing:O.enum(["immediate","renewal"]),changeKind:O.enum(["plan","seats","quantity"]),feature:O.strictObject({internal_feature_id:O.uuid(),name:O.string().min(1).max(80),fromQuantity:O.number().int().min(0).max(1e4),toQuantity:O.number().int().min(0).max(1e4)}).optional(),seat:O.object({key:O.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:O.number().int().min(0).max(1e4),toQuantity:O.number().int().min(0).max(1e4)}).strict().nullable(),status:O.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:O.object({phase:O.enum(["paid","trial"]),startsAt:sn,endsAt:sn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:O.boolean(),balances:O.array(O.object({...Oi,usageType:O.enum(["consumable","non_consumable"]).nullable(),accessible:O.boolean(),unlimited:O.boolean(),available:Ye,held:Ye,debt:Ye,nextExpiresAt:sn.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:O.boolean()}).strict(),kd=O.enum(["source","usage","transaction","invoice","debt","settlement"]),Oo=O.object({at:sn,id:O.uuid(),type:kd}).strict(),jd=O.object({type:kd.nullable(),resourceKey:tn.optional(),kind:O.enum(["purchase","refund"]).optional(),topup:O.boolean().optional(),from:O.iso.date().nullable(),to:O.iso.date().nullable(),after:Oo.nullable(),limit:O.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Or={id:O.uuid(),occurredAt:sn},cy=O.discriminatedUnion("type",[O.strictObject({...Or,type:O.literal("invoice"),status:O.string().min(1).max(80),paid:Ye,refunded:Ye,currency:W,externalId:O.string().nullable()}),O.object({...Or,...Oi,type:O.literal("source"),reason:O.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ye,unlimited:O.boolean(),status:O.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:sn,expiresAt:sn.nullable(),orderId:O.uuid().nullable(),parentSourceId:O.uuid().nullable()}).strict(),O.object({...Or,type:O.literal("usage"),internal_feature_id:O.uuid(),name:O.string().min(1).max(120),kind:O.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:O.uuid().nullable(),quantity:Y,accepted:O.boolean(),reason:O.enum([...Ao.options,"expired"]).nullable(),properties:Xe,reservationStatus:O.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:sn.nullable(),charges:O.array(O.discriminatedUnion("funding",[O.strictObject({funding:O.literal("balance"),sourceId:O.uuid(),rolloverId:O.uuid().nullable(),units:ir,amount:Ye}),O.strictObject({funding:O.literal("unbilled"),units:ir}),O.object({...Oi,funding:O.literal("prepaid"),amount:Ye}).strict(),O.object({funding:O.literal("postpaid"),invoiceId:O.uuid(),invoiceLineId:O.uuid(),authorizationId:O.uuid(),units:Y,currency:W}).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"),O.object({...Or,type:O.literal("transaction"),purpose:O.enum(["product","invoice"]),productVersionId:O.uuid().nullable(),productName:O.string().min(1).max(120).nullable(),productVersion:O.number().int().positive().nullable(),invoiceId:O.uuid().nullable(),orderId:O.uuid(),originalId:O.uuid().nullable(),kind:O.enum(["purchase","refund"]),amountMinor:O.number().int().nonnegative().max(2e8).nullable(),currency:W.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"),O.object({...Or,...Oi,type:O.literal("debt"),sourceId:O.uuid(),transactionId:O.uuid(),amount:Ye}).strict(),O.object({...Or,...Oi,type:O.literal("settlement"),sourceId:O.uuid(),debtId:O.uuid(),kind:O.enum(["payment","usage_refund","payment_return"]),amount:Ye}).strict()]),Nd=O.object({customerId:O.uuid(),rows:O.array(cy).max(50),nextCursor:Oo.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 Fd=ee.object({customerId:ee.uuid()}).strict(),Ud=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()]),Pi=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()}),Dd=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:Dd,product:Ts}),product:Ts,planLicense:ee.strictObject({id:ee.uuid(),prepaidOnly:ee.boolean(),isCustom:ee.boolean()}).nullable(),granted:Pi,included:Pi,paidQuantity:Pi,usage:Pi,remaining:Pi,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:Dd,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 Fn}from"zod";var uy=Fn.object({name:Fn.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:Fn.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")}),Md=Fn.object({description:Fn.string().trim().max(240)}),EE=Fn.object({project:uy.extend({id:Fn.string().min(1)}),environments:Fn.object({sandbox:Md,live:Md})});import{z as Ve}from"zod";import{z as Pe}from"zod";import{z as Pr}from"zod";var Ld=Pr.enum(["stripe","apple","google"]),Bd=Pr.enum(["membership","credit_pack","lifetime"]),kE=Pr.enum(["active","grace","suspended","inactive","revoked"]),jE=Pr.strictObject({currency:Pr.string().regex(/^[A-Z]{3}$/),micros:Pr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as Ne}from"zod";var ly=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()})]),dy=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),Un=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"})}),qd=Ne.record(Ne.uuid(),Un).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function py(e,t){if(e.nativeOffers!==void 0)return qd.parse(e.nativeOffers)[t]}function my(e,t,n,r){return Un.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=Pe.object({type:Pe.literal("native_purchase"),receiptId:Pe.uuid(),orderId:Pe.uuid(),productVersionId:Pe.uuid(),provider:Pe.enum(["apple","google"]),productId:Pe.string().min(1).max(255),productKind:Bd,replacement:Pe.strictObject({sourceOrderId:Pe.uuid(),sourceProductId:Pe.string().min(1).max(255),policy:Pe.enum(["apple_store","google_full_price"]),sourceAccountTokens:Pe.array(Pe.uuid()).max(50)}).nullable(),appAccountToken:Pe.uuid().optional(),obfuscatedAccountId:Pe.string().min(1).max(64).optional(),obfuscatedProfileId:Pe.uuid().optional(),basePlanId:Pe.string().min(1).max(255).optional(),offerId:Pe.string().min(1).max(255).optional(),offerKind:Pe.enum(["none","introductory","promotional"]),currency:W,catalogAmountMinor:Pe.number().int().nonnegative().max(1e8),discountMinor:Pe.number().int().nonnegative().max(1e8),trialDays:Pe.number().int().min(1).max(730).nullable(),seatBundle:Pe.array(Pe.strictObject({key:Pe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Pe.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Pe.strictObject({offerId:Pe.string().min(1).max(255),keyId:Pe.string().min(1).max(255),nonce:Pe.uuid(),signature:Pe.string().min(1).max(1024),timestamp:Pe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as m}from"zod";var Gd=m.strictObject({requestId:m.uuid(),entityId:m.uuid().optional(),billingSubscriptionId:m.uuid().optional(),newBillingSubscription:m.literal(!0).optional(),offerId:m.uuid().optional(),nativeOffer:Un.optional(),plans:m.array(m.strictObject({productVersionId:m.uuid(),seatQuantities:m.record(fn,m.number().int().min(0).max(1e4)).optional(),featureQuantities:m.record(m.uuid(),m.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:m.enum(["stripe","apple","google"]),currency:W}).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"),sr=m.strictObject({operationId:m.uuid()}),lt=m.number().int().min(0).max(1e8),fy=m.strictObject({lineId:m.uuid(),productVersionId:m.uuid(),productName:m.string().min(1).max(80),interval:m.enum(["free","week","month","year","one_time"]),intervalCount:m.number().int().min(1).max(156).optional(),baseAmountMinor:lt,seats:m.array(m.strictObject({key:fn,quantity:m.number().int().min(0).max(1e4),includedQuantity:m.number().int().min(0).max(1e4),maximumQuantity:m.number().int().min(0).max(1e4),unitAmountMinor:lt})).max(20),prepaid:m.array(gd).max(100).optional(),catalogAmountMinor:lt,trial:m.strictObject({days:m.number().int().min(1).max(730),cardRequired:m.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+go(n),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),Kd=m.string().regex(/^[A-Za-z0-9_-]{1,200}$/),gy=m.strictObject({id:Kd,name:m.string().min(1).max(40),percent_off:m.number().gt(0).max(100).optional(),amount_off:m.number().int().positive().optional(),currency:m.string().regex(/^[a-z]{3}$/).optional(),duration:m.enum(["once","repeating","forever"]),duration_in_months:m.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"),hy=m.strictObject({subscriptionId:m.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:m.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:m.array(m.strictObject({id:m.string(),price_id:m.string(),quantity:m.number().int().nonnegative(),discounts:m.array(m.strictObject({id:m.string(),coupon:m.string(),start:m.number(),end:m.number().nullable()})).optional()})).min(1).max(100),prorationDate:m.number().int().nonnegative(),amountMinor:m.number().int().positive(),periodStartMs:m.number(),periodEndMs:m.number()}),zd=m.strictObject({append:hy.optional(),provider:m.literal("stripe"),executor:m.enum(["indiana","merchant"]),accountId:m.string().regex(/^acct_[A-Za-z0-9]+$/),mode:m.enum(["payment","subscription"]),lineItems:m.array(m.strictObject({price:m.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:m.number().int().min(1).max(1e4),priceId:m.uuid(),productName:m.string().min(1).max(80),amountMinor:m.number().int().min(0).max(1e8),currency:m.string().regex(/^[a-z]{3}$/),interval:m.enum(["week","month","year","one_off"]),intervalCount:m.number().int().min(1).max(52),slot:m.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:m.strictObject({mode:m.enum(["graduated","volume"]),tiers:m.array(m.strictObject({upTo:m.number().int().min(1).max(1e6).nullable(),unitAmountMinor:m.number().int().min(0).max(1e8),flatAmountMinor:m.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:m.array(m.strictObject({coupon:Kd,terms:gy})).max(1),trialPeriodDays:m.number().int().min(1).max(730).nullable(),metadata:m.strictObject({grooveCheckoutId:m.uuid(),grooveCustomerId:m.uuid()}),expiresAt:m.iso.datetime({offset:!0})}),Ci=m.strictObject({operationId:m.uuid(),entityId:m.uuid().nullable(),billingSubscriptionId:m.uuid().nullable(),discount:m.strictObject({offerId:m.uuid(),couponId:m.uuid(),discount:Ar,duration:rn,amountMinor:lt,allocations:m.array(m.strictObject({productVersionId:m.uuid(),amountMinor:lt})).min(1).max(20),expiresAt:m.iso.datetime({offset:!0})}).nullable(),charge:m.strictObject({effectiveAt:m.iso.datetime({offset:!0}),periodEndsAt:m.iso.datetime({offset:!0}),debitMinor:lt,discountMinor:lt,taxMinor:lt,totalMinor:lt}).nullable(),expiresAt:m.iso.datetime({offset:!0}),provider:m.enum(["stripe","apple","google"]),nativeOffer:Un.optional(),currency:W,lines:m.array(fy).min(1).max(20),catalogAmountMinor:lt,automaticTax:m.boolean(),execution:zd.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0].trial?.cardRequired===!1?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)=>t.productVersionId===e.lines[n].productVersionId&&t.amountMinor<=e.lines[n].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"),Cr=m.strictObject({operationId:m.uuid(),orderId:m.uuid(),append:m.boolean().optional(),status:m.enum(["pending","complete","cancelled","failed"]),executor:m.enum(["indiana","merchant"]),checkoutUrl:m.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:zd.nullable(),currency:W,catalogAmountMinor:lt,taxMinor:lt,totalMinor:m.number().int().min(0).max(2e8).nullable(),quoteFinalized:m.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"),Co=m.strictObject({enabled:m.literal(!0),featureIds:m.array(m.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Hd=m.strictObject({requestId:m.uuid(),membershipId:m.uuid(),carryOverBalances:Co.optional(),carryOverUsages:Co.optional(),membershipIds:m.array(m.uuid()).min(1).max(20).optional(),prorationBehavior:m.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:m.enum(["immediate","renewal","store"]),change:m.discriminatedUnion("type",[m.strictObject({type:m.literal("plan"),productVersionId:m.uuid()}),m.strictObject({type:m.literal("seats"),licenseKey:fn,quantity:m.number().int().min(0).max(1e4)}),m.strictObject({type:m.literal("quantity"),internal_feature_id:m.uuid(),quantity:m.number().int().min(0).max(1e4)}),m.strictObject({type:m.literal("cancel")}),m.strictObject({type:m.literal("uncancel")})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").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"),Po=m.string().regex(/^price_[A-Za-z0-9]+$/),Vd=m.strictObject({grooveUpdateId:m.uuid(),grooveCustomerId:m.uuid()}),$d=m.strictObject({price:Po.nullable(),priceId:m.uuid().optional(),quantity:m.number().int().min(0).max(1e4)}),Wd=m.strictObject({provider:m.literal("stripe"),executor:m.enum(["indiana","merchant"]),accountId:m.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:m.string().regex(/^sub_[A-Za-z0-9]+$/),action:m.enum(["update","cancel","schedule","release"]),update:m.strictObject({items:m.array($d).max(20),remove:m.array(Po).max(20),restoreItems:m.array(m.strictObject({price:Po,quantity:m.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:m.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:m.number().int().positive().optional(),paymentBehavior:m.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:m.boolean().optional(),clearCancelAt:m.literal(!0).optional(),metadata:Vd}).nullable(),cancel:m.strictObject({prorate:m.literal(!1),invoiceNow:m.literal(!1)}).nullable(),schedule:m.strictObject({currentItems:m.array(m.strictObject({price:Po,quantity:m.number().int().min(0).max(1e4)})).max(20),nextItems:m.array($d).min(1).max(20),switchAt:m.number().int().positive(),interval:m.enum(["week","month","year"]),intervalCount:m.number().int().min(1).max(52),metadata:Vd}).nullable(),release:m.strictObject({schedule:m.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:m.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"),js=m.strictObject({carryOverBalances:Co.optional(),carryOverUsages:Co.optional(),operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),timing:m.enum(["immediate","renewal"]),effectiveAt:m.iso.datetime({offset:!0}),expiresAt:m.iso.datetime({offset:!0}),currency:W,creditMinor:lt,debitMinor:lt,discountMinor:lt,taxMinor:lt,totalMinor:lt,retainedProductVersionIds:m.array(m.uuid()).max(19),execution:Wd}),by=m.strictObject({operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),status:m.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:m.enum(["immediate","renewal"]),effectiveAt:m.iso.datetime({offset:!0}),checkoutUrl:m.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:m.enum(["indiana","merchant"]),execution:Wd.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),_y=m.strictObject({operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),timing:m.literal("store"),effectiveAt:m.null(),expiresAt:m.iso.datetime({offset:!0}),currency:W,creditMinor:m.null(),debitMinor:m.null(),discountMinor:m.null(),taxMinor:m.null(),totalMinor:m.null(),retainedProductVersionIds:m.array(m.uuid()).max(19),store:m.strictObject({provider:m.enum(["apple","google"]),productId:m.string().min(1).max(255),catalogAmountMinor:lt,policy:m.enum(["apple_store","google_full_price"])})}),yy=m.strictObject({operationId:m.uuid(),membershipId:m.uuid(),productVersionId:m.uuid(),status:m.enum(["prepared","pending","effective","cancelled","failed"]),timing:m.literal("store"),effectiveAt:m.iso.datetime({offset:!0}).nullable(),checkoutUrl:m.null(),nativePurchase:ks.nullable()}),Qd=m.union([js,_y]),Ns=m.union([by,yy]),Ei=m.number().int().positive().max(2e8),ar=m.number().int().min(0).max(2e8),Zd=m.strictObject({requestId:m.uuid(),invoiceId:m.uuid(),mode:m.enum(["full","partial"]),amountMinor:Ei.optional(),entitlementAction:m.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),Yd=m.strictObject({provider:m.literal("stripe"),executor:m.enum(["indiana","merchant"]),accountId:m.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:m.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Ei,currency:m.string().regex(/^[a-z]{3}$/),metadata:m.strictObject({indianaRefundId:m.uuid()}),idempotencyKey:m.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:m.array(m.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),Jd=m.strictObject({operationId:m.uuid(),invoiceId:m.uuid(),providerInvoiceId:m.string().regex(/^in_[A-Za-z0-9]+$/),currency:W,paidMinor:ar,refundedMinor:ar,pendingMinor:ar,amountMinor:Ei,mode:m.enum(["full","partial"]),entitlementAction:m.enum(["retain","revoke"]),revokes:m.strictObject({customerProductIds:m.array(m.uuid()).max(100),subscriptionIds:m.array(m.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:Yd,expiresAt:m.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"),Eo=m.strictObject({operationId:m.uuid(),invoiceId:m.uuid(),providerInvoiceId:m.string().regex(/^in_[A-Za-z0-9]+$/),status:m.enum(["quoted","pending","succeeded","failed","expired"]),executor:m.enum(["indiana","merchant"]),currency:W,amountMinor:Ei,mode:m.enum(["full","partial"]),entitlementAction:m.enum(["retain","revoke"]),refundId:m.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:Yd.nullable(),failureReason:m.string().min(1).max(200).nullable(),createdAt:m.iso.datetime({offset:!0}),completedAt:m.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"),ZE=m.strictObject({invoiceId:m.uuid(),currency:W,paidMinor:ar,refundedMinor:ar,pendingMinor:ar,refundableMinor:ar,executor:m.enum(["indiana","merchant"]).nullable(),canRefund:m.boolean(),operations:m.array(Eo).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),YE=m.strictObject({requestId:m.uuid(),mode:m.enum(["full","partial"]),amountMinor:Ei.optional(),entitlementAction:m.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 Xd=Ve.strictObject({requestId:Ve.uuid(),targets:Ve.array(Ve.strictObject({membershipId:Ve.uuid(),action:Ve.enum(["cancel","uncancel"]),timing:Ve.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"),To=Ve.strictObject({batchId:Ve.uuid()}),Sy=Ve.strictObject({operationId:Ve.uuid(),membershipIds:Ve.array(Ve.uuid()).min(1).max(20),provider:Ve.enum(["stripe","apple","google"]),action:Ve.enum(["cancel","uncancel"]),timing:Ve.enum(["immediate","renewal"]),status:Ve.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:js.nullable(),managementUrl:Ve.url().nullable(),failureCode:Ve.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Ti=Ve.strictObject({batchId:Ve.uuid(),ready:Ve.boolean(),status:Ve.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:Ve.iso.datetime({offset:!0}),acceptedAt:Ve.iso.datetime({offset:!0}).nullable(),groups:Ve.array(Sy).min(1).max(100)});import{z as ye}from"zod";var xy=ye.string().trim().min(1).max(240),Ds={requestId:ye.uuid(),reason:xy},Ro=ye.discriminatedUnion("action",[ye.strictObject({...Ds,action:ye.literal("start"),productVersionId:ye.uuid(),entityId:ye.uuid().optional(),days:ye.number().int().min(1).max(730).optional()}),ye.strictObject({...Ds,action:ye.literal("extend"),membershipId:ye.uuid(),days:ye.number().int().min(1).max(730)}),ye.strictObject({...Ds,action:ye.literal("end"),membershipId:ye.uuid()})]),ep=ye.strictObject({operationId:ye.uuid()}),tp=ye.iso.datetime({offset:!0}),vy=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"),tp]),prorationBehavior:ye.literal("none")}),Fs=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:tp.nullable(),execution:vy.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"),rT=ye.strictObject({groupId:ye.uuid(),productVersionId:ye.uuid(),enabled:ye.boolean()});import{z as ke}from"zod";var np=ke.strictObject({requestId:ke.uuid(),currency:W,makeDefault:ke.boolean()}),rp=ke.strictObject({setupId:ke.uuid()}),Iy=ke.strictObject({provider:ke.literal("stripe"),executor:ke.literal("merchant"),accountId:ke.string().regex(/^acct_[A-Za-z0-9]+$/),mode:ke.literal("setup"),currency:ke.string().regex(/^[a-z]{3}$/),customer:ke.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:ke.uuid(),metadata:ke.strictObject({grooveProjectId:ke.uuid(),grooveEnvironmentId:ke.uuid(),grooveCustomerId:ke.uuid(),groovePaymentSetupId:ke.uuid()}),setDefaultPaymentMethod:ke.boolean(),expiresAt:ke.iso.datetime({offset:!0})}),Us=ke.strictObject({id:ke.uuid(),provider:ke.literal("stripe"),status:ke.enum(["prepared","complete","expired"]),currency:W,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:Iy.nullable()});import{z as dt}from"zod";var ip=dt.union([dt.string(),dt.number(),dt.boolean(),dt.null()]),op=dt.strictObject({customerId:dt.uuid()}),ap=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:ip,actual:ip})).max(1e4)});import{z as de}from"zod";var ko=de.iso.datetime({offset:!0}),jo=de.strictObject({createdAt:ko,id:de.uuid()}),No=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:jo.optional(),limit:de.number().int().min(1).max(100).optional()}),Ms={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:ko},Ay=de.strictObject({...Ms,status:de.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:de.boolean(),billingSubscriptionId:de.uuid().nullable()}),wy=de.strictObject({...Ms,status:de.enum(["active","ended","refunded"]),orderId:de.uuid().nullable(),transactionId:de.uuid().nullable(),currency:W.nullable(),amountMinor:de.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),Oy=de.strictObject({...Ms,status:de.enum(["blocked","resolved"]),conflict:de.strictObject({detectedAt:ko,blockingMembershipIds:de.array(de.uuid()).min(1).max(100),transactionId:de.uuid()}),resolvedAt:ko.nullable()}),sp=No.extend({status:de.enum(["blocked","resolved"]).optional()}),cp=de.strictObject({customerId:de.uuid(),orderId:de.uuid()}),up=de.strictObject({orderId:de.uuid(),status:de.enum(["blocked","resolved"])}),lp=de.strictObject({items:de.array(Ay).max(100),nextCursor:jo.nullable()}),dp=de.strictObject({items:de.array(wy).max(100),nextCursor:jo.nullable()}),pp=de.strictObject({items:de.array(Oy).max(100),nextCursor:jo.nullable()});import{z as Ue}from"zod";var mp=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)})]),fp=Ue.strictObject({requestId:Ue.uuid(),orderId:Ue.uuid(),purchaseIntentId:Ue.uuid(),status:Ue.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:W,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 ze}from"zod";import{z as Py}from"zod";var Er=Py.object({provider:Ld,currency:W}).strict();var Mn=ze.strictObject({internal_feature_id:ze.uuid(),quantity:Y.refine(e=>/[1-9]/.test(e)),properties:Xe,entityId:ze.uuid().optional()}),gp=ze.strictObject({requirement:Mn,commerce:Er.optional(),paywallId:ze.uuid().optional()}),Cy=ze.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Ls=ze.strictObject({productId:ze.string().min(1),productVersionId:ze.string().min(1),name:ze.string().min(1).max(120),action:ze.enum(["purchase","upgrade","addon","topup"]),membershipId:ze.string().min(1).nullable(),currency:W,amountMinor:ze.string().regex(/^(0|[1-9]\d{0,8})$/),interval:ze.enum(["free","week","month","year","one_time"]),intervalCount:ze.number().int().min(1).max(156)}),cr=ze.strictObject({internal_feature_id:ze.string().min(1),name:ze.string().min(1).max(120),kind:ze.enum(["access","metered","credit"]),quantity:Y,allowed:ze.boolean(),reason:Cy.nullable(),preview:ze.strictObject({scenario:ze.enum(["feature_flag","usage_limit"]),candidates:ze.array(Ls).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"})}),AT=ze.strictObject({paywallId:ze.uuid(),requirement:Mn});import{z as k}from"zod";var Vs=k.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Ey=k.record(k.string(),k.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Ty=3,Ri=20,Ry=Ty*Ri,Bs=k.strictObject({type:k.literal("product"),productId:Vs}),hp={type:k.literal("group"),key:k.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:k.string().trim().min(1).max(80)},ky=k.discriminatedUnion("type",[Bs,k.strictObject({...hp,items:k.array(Bs).max(Ri)})]),jy=k.discriminatedUnion("type",[Bs,k.strictObject({...hp,items:k.array(ky).max(Ri)})]),Ny=k.array(jy).max(Ri).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function o(a){for(let s of a){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&o(s.items)}}o(e),(n.size>Ri||i>Ry)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function ki(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:ki(t))}function PT(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 Do=k.strictObject({lookupKey:k.string().trim().min(1).max(200),displayName:k.string().trim().min(1).max(1500),items:Ny,metadata:Ey}),qs=Do.extend({paywallId:k.uuid().nullable()}),Dy=k.strictObject({product:k.record(k.string(),k.json()),prices:k.array(k.record(k.string(),k.json())),entitlements:k.array(k.record(k.string(),k.json())),freeTrials:k.array(k.record(k.string(),k.json())),licenses:k.array(k.record(k.string(),k.json()))}),bp=qs.extend({id:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),state:k.enum(["active","archived"]),isCurrent:k.boolean(),revision:k.number().int().nonnegative(),publishedVersionId:k.uuid().nullable(),createdAt:k.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"})}),_p=k.strictObject({id:k.uuid(),offeringId:k.uuid(),projectId:k.uuid(),environmentId:k.uuid(),version:k.number().int().positive(),document:Do,productEvidence:k.record(Vs,Dy),createdAt:k.number().nonnegative().nullable()}).superRefine((e,t)=>{let n=ki(e.document);(!n.length||My(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"})}),Fy=k.strictObject({rows:k.array(bp).max(200),versions:k.array(_p).max(500)}),CT=k.discriminatedUnion("action",[k.strictObject({action:k.literal("create"),document:qs}),k.strictObject({action:k.literal("save"),id:k.uuid(),revision:k.number().int().nonnegative(),document:qs}),k.strictObject({action:k.enum(["publish","set_current","archive","restore"]),id:k.uuid(),revision:k.number().int().nonnegative()})]),ET=k.strictObject({record:bp,version:_p.nullable()}),yp=k.discriminatedUnion("type",[k.strictObject({type:k.literal("current")}),k.strictObject({type:k.literal("id"),id:k.uuid()}),k.strictObject({type:k.literal("lookup_key"),lookupKey:k.string().min(1).max(200)}),k.strictObject({type:k.literal("version"),versionId:k.uuid()})]),Uy=k.strictObject({internalId:Vs,id:k.string(),name:k.string().nullable(),version:k.number().int().positive(),archived:k.boolean()}),TT=Fy.extend({products:k.array(Uy).max(500),paywalls:k.array(k.strictObject({id:k.uuid(),name:k.string()})).max(200)});function My(e){let t=[];ki(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 Fo}from"zod";var Tr=Fo.strictObject({id:Fo.uuid(),offeringId:Fo.uuid(),version:Fo.number().int().positive(),document:Do});import{z as kt}from"zod";import{z as ne}from"zod";import{z as Rr}from"zod";import{z as wn}from"zod";var Sp=wn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Uo=wn.strictObject({tiers:wn.array(wn.strictObject({id:Sp,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:Sp,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 Mo(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var xp=Rr.strictObject({items:Rr.array(Rr.strictObject({productVersionId:Rr.string().min(1).max(200),label:Rr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Rr.string().min(1).max(200).nullable(),grouping:Uo.optional()});function LT(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 vp(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function kr(e){let t={};function n(r){if(vp(r)){let i=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let a of r.children){let s=a.type==="stack"?a.bind?.plan:void 0;s&&!i.ids.includes(s)&&i.ids.push(s)}let o=r.children[r.interaction.defaultIndex];!i.defaultId&&o?.type==="stack"&&(i.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}function Ip(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(vp(c)){let d=r[c.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},p=n.pickers[c.interaction.pickerId]?.options??[];for(let f of u){let h=f.type==="stack"?f.bind?.plan:void 0;h&&p.includes(h)&&!d.ids.includes(h)&&d.ids.push(h),h&&f.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(p=>p.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,p=c.children[d?0:1];p&&i(p)}else u.forEach(i)}let o=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,a=e.pages.find(c=>c.id===o);a&&i(a.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(kr(e)))s[c]??="";return s}import{z as oe}from"zod";var Ly=["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"],$s=oe.object({plan:oe.string().min(1).max(200).optional(),coupon:oe.uuid().optional(),promotionCode:oe.uuid().optional(),picker:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Ap=oe.object({text:oe.string().optional(),label:oe.string().optional(),alt:oe.string().optional(),html:oe.string().max(32768).optional(),price:oe.object({current:oe.string(),original:oe.string().nullable(),period:oe.string()}).optional(),code:oe.string().optional(),countdownAt:oe.iso.datetime().optional(),planId:oe.string().min(1).max(200).optional(),planVersionId:oe.string().min(1).max(200).optional(),currency:W.optional(),couponId:oe.uuid().optional(),offerId:oe.uuid().optional(),unavailable:oe.boolean().optional(),unavailableReason:oe.string().optional(),missing:oe.array(oe.string()).optional()}).strict(),Lo=oe.object({paywall:cr.optional(),nodes:oe.record(oe.string(),oe.object({base:Ap,picker:oe.string().optional(),byPlan:oe.record(oe.string(),Ap).optional()}).strict()),plans:oe.record(oe.string(),oe.object({id:oe.string().min(1).max(200),versionId:oe.string().min(1).max(200),available:oe.boolean(),name:oe.string(),price:oe.string(),period:oe.string(),currency:W.optional()}).strict()),pickers:oe.record(oe.string(),oe.object({options:oe.array(oe.string().min(1).max(200)).max(20),selected:oe.string().min(1).max(200).nullable()}).strict()),diagnostics:oe.array(oe.object({nodeId:oe.string(),message:oe.string()}).strict())}).strict();function Bo(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].map(t=>t[1].trim())}function qo(e){let t=Bo(e).filter(r=>!Ly.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 KT(e,t,n,r=!1){let i=Bo(e).filter(o=>!/^(input|params)\.[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(o)&&t[o]===void 0);return i.length&&!r?{value:n,missing:i}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(o,a)=>t[a.trim()]??o),missing:i}}function zT(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 _}from"zod";import{z as Z}from"zod";var By=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],wp=Z.enum(By),Op=Z.object({source:wp,layout:Z.enum(["full","compact"]),resourceKey:tn.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"})}),at=Z.string().max(2e3),Pp=Z.object({id:Z.string().max(100),label:at,detail:Z.array(at).max(12),value:at.optional(),status:at.optional(),facts:Z.array(Z.object({label:at,value:at}).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:at})).max(1).optional(),membershipActions:Z.array(Z.object({value:Z.string().max(100),label:at}).strict()).max(3).optional()}).strict(),qy=Z.object({key:tn,name:at,spendable:at,reserved:at,available:at,expiry:at.nullable(),sources:Z.array(Pp).max(50),sourceCount:Z.number().int().nonnegative(),sourcePage:Z.number().int().positive(),hasNextSources:Z.boolean(),hasPreviousSources:Z.boolean()}).strict(),Vy=Z.object({source:wp,status:Z.enum(["idle","loading","ready","error"]),stale:Z.boolean(),preview:Z.boolean(),errorCode:Z.string().max(80).optional(),errorMessage:at.optional(),resources:Z.array(qy).max(500),rows:Z.array(Pp).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:at,note:at,facts:Z.array(Z.object({label:at,value:at}).strict()).max(100)}).strict().optional(),membershipResult:at.optional()}).strict(),Cp=Z.object({nodes:Z.record(Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Vy)}).strict(),ZT=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 Gs(e){let t=qo(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 o=e[n];if(i)o===i&&(i="");else if(o==='"'||o==="'")i=o;else if(o===">")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 XT(e,t,n,r=!1){let i=Gs(e);if(i.length)throw new Error(i[0]);let o=[...new Set(Bo(e).filter(a=>t[a]===void 0))];return o.length&&!r?{value:Tp(n),missing:o}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(a,s)=>t[s.trim()]===void 0?a:Tp(t[s.trim()])),missing:o}}var $y=4,cn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Ni=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Me=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Gy=_.enum(["none","xs","sm","md","lg","xl"]),Ky=_.enum(["none","sm","md","lg","full"]),Ks=_.string().regex(/^#[0-9a-fA-F]{6}$/),jp=_.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"),zs=_.union([jp,_.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),_.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),_.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Rp=_.object({primary:Ks,background:Ks,text:Ks,radius:Ky,font:_.enum(["system","serif","rounded","mono"])}).strict(),Di=_.union([_.enum(["primary","text","muted","background","surface"]),_.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),Ce=(e,t)=>_.number().int().min(e).max(t),kp=_.union([_.enum(["fit","fill"]),Ce(1,1200)]),zy=_.object({top:Ce(0,200),right:Ce(0,200),bottom:Ce(0,200),left:Ce(0,200)}).strict(),Hy=_.object({top:Ce(-100,200),right:Ce(-100,200),bottom:Ce(-100,200),left:Ce(-100,200)}).strict(),Np=_.object({x:Ce(0,100),y:Ce(0,100)}).strict(),Wy=_.discriminatedUnion("type",[_.object({type:_.literal("color"),color:Di}).strict(),_.object({type:_.literal("linear"),angle:Ce(0,360),stops:_.array(_.object({color:Di,at:Ce(0,100)}).strict()).min(2).max(4)}).strict(),_.object({type:_.literal("image"),src:zs,fit:_.enum(["cover","contain"]),position:Np.optional()}).strict()]),Qy=_.discriminatedUnion("type",[_.object({type:_.literal("rect"),radius:_.union([Ce(0,200),_.object({topLeft:Ce(0,200),topRight:Ce(0,200),bottomRight:Ce(0,200),bottomLeft:Ce(0,200)}).strict()])}).strict(),_.object({type:_.literal("pill")}).strict()]),Zy=_.object({width:Ce(0,12),color:Di,style:_.enum(["solid","dashed"])}).strict(),Yy=_.object({x:Ce(-40,40),y:Ce(-40,40),blur:Ce(0,80),spread:Ce(-20,40),color:Di}).strict(),Jy=_.object({font:_.enum(["system","serif","rounded","mono"]),size:Ce(8,96),weight:_.number().int().min(100).max(900).multipleOf(100),lineHeight:_.number().min(.8).max(3),letterSpacing:_.number().min(-5).max(20),color:Di,align:_.enum(["start","center","end"]),italic:_.boolean(),decoration:_.enum(["none","underline","line-through"]),transform:_.enum(["none","uppercase"])}).strict().partial(),ur=_.object({width:kp,height:kp,padding:zy,margin:Hy,gap:Ce(0,120),grow:_.union([_.boolean(),_.number().min(0).max(12)]),background:Wy,opacity:_.number().min(0).max(1),clipContent:_.boolean(),shape:Qy,border:Zy,shadow:Yy,text:Jy}).strict().partial(),zt={id:Ni,name:_.string().trim().min(1).max(60).optional(),hidden:_.boolean().optional(),style:ur.optional(),fallback:Me.optional()},Xy=_.object({...zt,type:_.literal("text"),productField:_.enum(["name","price","trial","period"]).optional(),feature:_.object({id:_.uuid(),field:_.enum(["name","allowance"])}).strict().optional(),text:Me,variant:_.enum(["title","heading","body","caption"])}).strict(),eS=_.object({...zt,type:_.literal("image"),src:zs,localizedSrc:_.record(nn,zs).optional(),alt:Me,aspect:_.enum(["auto","1:1","4:3","16:9","3:1"]),fit:_.enum(["cover","contain"]),position:Np.optional()}).strict(),tS=_.object({...zt,type:_.literal("button"),label:Me,variant:_.enum(["primary","secondary","link"]),action:Me,purpose:_.enum(["purchase","navigation","close"]).optional(),bind:$s.optional()}).strict(),nS=_.object({...zt,type:_.literal("divider")}).strict(),rS=_.object({...zt,type:_.literal("customer_data"),title:Me,data:Op}).strict(),iS=_.object({...zt,type:_.literal("spacer"),size:Gy}).strict(),oS=_.object({...zt,type:_.literal("custom_html"),html:_.record(nn,_.string().max(cn.customHtml)),css:_.string().max(cn.customCss)}).strict(),aS=_.object({...zt,type:_.literal("price"),fallback:Me,parts:_.object({current:ur.optional(),original:ur.optional(),period:ur.optional()}).strict().optional()}).strict(),sS=_.object({...zt,type:_.literal("coupon_code"),label:Me,fallback:Me}).strict(),cS=_.object({...zt,type:_.literal("countdown"),source:_.enum(["offer.ends_at","offer.expires_at","fixed"]),at:_.iso.datetime().optional(),granularity:_.enum(["day","hour","minute","second"]),expired:Me,fallback:Me}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),uS=_.object({...zt,type:_.literal("plan_picker"),label:Me,fallback:Me,planIds:_.array(_.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:_.string().min(1).max(200).optional(),grouping:Uo.safeExtend({monthLabel:Me,yearLabel:Me,unavailableLabel:Me}).optional(),states:_.object({selected:ur.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!Mo(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),lS=_.discriminatedUnion("type",[_.object({type:_.literal("input"),label:Me,keyboard:_.enum(["text","email","tel","url"]),maxLength:Ce(1,500)}).strict(),_.object({type:_.literal("multiselect"),label:Me,min:Ce(0,50),max:Ce(1,50)}).strict(),_.object({type:_.literal("select"),label:Me,defaultIndex:Ce(0,49),purpose:_.enum(["option","product","tier"]).optional(),pickerId:Ni.optional(),selectedStyle:ur.optional()}).strict(),_.object({type:_.literal("tabs"),label:Me,defaultIndex:Ce(0,49),purpose:_.literal("tier").optional()}).strict(),_.object({type:_.literal("toggle"),label:Me,defaultEnabled:_.boolean()}).strict(),_.object({type:_.literal("carousel"),label:Me}).strict()]),Dp=_.lazy(()=>_.object({...zt,type:_.literal("stack"),direction:_.enum(["vertical","horizontal","overlay"]),align:_.enum(["start","center","end","stretch"]),justify:_.enum(["start","center","end","between"]),children:_.array(dS).max(cn.children),productSlot:_.object({index:Ce(0,19),period:_.enum(["month","year"]).optional(),requireBinding:_.boolean().optional()}).strict().optional(),interaction:lS.optional(),states:_.object({selected:ur.optional()}).strict().optional(),purpose:_.literal("benefits").optional(),purchaseAction:Me.optional(),buttonVariant:_.enum(["primary","secondary","link"]).optional(),bind:$s.optional()}).strict()),dS=_.lazy(()=>_.union([Dp,Xy,eS,tS,nS,iS,oS,aS,sS,cS,uS,rS])),pS=_.union([_.string().max(500),_.number().finite(),_.boolean(),_.null()]),ji={id:Me,event:Me,properties:_.record(Me,pS).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},mS=_.discriminatedUnion("type",[_.object({...ji,type:_.literal("navigate"),close:_.literal(!1),pageId:Ni}).strict(),_.object({...ji,type:_.literal("event"),close:_.boolean()}).strict(),_.object({...ji,type:_.literal("close"),close:_.literal(!0)}).strict(),_.object({...ji,type:_.literal("open_url"),close:_.boolean(),url:jp}).strict(),_.object({...ji,type:_.literal("claim_offer"),close:_.boolean(),couponId:_.uuid()}).strict()]),fS=_.object({defaultLocale:nn,locales:_.record(nn,_.record(Me,_.string().max(cn.stringLength)))}).strict(),Hs=_.enum(["popup","paywall","onboarding","page"]),cR={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},gS=_.discriminatedUnion("type",[_.object({type:_.literal("modal"),size:_.enum(["sm","md","lg"])}).strict(),_.object({type:_.literal("sheet"),size:_.enum(["sm","md","lg"])}).strict(),_.object({type:_.literal("fullscreen")}).strict()]),uR={sm:360,md:420,lg:560},hS=_.object({kind:_.literal("screen"),schemaVersion:_.literal($y),name:_.string().trim().min(1).max(80),surface:Hs,initialPageId:Ni.optional(),presentation:gS,theme:Rp,pages:_.array(_.object({id:Ni,name:_.string().trim().min(1).max(60),root:Dp,theme:Rp.optional(),editorPosition:_.object({x:_.number().finite().min(-1e5).max(1e5),y:_.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(cn.pages),strings:fS,actions:_.array(mS).max(cn.actions)}).strict();function Ct(e,t){for(let n of e.pages)hn(n.root,t)}function lR(e,t){return{...e,pages:e.pages.map((n,r)=>r===0?{...n,root:t}:n)}}var Rt=hS.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 o=new Set;for(let l of e.actions)o.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let a=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}`),a.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let s=new Set,c=0,u=!1;Ct(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"&&!o.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 p of Object.keys(l.html))i.includes(p)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${p}`);if(l.type==="image")for(let p of Object.keys(l.localizedSrc??{}))i.includes(p)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${p}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${cn.depth} \u5C42`)});function hn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)hn(i,t,n+1,e)}function Ws(e){let t=[],n=new Set;return Ct(e,r=>{let i=(o,a,s)=>{n.has(o)||(n.add(o),t.push({key:o,nodeId:r.id,nodeType:r.type,field:a,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 bS(e,t,n){if(t.field==="html"){let r;return Ct(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Fi(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 jr(e){let t=Ws(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(o=>!bS(e,o,r)?.trim()).map(o=>o.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function dR(e){return Fp(e,!0)}function pR(e){return Fp(e,!1)}function Fp(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(p=>p[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 p=e.actions.find(g=>g.id===u.action);p?.type==="claim_offer"&&d&&d!==p.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(p=>i(p,d))}e.pages.forEach(u=>i(u.root));let o=[],a=Rt.safeParse(e);a.success||n.push(...a.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 qo(l))n.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${d}`);Ct(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(p=>p[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(...Gs(d).map(p=>`HTML ${u.id}\uFF1A${p}`));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&&Fi(e,u.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(kr(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(kr(e)))Fi(e,u)||n.push(`Product selection scope ${u} must reference a UI node`);let s=jr(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`));Ws(e).length===0&&!e.pages.some(u=>_S(u.root))&&n.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let c=new Set;Ct(e,u=>{u.type==="button"&&c.add(u.action)});for(let u of e.actions)!c.has(u.id)&&!e.pages.some(l=>yS(l.root,u.id))&&o.push(`\u52A8\u4F5C ${u.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:n,warnings:o}}function _S(e){let t=!1;return hn(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function yS(e,t){let n=!1;return hn(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 SS(e){return jr(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function Qs(e,t){return _o(t,SS(e),e.strings.defaultLocale)}function mR(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let a of Ws(e)){if(a.field==="html"||a.field==="src")continue;let s=n[a.key]?.trim()?n[a.key]:r[a.key];s!==void 0&&(i[a.key]=s)}let o=a=>{if(a.type==="stack")return{...a,children:a.children.map(o)};if(a.type==="custom_html"){let s=a.html[t]?.trim()?a.html[t]:a.html[e.strings.defaultLocale];return{...a,html:s===void 0?{}:{[t]:s}}}if(a.type==="image"){let{localizedSrc:s,...c}=a;return{...c,src:s?.[t]??s?.[e.strings.defaultLocale]??a.src}}return a};return{...e,pages:e.pages.map(a=>({...a,root:o(a.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function xS(e,t){let n=null;return hn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Fi(e,t){for(let n of e.pages){let r=xS(n.root,t);if(r)return r}return null}function fR(e){let t=Xn(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function gR(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;if(Ct(e,o=>{if(o.type==="plan_picker"){let s=i[o.id];typeof s=="string"&&(r[o.id]=n?.pickers[o.id]?.options.includes(s)?s:"");return}if(o.type!=="stack"||!o.interaction)return;let a=Object.hasOwn(i,o.id)?i[o.id]:void 0;["select","tabs"].includes(o.interaction.type)&&typeof a=="string"&&o.children.some(s=>s.id===a)&&(r[o.id]=a),o.interaction.type==="toggle"&&typeof a=="boolean"&&(r[o.id]=a)}),e.surface==="paywall"&&typeof i.__page=="string"&&e.pages.some(o=>o.id===i.__page)&&(r.__page=i.__page),n){let o={...r};for(let[a,s]of Object.entries(i))(typeof s=="string"||typeof s=="boolean")&&(o[a]=s);Object.assign(r,Ip(e,o,n))}return r}import{z as it}from"zod";var vS=it.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Up=it.discriminatedUnion("type",[it.object({type:it.literal("fixed"),productVersionId:it.string().min(1).max(200)}).strict(),it.object({type:it.literal("picker"),pickerId:vS,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 IS=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:")})]),AS=Rt,wS=ne.discriminatedUnion("type",[ne.object({type:ne.literal("checkout"),product:Up}).strict(),ne.object({type:ne.literal("close")}).strict(),ne.object({type:ne.literal("action"),action:IS}).strict()]),Vo=ne.object({schemaVersion:ne.literal(3),kind:ne.literal("paywall"),name:ne.string().trim().min(1).max(80),presentation:On,requirement:Mn.optional(),products:xp,offeringVersionId:ne.uuid().nullable(),offeringId:ne.uuid().nullable(),screen:AS,buttons:ne.record(ne.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),wS)}).strict(),$o=Vo.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 PS(e))t.addIssue({code:"custom",message:r});for(let r of OS(e))t.addIssue({code:"custom",message:r});jr(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 OS(e){let t=e.products.items.map(o=>o.productVersionId),n=kr(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&&(!Mo(e.products.grouping,t)||e.products.grouping.tiers.some(o=>!e.products.grouping.assignments.some(a=>a.tierId===o.id)))&&i.push("grouping");for(let o of Object.values(e.buttons))if(o.type==="checkout"){let a=o.product;if(a.type==="fixed")r.add(a.productVersionId);else{a.allowedProductVersionIds.forEach(c=>r.add(c));let s=!1;n[a.pickerId]&&(s=!0,(a.allowedProductVersionIds.some(c=>!n[a.pickerId].ids.includes(c))||n[a.pickerId].ids.some(c=>!a.allowedProductVersionIds.includes(c)))&&i.push("picker")),Ct(e.screen,c=>{if(c.id!==a.pickerId||c.type!=="plan_picker")return;s=!0,(JSON.stringify(c.planIds)!==JSON.stringify(t)||JSON.stringify(a.allowedProductVersionIds)!==JSON.stringify(t)||c.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let u=c.grouping?{tiers:c.grouping.tiers,assignments:c.grouping.assignments}:void 0;JSON.stringify(u)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(o=>!t.includes(o)))&&i.push("purchase"),Ct(e.screen,o=>{o.type==="stack"&&o.productSlot&&!o.bind?.plan&&i.push(`productBinding:${o.id}`),(o.type==="stack"||o.type==="button")&&o.bind?.plan&&!t.includes(o.bind.plan)&&i.push("binding"),o.type==="plan_picker"&&(!o.planIds?.length||o.planIds.some(a=>!t.includes(a)))&&i.push("binding")}),[...new Set(i)]}function PS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let a of e.screen.pages)r.set(a.id,[]),hn(a.root,s=>{let c=s.type==="button"?s.action:s.type==="stack"?s.purchaseAction:void 0;if(c){let u=e.screen.actions.find(d=>d.id===c);u?.type==="navigate"&&r.get(a.id).push(u.pageId);let l=e.buttons[c];a.id!==n.id&&l&&l.type!=="close"&&t.push(`purchaseScreen:${s.id}`)}a.id!==n.id&&(s.type==="plan_picker"||s.type==="stack"&&s.productSlot)&&t.push(`packageScreen:${s.id}`)});let i=new Set;function o(a){if(!i.has(a)){i.add(a);for(let s of r.get(a)??[])o(s)}}o(e.screen.initialPageId??e.screen.pages[0].id);for(let a of e.screen.pages)i.has(a.id)||t.push(`unreachableScreen:${a.id}`);return[...new Set(t)]}var Mp=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:Vo}).strict(),OR=ne.object({rows:ne.array(Mp).max(200),nextCursor:ne.uuid().nullable()}).strict(),PR=Mp.omit({draft:!0}).extend({name:ne.string(),productCount:ne.number().int().nonnegative()}).strict(),CR=ne.discriminatedUnion("action",[ne.object({action:ne.literal("save"),id:ne.uuid().nullable(),revision:ne.number().int().nonnegative(),document:Vo}).strict(),ne.object({action:ne.enum(["publish","archive"]),id:ne.uuid(),revision:ne.number().int().nonnegative()}).strict()]),ER=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:Vo.shape.buttons}).strict()).max(500),limited:ne.boolean()}).strict();var Lp=kt.strictObject({selector:kt.discriminatedUnion("type",[kt.strictObject({type:kt.literal("paywall"),paywallId:kt.uuid()}),kt.strictObject({type:kt.literal("version"),versionId:kt.uuid()})]),customerId:kt.uuid().optional(),commerce:Er,locale:kt.string().min(1).max(35),requirement:Mn.optional()}),Go=kt.strictObject({id:kt.uuid(),paywallId:kt.uuid(),version:kt.number().int().positive(),document:$o,offering:Tr,capabilities:Lo,check:cr.nullable()}).superRefine((e,t)=>{let n=new Set(ki(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 It}from"zod";var Bp={requestId:It.uuid(),sourceId:It.uuid(),expectedAvailable:Ye},qp=It.discriminatedUnion("action",[It.strictObject({...Bp,action:It.enum(["add","subtract","set_remaining"]),amount:Y}),It.strictObject({...Bp,action:It.literal("edit"),granted:Y,expiresAt:It.iso.datetime({offset:!0}).nullable(),nextResetAt:It.iso.datetime({offset:!0}).nullable(),expectedRevision:It.number().int().nonnegative()})]),Zs=It.strictObject({sourceId:It.uuid(),available:Ye,held:Ye,spent:Ye,adjustmentGrantId:It.uuid().nullable()}),Vp=Zs.extend({granted:Ye,expiresAt:It.iso.datetime({offset:!0}).nullable(),nextResetAt:It.iso.datetime({offset:!0}).nullable(),revision:It.number().int().nonnegative()});import{z as Bt}from"zod";var $p=Bt.discriminatedUnion("action",[Bt.object({action:Bt.literal("upsert"),externalId:Bt.string().min(1).max(128),name:Bt.string().trim().min(1).max(80)}).strict(),Bt.object({action:Bt.literal("archive"),entityId:Bt.uuid()}).strict()]),Gp=Bt.object({id:Bt.uuid(),externalId:Bt.string().min(1).max(128),name:Bt.string().min(1).max(80),archived:Bt.boolean()}).strict();import{z as ft}from"zod";import{z as dr}from"zod";var zp=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Kp=dr.string().regex(/.+\/.+/),Ys=dr.number().min(-100),lr=dr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),CS=dr.strictObject({input:lr,output:lr,cache_read:lr.optional(),cache_write:lr.optional(),reasoning:lr.optional(),input_audio:lr.optional(),output_audio:lr.optional()}),Js=(e,t)=>dr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),zR=dr.strictObject({defaultMarkup:Ys,providerMarkups:Js(dr.string().min(1),Ys),modelMarkups:Js(Kp,Ys),customModels:Js(Kp,CS.partial())});import{z as ae}from"zod";var pr=ae.iso.datetime({offset:!0}),Ln=ae.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),ES=ae.discriminatedUnion("kind",[ae.object({kind:ae.literal("absolute"),from:pr,to:pr}).strict(),ae.object({kind:ae.literal("last_days"),days:ae.union([ae.literal(1),ae.literal(7),ae.literal(30),ae.literal(90)])}).strict(),ae.object({kind:ae.literal("billing_cycles"),membershipId:ae.uuid(),count:ae.number().int().min(1).max(12),includeCurrent:ae.boolean()}).strict()]),Hp=ae.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"),TS=ae.object({key:ae.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:ae.array(ae.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),mr=ae.object({range:ES,timezone:Hp,filterBy:ae.array(TS).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:ae.enum(["hour","day","week","month"]),internal_feature_id:ae.uuid().nullable(),entityId:ae.uuid().nullable(),topN:ae.number().int().min(1).max(50).nullable(),groupBy:ae.union([ae.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),ae.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:ae.object({bucket:pr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid()}).strict().nullable(),limit:ae.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)"})}),Wp=ae.object({from:pr,to:pr,interval:ae.enum(["hour","day","week","month"]),timezone:Hp,rows:ae.array(ae.object({bucket:pr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid(),consumedUnits:Ln,refundedUnits:Ln,reservedUnits:Ln,charged:Ln,refunded:Ln,reserved:Ln,netUnits:Ln,netCharged:Ln}).strict()).max(100),nextCursor:ae.object({bucket:pr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid()}).strict().nullable()}).strict();var Nr=ft.string().regex(/^(0|[1-9]\d{0,29})$/),Qp=ft.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Xs=ft.strictObject({bucket:ft.iso.datetime({offset:!0}),group:ft.string().max(240),isOther:ft.boolean(),internal_feature_id:ft.uuid()}),Zp=ft.strictObject({...mr.shape,groupBy:ft.union([ft.enum(["customer","entity","entitlement"]),ft.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Xs.nullable()}).superRefine((e,t)=>{let n=mr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Yp=ft.strictObject({from:ft.iso.datetime({offset:!0}),to:ft.iso.datetime({offset:!0}),interval:mr.shape.interval,timezone:mr.shape.timezone,rows:ft.array(ft.strictObject({...Xs.shape,eventCount:Nr,units:Qp,tokenEventCount:Nr,tokens:ft.strictObject(Object.fromEntries(zp.map(e=>[e,Nr]))),totalTokens:Nr,providerCostEventCount:Nr,providerCostUsd:Qp,invalidTelemetryEventCount:Nr})).max(100),nextCursor:Xs.nullable()});import{z as et}from"zod";var Jp=et.object({requestId:et.uuid(),items:et.array(et.object({customerId:et.uuid(),command:Ii.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"),Xp=et.object({batchId:et.uuid(),after:et.number().int().min(-1).max(999),limit:et.number().int().min(1).max(100)}).strict(),em=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:Ai.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 x}from"zod";var RS=x.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),tm=x.enum(["draft","active","paused","archived"]),nm=x.string().min(1).max(256),rm=x.array(nm).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),kS=x.strictObject({duration:x.enum(["day","week","month","year"]),length:x.number().int().min(1).max(3660)}),jS=x.strictObject({internal_feature_id:x.uuid(),allowance:x.number().nonnegative().max(1e15).nullable(),expiry:kS.nullable()}),NS=x.discriminatedUnion("type",[x.strictObject({type:x.literal("feature_grant"),grants:x.array(jS).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),x.strictObject({type:x.literal("free_product"),productId:nm,duration:rn}),x.strictObject({type:x.literal("invoice_credits"),amount:x.number().positive().max(1e8),duration:rn,rollover:x.boolean(),productIds:rm})]),DS=x.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),im=x.object({key:DS,name:x.string().trim().min(1).max(80),configuration:NS}).strict(),om=x.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),ec=x.object({code:om,maxUses:x.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:x.boolean()}).strict(),am=x.object({key:x.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:x.string().trim().min(1).max(80),rewardId:x.uuid(),redeemOn:x.enum(["customer_creation","checkout"]),receivedBy:x.enum(["referrer","all"]),maxRedemptions:x.number().int().min(1).max(1e6).nullable(),productIds:rm,excludeTrial:x.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),sm={id:x.uuid(),projectId:x.uuid(),environmentId:x.uuid(),revision:x.number().int().nonnegative(),status:tm,createdAt:x.iso.datetime({offset:!0}),updatedAt:x.iso.datetime({offset:!0})},FS=im.extend(sm).strict(),US=am.safeExtend(sm).strict(),ak=x.strictObject({id:x.uuid(),key:x.string(),name:x.string(),type:RS,status:tm}),sk=x.discriminatedUnion("action",[x.object({action:x.literal("save"),id:x.uuid().nullable(),revision:x.number().int().nonnegative(),input:im}).strict(),x.object({action:x.enum(["activate","pause","resume","archive","delete"]),id:x.uuid(),revision:x.number().int().nonnegative()}).strict()]),ck=x.discriminatedUnion("action",[x.object({action:x.literal("save"),id:x.uuid().nullable(),revision:x.number().int().nonnegative(),input:am}).strict(),x.object({action:x.enum(["activate","pause","resume","archive","delete"]),id:x.uuid(),revision:x.number().int().nonnegative()}).strict()]),cm=x.object({id:x.uuid(),rewardId:x.uuid(),programId:x.uuid().nullable(),customerId:x.uuid(),referrerId:x.uuid().nullable(),status:x.enum(["pending","applied"]),result:x.record(x.string(),x.unknown()).nullable(),createdAt:x.iso.datetime({offset:!0})}).strict(),um=x.object({code:om,requestId:x.uuid()}).strict(),lm=x.strictObject({redemptionId:x.uuid(),currency:W,requestId:x.uuid(),accepted:x.literal(!0)}),MS=x.strictObject({type:x.literal("checkout"),orderId:x.uuid(),productVersionId:x.uuid(),currency:W,duration:rn,renewalAmountMinor:x.number().int().positive().max(1e8),status:x.enum(["created","pending","trialing","paid","cancelled","failed"]),url:x.url().nullable()}),dm=x.discriminatedUnion("type",[MS,x.strictObject({type:x.literal("subscription"),operationId:x.uuid(),membershipId:x.uuid(),productVersionId:x.uuid(),currency:W,duration:rn,renewalAmountMinor:x.number().int().positive().max(1e8),status:x.enum(["pending","running","applied","failed"])})]),pm=x.object({programId:x.uuid(),requestId:x.uuid()}).strict(),mm=x.object({id:x.uuid(),programId:x.uuid(),code:ec.shape.code,createdAt:x.iso.datetime({offset:!0})}).strict(),uk=x.object({rows:x.array(FS).max(100),nextCursor:x.uuid().nullable()}).strict(),lk=x.object({rows:x.array(US).max(100),nextCursor:x.uuid().nullable()}).strict(),LS=ec.extend({id:x.uuid(),redemptions:x.number().int().nonnegative()}).strict(),BS=x.strictObject({id:x.uuid(),programId:x.uuid().nullable(),customerId:x.uuid().nullable(),referrerId:x.uuid().nullable(),code:x.string().nullable(),status:x.enum(["pending","triggered","applied"]),createdAt:x.iso.datetime({offset:!0})}),dk=x.object({codes:x.array(LS).max(100),redemptions:x.array(BS).max(100),customers:x.record(x.uuid(),x.string()),codesCursor:x.uuid().nullable(),redemptionsCursor:x.uuid().nullable()}).strict(),pk=x.discriminatedUnion("action",[x.object({action:x.literal("create"),rewardId:x.uuid(),revision:x.number().int().nonnegative(),input:ec}).strict(),x.object({action:x.literal("remove"),rewardId:x.uuid(),revision:x.number().int().nonnegative(),codeId:x.uuid()}).strict()]);import{z as y}from"zod";import{z as J}from"zod";var tc=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"),Dr=J.intersection(Ut,J.object({tags:tc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ko=J.string().trim().max(80),zo=J.union([J.email().max(254),J.literal("")]),Ho=J.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),fm=J.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),gm=J.object({externalUserId:fm.optional(),name:Ko.default(""),email:zo.default(""),attributes:Dr.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Fr=J.discriminatedUnion("type",[J.strictObject({type:J.literal("id"),value:J.uuid()}),J.strictObject({type:J.literal("externalUserId"),value:fm})]),Ur=J.strictObject({name:Ko.optional(),email:zo.optional(),attributes:Dr.optional(),fingerprint:Ho.optional()}),fr=e=>!e.customerData||e.customer?.type==="externalUserId",gr="customerData requires an externalUserId customer",Mr=J.object({id:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),name:Ko,email:zo,attributes:Dr,createdAt:J.iso.datetime()}).strict(),hm=J.object({customer:Mr,changed:J.boolean(),replayed:J.boolean()}).strict(),qS=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()]),VS=J.object({name:Ko.optional(),email:zo.optional(),attributes:Dr.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:tc,remove:tc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),nc=J.object({lookup:qS}).strict(),bm=nc.extend({requestId:J.uuid(),patch:VS}).strict(),_m=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(),ym=J.object({customers:Mr.array(),hasMore:J.boolean(),total:J.number().int().nonnegative().nullable(),evaluatedAt:J.iso.datetime()}).strict();import{z as Re}from"zod";import{z as Wo}from"zod";var rc=Wo.strictObject({eventsEnabled:Wo.boolean(),experimentViewsEnabled:Wo.boolean(),featureUsageEnabled:Wo.boolean()}),_k=Object.freeze({eventsEnabled:!1,experimentViewsEnabled:!0,featureUsageEnabled:!1});function yk(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as N}from"zod";var ic=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),$S=N.strictObject({attribute:N.string().optional(),seed:N.string(),hashVersion:N.literal(2),ranges:N.array(ic).max(100)}),GS=N.strictObject({id:N.string().min(1).max(255),condition:xt,gate:N.boolean().optional()}),KS=N.strictObject({key:N.string().optional(),name:N.string().optional(),passthrough:N.boolean().optional()}),Sm={condition:xt.optional(),parentConditions:N.array(GS).max(100).optional(),weights:N.array(N.number().min(0).max(1)).max(20).optional(),coverage:N.number().min(0).max(1).optional(),hashAttribute:N.string().optional(),fallbackAttribute:N.string().optional(),hashVersion:N.literal(2).optional(),disableStickyBucketing:N.boolean().optional(),bucketVersion:N.number().int().nonnegative().optional(),minBucketVersion:N.number().int().nonnegative().optional(),filters:N.array($S).max(100).optional(),ranges:N.array(ic).max(20).optional(),meta:N.array(KS).max(20).optional(),seed:N.string().optional(),name:N.string().optional(),phase:N.string().optional()},Lr=N.strictObject({...Sm,key:N.string().min(1).max(255),variations:N.tuple([_e,_e]).rest(_e).refine(e=>e.length<=20),urlPatterns:N.array(N.strictObject({include:N.boolean(),type:N.enum(["regex","simple"]),pattern:N.string()})).max(100).optional(),force:N.number().int().nonnegative().optional(),active:N.boolean().optional(),persistQueryString:N.boolean().optional()}),oc=N.strictObject({value:_e,variationId:N.number().int(),key:N.string(),name:N.string().optional(),bucket:N.number().optional(),passthrough:N.boolean().optional(),inExperiment:N.boolean(),hashUsed:N.boolean().optional(),hashAttribute:N.string(),hashValue:N.string(),featureId:N.string().nullable(),stickyBucketUsed:N.boolean().optional()}),zS=N.strictObject({...Sm,id:N.string().max(255).optional(),force:_e.optional(),variations:N.array(_e).min(2).max(20).optional(),key:N.string().optional(),range:ic.optional(),tracks:N.array(N.strictObject({experiment:Lr,result:oc})).max(100).optional()}),HS=N.strictObject({defaultValue:_e.optional(),rules:N.array(zS).max(500).optional()}),Ui=N.record(N.string(),N.union([N.strictObject({type:N.literal("hashed"),attributeKey:N.string(),values:N.array(N.string().regex(/^[a-f0-9]{64}$/))}),N.strictObject({type:N.literal("list"),attributeKey:N.string(),values:N.array(N.union([N.string(),N.number()]))}),N.strictObject({type:N.literal("condition"),condition:xt})])),bn=N.strictObject({scope:Fe,generation:N.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:N.iso.datetime({offset:!0}),expiresAt:N.iso.datetime({offset:!0}).nullable(),features:N.record(N.string(),HS),savedGroups:Ui,experiments:N.record(N.uuid(),Lr)});var xm=bn.extend({analyticsConfig:rc,remoteFeatures:Re.array(Re.string().min(1).max(255)).max(500)}),vm=Re.strictObject({attributes:Ut,features:Re.array(Re.string().min(1).max(255)).min(1).max(500).optional(),customerId:Re.uuid().optional()}),WS=Re.strictObject({value:_e,source:Re.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Re.boolean(),off:Re.boolean(),ruleId:Re.string(),experimentResult:oc.optional()}),Im=Re.strictObject({generation:bn.shape.generation,evaluatedAt:bn.shape.evaluatedAt,expiresAt:bn.shape.expiresAt,features:Re.record(Re.string(),WS)}),Am=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(),_e).default({}),deviceId:Re.string().min(1).max(255).optional(),sessionId:Re.string().min(1).max(255).optional()})).min(1).max(100)}),wm=Re.strictObject({inserted:Re.number().int().nonnegative(),duplicates:Re.number().int().nonnegative(),rejected:Re.number().int().nonnegative(),skipped:Re.number().int().nonnegative(),analyticsConfig:rc});var QS=y.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"]),Om={scope:Fe,permissions:y.array(QS),expiresAt:y.iso.datetime().nullable()},lj=y.discriminatedUnion("kind",[y.object({...Om,kind:y.literal("server"),keyId:y.string().min(1)}),y.object({...Om,kind:y.literal("customer"),customerId:y.string().min(1),identityKind:y.enum(["identified","guest"]),expiresAt:y.iso.datetime()})]),M=y.object({requestId:y.uuid(),scope:Fe}).strict(),ZS=gm.safeExtend({fingerprint:Ho.optional()}).strict(),YS=M.extend({customer:Mr,created:y.boolean()}),JS=y.enum(["unassigned","unknown","scheduled","active","expired"]),dj=y.object({customerId:y.string().min(1),evaluatedAt:y.iso.datetime(),status:JS,validity:ps.nullable(),planVersion:El.nullable(),holdings:y.array(y.object({id:y.uuid(),planVersionId:y.uuid(),source:y.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:y.array(y.object({featureId:y.string(),featureKey:y.string(),featureName:y.string(),type:y.enum(["boolean","metered"]),allowance:y.number().int().nonnegative().nullable(),used:y.number().finite().nonnegative(),remaining:y.number().finite().nonnegative().nullable(),allowed:y.boolean(),sources:y.array(y.object({holdingId:y.uuid(),planVersionId:y.uuid(),group:y.string(),kind:y.enum(["main","addon"]),allowance:y.number().nullable()})).optional()}))});function Pm(){return M.extend({offer:di.nullable(),reason:yo.nullable()})}var U={getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:y.strictObject({}),response:M.extend({payload:xm})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:vm,response:M.merge(Im)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Am,response:M.merge(wm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid(),sourceId:y.uuid()}),response:M.extend({balance:Vp})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:qp}),response:M.extend({balance:Zs})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:y.strictObject({internal_feature_id:y.uuid(),customerId:y.uuid().optional(),entityId:y.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:M.extend({internal_feature_id:y.uuid(),config:ns,model_markups:fo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid(),query:wo}),response:M.extend({usage:wi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:Td}),response:M.extend({usage:wi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:Id}),response:M.extend({grant:Ps})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ad,response:M.extend({grants:wd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:y.union(mp.options.map(e=>e.extend({customerId:y.uuid().optional(),customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:M.extend({operation:fp})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:np.extend({customerId:y.uuid().optional()}),response:M.extend({setup:Us})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:rp.extend({customerId:y.uuid().optional()}),response:M.extend({setup:Us})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:Xd.safeExtend({customerId:y.uuid()}),response:M.extend({batch:Ti})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:To.extend({customerId:y.uuid()}),response:M.extend({batch:Ti})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:To.extend({customerId:y.uuid()}),response:M.extend({batch:Ti})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:To.extend({customerId:y.uuid()}),response:M.extend({batch:Ti})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:y.discriminatedUnion("action",[Ro.options[0].extend({customerId:y.uuid()}),Ro.options[1].extend({customerId:y.uuid()}),Ro.options[2].extend({customerId:y.uuid()})]),response:M.extend({trial:Fs})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:ep.extend({customerId:y.uuid()}),response:M.extend({trial:Fs})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:No,response:M.extend({subscriptions:lp})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:No,response:M.extend({purchases:dp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:sp,response:M.extend({conflicts:pp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:cp,response:M.extend({resolution:up})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:op,response:M.extend({verification:ap})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Gd.safeExtend({customerId:y.uuid().optional()}),response:M.extend({quote:Ci})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:sr.extend({customerId:y.uuid().optional(),intent:y.enum(["confirm","cancel"]).optional()}),response:M.extend({operation:Cr})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:sr.extend({customerId:y.uuid().optional()}),response:M.extend({operation:Cr})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Hd.safeExtend({customerId:y.uuid().optional()}),response:M.extend({quote:Qd})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:sr.extend({customerId:y.uuid().optional(),intent:y.enum(["confirm","cancel"]).optional()}),response:M.extend({operation:Ns})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:sr.extend({customerId:y.uuid().optional()}),response:M.extend({operation:Ns})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Zd.safeExtend({customerId:y.uuid()}),response:M.extend({quote:Jd})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:sr.extend({customerId:y.uuid()}),response:M.extend({operation:Eo})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:sr.extend({customerId:y.uuid()}),response:M.extend({operation:Eo})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Xl,response:M.extend({controls:_s})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:zl,response:M.extend({prepared:Wl})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Ql,response:M.extend({authorization:So})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:rd,response:M.extend({coupons:id})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Zl,response:M.extend({authorization:So})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:td,response:M.extend({invoices:nd})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:ed,response:M.extend({invoice:fi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:y.object({customerId:y.uuid(),command:Jl}).strict(),response:M.extend({controls:_s})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:y.object({customerId:y.uuid(),command:$p}).strict(),response:M.extend({entity:Gp})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid().nullable(),query:Zp}),response:M.extend({analytics:Yp})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:y.object({customerId:y.uuid().nullable(),query:mr}).strict(),response:M.extend({analytics:Wp})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Jp,response:M.extend({batchId:y.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Xp,response:M.extend({batch:em})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:gp.extend({customerId:y.string().min(1).optional()}),response:M.extend({check:cr})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Lp,response:M.extend({paywall:Go})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:y.strictObject({selector:yp,customerId:y.string().min(1).optional(),commerce:Er,requirement:Mn.optional()}),response:M.extend({offering:Tr,candidates:y.array(Ls).max(20),availability:y.array(y.strictObject({productVersionId:y.uuid(),available:y.boolean(),reason:y.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:cr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),entityId:y.uuid().optional()}).strict(),response:M.extend({holdings:Rd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),query:jd}).strict(),response:M.extend({ledger:Nd})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Od.extend({customerId:y.uuid().optional()}),response:M.extend({detail:Pd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Cs.safeExtend({customerId:y.uuid().optional()}),response:M.extend({statement:Cd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),command:Ii.options[0]}).strict(),response:M.extend({quote:Sd})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:y.strictObject({customerId:y.uuid(),command:y.union([y.strictObject({eventName:y.string().min(1),quantity:Y.optional(),properties:Xe.optional(),entityId:y.uuid().optional(),idempotencyKey:y.string().min(1).max(120)}),y.strictObject({internal_feature_id:y.uuid(),quantity:Y.optional(),properties:Xe.optional(),entityId:y.uuid().optional(),idempotencyKey:y.string().min(1).max(120)})])}),response:M.extend({receipts:y.array(Ai).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:y.object({customerId:y.uuid(),command:Ii.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:M.extend({receipt:Ai})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:um,response:M.extend({redemption:cm})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:pm,response:M.extend({referralCode:mm})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:lm,response:M.extend({checkout:dm})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Fd,response:M.extend({seats:Rs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Ud,response:M.extend({seats:Rs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:ZS,response:YS},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:nc,response:M.extend({customer:Mr})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:_m,response:M.extend(ym.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:bm,response:M.extend(hm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:y.object({customerId:y.uuid()}).strict(),response:M.extend({customerToken:y.string().min(1),expiresAt:y.iso.datetime(),sessionId:y.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:y.strictObject({customerId:y.uuid(),customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:M.extend({customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:y.uuid(),expiresAt:y.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:y.strictObject({customerId:y.uuid(),sessionId:y.uuid().optional()}),response:M.extend({revoked:y.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:y.strictObject({guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ho.optional()}),response:M.extend({customerId:y.uuid(),guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:y.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:y.strictObject({guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:M.extend({customerId:y.uuid(),customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:y.uuid(),expiresAt:y.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:y.strictObject({guestToken:y.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:y.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:y.uuid()}),response:M.extend({customer:Mr,switched:y.boolean(),replayed:y.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:y.strictObject({code:y.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:y.uuid()}),response:Pm()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:y.object({}).strict(),response:M.extend({offers:y.array(di)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"server",request:y.object({customerId:y.string().min(1).max(255),couponId:y.uuid(),requestId:y.uuid()}).strict(),response:Pm()}},pj={getFeatures:U.getFeatures,evaluateFeatures:U.evaluateFeatures,trackEvents:U.trackEvents,setupPayment:U.setupPayment,readPaymentSetup:U.readPaymentSetup,previewSubscriptionBatch:U.previewSubscriptionBatch,confirmSubscriptionBatch:U.confirmSubscriptionBatch,readSubscriptionBatch:U.readSubscriptionBatch,abandonSubscriptionBatch:U.abandonSubscriptionBatch,manageSubscriptionTrial:U.manageSubscriptionTrial,readSubscriptionTrial:U.readSubscriptionTrial,listSubscriptions:U.listSubscriptions,listPurchases:U.listPurchases,listSubscriptionConflicts:U.listSubscriptionConflicts,retrySubscriptionConflict:U.retrySubscriptionConflict,readAiPricing:U.readAiPricing,readUsage:U.readUsage,setUsage:U.setUsage,previewRefund:U.previewRefund,refund:U.refund,readRefund:U.readRefund,previewUpdate:U.previewUpdate,update:U.update,readSubscriptionUpdate:U.readSubscriptionUpdate,restoreNativePurchase:U.restoreNativePurchase,verifySubscriptions:U.verifySubscriptions,previewAttach:U.previewAttach,attach:U.attach,readSubscriptionOperation:U.readSubscriptionOperation,manageBalanceGrant:U.manageBalanceGrant,readBalanceSource:U.readBalanceSource,adjustBalance:U.adjustBalance,listBalanceGrants:U.listBalanceGrants,readBillingControls:U.readBillingControls,prepareBillingAuthorization:U.prepareBillingAuthorization,confirmBillingAuthorization:U.confirmBillingAuthorization,setBillingCoupons:U.setBillingCoupons,revokeBillingAuthorization:U.revokeBillingAuthorization,listBillingInvoices:U.listBillingInvoices,confirmBillingAdjustment:U.confirmBillingAdjustment,manageBillingLimits:U.manageBillingLimits,createCustomer:U.createCustomer,getCustomer:U.getCustomer,listCustomers:U.listCustomers,updateCustomer:U.updateCustomer,createSession:U.createSession,renewSession:U.renewSession,revokeSessions:U.revokeSessions,createGuestCustomer:U.createGuestCustomer,resumeGuestSession:U.resumeGuestSession,claimGuestCustomer:U.claimGuestCustomer,checkEntitlement:U.checkEntitlement,resolveOffering:U.resolveOffering,resolvePaywall:U.resolvePaywall,readHoldings:U.readHoldings,readLedger:U.readLedger,readBillingInvoice:U.readBillingInvoice,readCreditStatement:U.readCreditStatement,quoteBalance:U.quoteBalance,trackUsage:U.trackUsage,mutateBalance:U.mutateBalance,manageUsageEntity:U.manageUsageEntity,readUsageAnalytics:U.readUsageAnalytics,readCreditAnalytics:U.readCreditAnalytics,submitUsageBatch:U.submitUsageBatch,readUsageBatch:U.readUsageBatch,listOffers:U.listOffers,grantOffer:U.grantOffer,redeemCoupon:U.redeemCoupon,redeemReward:U.redeemReward,createReferralCode:U.createReferralCode,claimRewardProduct:U.claimRewardProduct,readSeats:U.readSeats,manageSeat:U.manageSeat};import{z as ac}from"zod";var XS="[a-f0-9]{64}",Cm="[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",e0="[a-zA-Z][a-zA-Z0-9_.-]{0,63}",t0="[a-z]{2,3}(?:-[A-Z][a-z]{3})?(?:-(?:[A-Z]{2}|[0-9]{3}))?",sc=new RegExp(`^/web-view/screens/(${XS})/(?:funnel/(${Cm})/(${e0})|paywall/(${Cm}))/(${t0})$`),Em=ac.string().max(256).regex(sc,"Invalid screen render address"),Tm=ac.union([Em,ac.string().max(512).regex(new RegExp(`^(?:https://[a-z0-9.-]+(?::[0-9]{1,5})?|http://(?:localhost|127\\.0\\.0\\.1)(?::[0-9]{1,5})?)${sc.source.slice(1)}`),"Invalid screen render URL")]);function bj(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 Em.parse(t)}function _j(e){let t=sc.exec(e);if(!t||!nn.safeParse(t[5]).success)return null;let[,n,r,i,o,a]=t;return r?{kind:"funnel",tag:n,versionId:r,screenId:i,locale:a}:{kind:"paywall",tag:n,versionId:o,locale:a}}var yj={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},xj="00000000-0000-0000-0000-000000000000";var km={primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},Mi=(e,t,n,r,i)=>({kind:"screen",schemaVersion:4,name:e,surface:"popup",presentation:{type:"modal",size:"md"},theme:{...km},pages:[{id:"main",name:"\u4E3B\u9875\u9762",root:t}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":n,en:r}},actions:i}),Br=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}}}),Qo={id:"dismiss",type:"close",event:"popup.dismissed",properties:{},close:!0},Rm=[{id:"blank",label:"\u7A7A\u767D",description:"\u4E00\u4E2A\u6807\u9898\u548C\u4E00\u4E2A\u6309\u94AE\uFF0C\u4ECE\u96F6\u5F00\u59CB\u642D\u3002",document:Mi("\u672A\u547D\u540D\u5F39\u7A97",Br([{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"},[Qo])},{id:"announcement",label:"\u516C\u544A",description:"\u65B0\u529F\u80FD\u6216\u91CD\u8981\u901A\u77E5\uFF0C\u4E00\u4E2A\u4E3B\u6309\u94AE\u3002",document:Mi("\u65B0\u529F\u80FD\u516C\u544A",Br([{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},Qo])},{id:"upgrade",label:"\u5347\u7EA7\u5230 Pro",description:"\u5217\u51FA\u51E0\u9879\u6743\u76CA\uFF0C\u5F15\u5BFC\u5347\u7EA7\u3002",document:Mi("\u5347\u7EA7\u5230 Pro",Br([{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},Qo])},{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:{...Mi("\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},Qo]),theme:{...km,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:Mi("\u6EE1\u610F\u5EA6\u8C03\u67E5",Br([{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 Zo(e="blank"){let t=Rm.find(n=>n.id===e)??Rm[0];return structuredClone(t.document)}var n0=(e,t,n)=>({type:"stack",id:e,name:"Web \u81EA\u9002\u5E94\u5E03\u5C40",direction:"horizontal",align:"center",justify:"center",children:[{...Br(t),id:`${e}_intro`,name:"\u4ECB\u7ECD",style:{width:480,gap:20,padding:{top:0,right:0,bottom:0,left:0}}},{...Br(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 Ij(e,t="blank"){let n=Zo(t);if(e==="popup"||(n.surface=e,n.presentation={type:"fullscreen"},e==="page"))return n;if(e==="paywall"){let r=Zo("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].root.children;return r.pages[0].root=n0("root",[...i.slice(0,2),{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}}],i.slice(2)),{...r,surface:e,presentation:{type:"fullscreen"},name:"\u9AD8\u7EA7\u529F\u80FD\u4ED8\u8D39\u5899"}}return{...n,surface:e,presentation:{type:"fullscreen"}}}function jm(e,t){if(t!=="en"&&t!=="zh-CN")throw new Error("Unsupported blank content language");let n=t==="en"?{popup:"popup",paywall:"paywall",onboarding:"funnel",page:"page"}:{popup:"\u5F39\u7A97",paywall:"\u4ED8\u8D39\u5899",onboarding:"\u5F15\u5BFC\u6D41\u7A0B",page:"\u9875\u9762"},r=Zo();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:{...r.pages[0].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 fe}from"zod";var Li=fe.number().int().min(0).max(1e4),Ej=fe.strictObject({couponId:fe.uuid(),couponRevision:fe.number().int().nonnegative(),savedGroupId:fe.uuid(),savedGroupRevision:fe.number().int().nonnegative(),savedGroupName:fe.string().min(1).max(128),count:Li,snapshotHash:fe.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:fe.iso.datetime({offset:!0})}),r0=fe.strictObject({id:fe.uuid(),couponId:fe.uuid(),couponName:fe.string().min(1).max(80),savedGroupId:fe.uuid(),savedGroupName:fe.string().min(1).max(128),savedGroupRevision:fe.number().int().nonnegative(),status:fe.enum(["pending","running","completed"]),total:Li,issued:Li,skipped:Li,remaining:Li,createdAt:fe.iso.datetime({offset:!0}),completedAt:fe.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)),i0=fe.strictObject({id:fe.uuid(),customerId:fe.uuid(),customerName:fe.string().max(255),position:fe.number().int().min(1).max(1e4),status:fe.enum(["pending","issued","skipped"]),grantId:fe.uuid().nullable(),reason:yo.nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),Tj=fe.strictObject({batch:r0,recipients:fe.array(i0).max(50),nextPosition:fe.number().int().min(1).max(1e4).nullable()}),Rj=fe.discriminatedUnion("action",[fe.strictObject({action:fe.literal("create"),requestId:fe.uuid(),couponId:fe.uuid(),couponRevision:fe.number().int().nonnegative(),savedGroupId:fe.uuid(),savedGroupRevision:fe.number().int().nonnegative(),snapshotHash:fe.string().regex(/^[a-f0-9]{64}$/)}),fe.strictObject({action:fe.literal("process"),batchId:fe.uuid()})]);import{z as B}from"zod";var At=B.number().int().min(0),Bi=B.iso.datetime({offset:!0}),Yo=B.strictObject({internalId:B.uuid(),version:B.number().int().positive()}),Nm=B.enum(["subscription_change_required","unsupported_operation_input"]),o0=B.enum([...Nm.options,"internal_error"]),Nj=B.strictObject({productId:B.string().min(1),productName:B.string(),from:Yo,to:Yo,noBillingChanges:B.boolean(),counts:B.strictObject({customers:At,movable:At,blocked:At,unsupported:At,canceled:At,custom:At}),rows:B.array(B.strictObject({customerId:B.uuid(),customerKey:B.string().nullable(),name:B.string().nullable(),email:B.string().nullable(),holdings:B.number().int().positive(),outcome:B.enum(["move","blocked","unsupported"]),reason:Nm.nullable()})).max(50),nextCursor:B.uuid().nullable()}),a0=B.enum(["queued","running","succeeded","no_changes","failed","canceled"]),Dm=B.enum(["running","succeeded","skipped","failed"]),Fm=B.strictObject({internalId:B.uuid(),id:B.string().min(1),productId:B.string().min(1),productName:B.string(),from:Yo,to:Yo,noBillingChanges:B.boolean(),retryFailed:B.boolean(),step:B.enum(["queued","received","get_customers","migrate_customers","finished","failed"]),snapshot:B.strictObject({total_customers:At,canceled_customers:At,custom_customers:At,migration_customers:At}),createdAt:Bi,run:B.strictObject({id:B.uuid(),status:a0,errorMessage:B.string().nullable(),createdAt:Bi,startedAt:Bi.nullable(),finishedAt:Bi.nullable()}).nullable(),totals:B.strictObject({succeeded:At,skipped:At,failed:At,running:At,blocked:At,remaining:At})}),s0=B.strictObject({customerId:B.uuid(),customerKey:B.string().nullable(),name:B.string().nullable(),email:B.string().nullable(),status:Dm,skipReason:B.enum(["no_updates_needed","ineligible"]).nullable(),updatedAt:Bi,error:B.strictObject({code:o0,message:B.string().nullable()}).nullable()}),Dj=B.strictObject({migration:Fm,items:B.array(s0).max(50),nextCursor:B.uuid().nullable()}),Fj=B.array(Fm).max(20),Uj=B.discriminatedUnion("action",[B.strictObject({action:B.literal("create"),requestId:B.uuid(),fromInternalId:B.uuid(),toInternalId:B.uuid()}),B.strictObject({action:B.enum(["process","retry","cancel"]),migrationId:B.uuid()})]),Mj=B.discriminatedUnion("action",[B.strictObject({action:B.literal("preview"),from:B.uuid(),to:B.uuid(),after:B.uuid().optional()}),B.strictObject({action:B.literal("read"),migrationId:B.uuid(),status:Dm.optional(),after:B.uuid().optional()}),B.strictObject({action:B.literal("list"),productId:B.string().min(1).max(120)})]);import{z as gt}from"zod";var cc=gt.iso.datetime({offset:!0}),Um=gt.strictObject({internalId:gt.uuid(),productId:gt.string().min(1),name:gt.string(),version:gt.number().int().positive()}),c0=gt.strictObject({id:gt.uuid(),status:gt.literal("scheduled"),effectiveAt:cc,createdAt:cc,entityId:gt.string().nullable(),to:Um,from:Um.extend({customerProductId:gt.uuid(),status:gt.enum(["active","past_due","trialing"]),endsAt:cc.nullable()}).nullable(),scheduleId:gt.uuid().nullable(),providerManaged:gt.boolean()}),qj=gt.array(c0).max(100),Vj=gt.strictObject({customerProductId:gt.uuid()});import{z as qi}from"zod";var u0=qi.url().refine(e=>new URL(e).protocol==="https:"),Kj=qi.strictObject({requestId:qi.uuid()}),zj=qi.strictObject({url:u0,createdAt:qi.iso.datetime()});import{z as Je}from"zod";var Mm=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:Hs,source:Je.enum(["official","private"]),document:Rt,revision:Je.number().int().positive(),archived_at:Je.string().nullable(),created_at:Je.string()}).strict(),Zj=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:Rt}).strict(),Yj=Je.object({projectId:Je.uuid(),environmentId:Je.uuid(),id:Je.uuid(),revision:Je.number().int().positive()}).strict();import{z as q}from"zod";import{z as Ee}from"zod";var Vi=_e;function Lm(e){let t={};for(let[n,r]of Object.entries(e.results??{})){let i=n.split(".");if(i.some(a=>["__proto__","constructor","prototype"].includes(a)))throw new Error("Reserved result path");let o=t;for(let a of i.slice(0,-1)){Object.hasOwn(o,a)||(o[a]={});let s=o[a];if(!s||typeof s!="object"||Array.isArray(s))throw new Error("Ambiguous result path");o=s}o[i[i.length-1]]=r}return{...e.attributes,parameters:e.parameters,answers:e.answers,results:t}}function uc(e,t){return ja(Lm(t),e,t.savedGroups)}function $i(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,o]of Object.entries(r))i.startsWith("$")||t.add(i),i==="$savedGroup"&&o&&typeof o=="object"&&!Array.isArray(o)&&typeof o.attributeKey=="string"&&t.add(o.attributeKey),["$and","$or","$nor","$not"].includes(i)&&n(o)}return n(e),[...t]}import{z as rt}from"zod";var Jo=rt.discriminatedUnion("kind",[rt.object({kind:rt.literal("ledger"),cursor:Oo}).strict(),rt.object({kind:rt.literal("billing"),cursor:rt.uuid()}).strict()]),l0=rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Gi=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"),d0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function lc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>lc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||d0.test(n)||lc(r,t+1)))}var p0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,un=rt.record(l0,_e).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!lc(e)&&!p0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function i2(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 Bm=rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),dc=rt.array(rt.object({key:Bm,componentId:Bm,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"),o2=rt.object({bindings:dc,answers:Gi}).strict();import{z as hr}from"zod";var Bn=hr.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"),Xo=hr.discriminatedUnion("source",[hr.strictObject({source:hr.literal("literal"),value:_e}),hr.strictObject({source:hr.enum(["parameter","answer","attribute","result"]),key:hr.string().min(1).max(255),path:Bn.optional()})]);function ea(e,t){if(!t)return e;for(let n of Bn.parse(t).split(".")){if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function pc(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(_e.parse(ea(n[e.key],e.path)))}function qm(e,t){let n={},r=Object.entries(e).sort(([i],[o])=>i.split(".").length-o.split(".").length||i.localeCompare(o,"en",{numeric:!0}));for(let[i,o]of r){let a=Bn.parse(i).split("."),s=n;for(let u=0;u<a.length-1;u++){let l=a[u];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(a[u+1])?[]:{});let d=Reflect.get(s,l);if(!d||typeof d!="object")throw new Error("Nested input requires an object or array");if(Array.isArray(d)!==/^(0|[1-9]\d*)$/.test(a[u+1]))throw new Error("Nested input container does not match its path");s=d}let c=a.at(-1);if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(c)||Number(c)>s.length))throw new Error("Invalid array binding index");Reflect.set(s,c,pc(o,t))}return n}var ta=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Vm=Ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),na=un.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),mc=Ee.record(ta,Ee.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),m0=Xo,$m=Ee.strictObject({type:Ee.literal("external_task"),endpointId:Ee.uuid(),taskKey:ta,inputs:Ee.record(ta,m0).refine(e=>Object.keys(e).length<=20),outputs:mc}),Gm=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"),g2={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},h2=Ee.strictObject({outcome:Ee.enum(["success","failure"]),data:na});function b2(e,t){let n=na.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]):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function _2(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=pc(i,t);return na.parse(n)}var y2=Ee.discriminatedUnion("operation",[Ee.strictObject({operation:Ee.literal("signal"),runId:Ee.uuid(),nodeId:Vm,eventName:ta,eventId:Ee.uuid(),data:na}),Ee.strictObject({operation:Ee.literal("read_results"),runId:Ee.uuid()})]),S2=Ee.strictObject({scope:Fe,runId:Ee.uuid(),eventId:Ee.uuid(),accepted:Ee.boolean()}),f0=Ee.record(Vm,Vi),x2=Ee.strictObject({scope:Fe,runId:Ee.uuid(),results:f0});import{z as ge}from"zod";var fc=ge.discriminatedUnion("type",[ge.strictObject({type:ge.literal("literal"),value:_e}),ge.strictObject({type:ge.literal("feature"),featureKey:ge.string().min(1).max(128)})]),g0=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:_e}),gc={funnelId:ge.uuid(),requestId:ge.uuid(),customer:Fr,customerData:Ur.optional(),attributes:Ut.refine(e=>!["parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"parameters, answers and results are reserved flow namespaces")},P2=ge.discriminatedUnion("operation",[ge.strictObject({operation:ge.literal("decide"),...gc}).refine(fr,gr),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()})]),C2=ge.strictObject({scope:Fe,decisionId:ge.uuid(),requestId:ge.uuid(),status:ge.enum(["pending","completed","failed"]),decision:g0.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"),E2=ge.strictObject({scope:Fe,decisionId:ge.uuid(),eventId:ge.uuid(),source:ge.literal("caller_reported")});import{z as Ht}from"zod";var Km=Ht.strictObject({type:Ht.literal("bundle"),paywallVersionId:Ht.uuid().optional(),couponIds:Ht.array(Ht.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Bundle Coupons must be unique"),data:_e}),N2=Ht.strictObject({type:Ht.literal("bundle"),paywall:Ht.strictObject({versionId:Ht.uuid(),paywallId:Ht.uuid(),offeringVersionId:Ht.uuid()}).nullable(),coupons:Ht.array(di).max(20),data:_e});import{z as Wt}from"zod";import{z as ht}from"zod";var zm=ht.union([ht.string(),ht.number().finite(),ht.boolean(),ht.null()]),h0=ht.union([zm,ht.array(zm).min(1).max(20)]),b0=ht.record(Bn,h0).refine(e=>Object.keys(e).length<=10),hc=ht.strictObject({path:Bn,type:ht.enum(["string","number","boolean","strings"]),nullable:ht.boolean().optional(),aggregation:ht.enum(["count","exists"]).optional(),where:b0.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 M2(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{let i=hc.parse(r),o=ea(t,i.path);if(i.nullable&&o==null)return[n,null];if(i.aggregation){if(!Array.isArray(o))throw new Error("Collection projection requires an array");let s=o.filter(c=>Object.entries(i.where??{}).every(([u,l])=>{let d=ea(c,u);return Array.isArray(l)?l.some(p=>p===d):l===d}));return[n,i.aggregation==="count"?s.length:s.length>0]}let a=i.type==="strings"?ht.array(ht.string()):i.type==="string"?ht.string():i.type==="number"?ht.number().finite():ht.boolean();return[n,a.parse(o)]}))}var _0=["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"],bc=Wt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),y0=Xo,Hm=Wt.discriminatedUnion("type",[$m,Wt.strictObject({type:Wt.literal("claim_offer"),couponId:Wt.uuid()}),Wt.strictObject({type:Wt.literal("event"),event:bc}),Wt.strictObject({type:Wt.literal("api"),operation:Wt.enum(_0),inputs:Wt.record(Bn,y0).refine(e=>Object.keys(e).length<=40),resultKey:bc,outputs:Wt.record(bc,hc).refine(e=>Object.keys(e).length<=20)})]);function G2(e,t){return qm(e,t)}import{z as S0}from"zod";var _n=S0.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 We=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),x0=q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),Qt={id:We,name:q.string().trim().min(1).max(80),position:q.strictObject({x:q.number().finite(),y:q.number().finite()}).optional()},v0={success:We,cancel:We,unavailable:We,failure:We},_c=q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),yc=q.enum(["same_window","new_window"]),I0=q.discriminatedUnion("type",[q.strictObject({...Qt,type:q.literal("entry"),next:We}),q.strictObject({...Qt,type:q.literal("screen"),screenId:We,presentation:On,outputs:q.record(We,We),offering:q.discriminatedUnion("source",[q.strictObject({source:q.literal("result"),key:_n}),q.strictObject({source:q.literal("fixed"),versionId:q.uuid()})]).optional()}),q.strictObject({...Qt,type:q.literal("offering"),configuration:q.discriminatedUnion("source",[q.strictObject({source:q.literal("fixed"),versionId:q.uuid()}),q.strictObject({source:q.literal("feature"),featureKey:q.string().min(1).max(128)})]),resultKey:_n,next:We}),q.strictObject({...Qt,type:q.literal("coupon"),couponId:q.uuid(),resultKey:_n,next:We}),q.strictObject({...Qt,type:q.literal("output"),value:q.discriminatedUnion("type",[...fc.options,Km,q.strictObject({type:q.literal("result"),key:_n}),q.strictObject({type:q.literal("selection"),screenId:We,offeringKey:_n})])}),q.strictObject({...Qt,type:q.literal("condition"),cases:q.array(q.strictObject({condition:xt,target:We})).min(1).max(50),default:We}),q.strictObject({...Qt,type:q.literal("feature"),featureKey:q.string().min(1).max(128),next:We}),q.strictObject({...Qt,type:q.literal("split"),experimentId:q.uuid(),routes:q.record(x0,We).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:We}),q.strictObject({...Qt,type:q.literal("action"),...v0,execution:Gm,action:Hm}),q.strictObject({...Qt,type:q.literal("external_page"),url:_c,openIn:yc,opened:We,failed:We}),q.strictObject({...Qt,type:q.literal("end"),outcome:q.enum(["completed","closed","ineligible","failed"]),output:fc.optional()}),q.strictObject({...Qt,type:q.literal("wait"),wait:q.discriminatedUnion("type",[q.strictObject({type:q.literal("duration"),delaySeconds:q.number().int().min(1).max(2592e3),elapsed:We}),q.strictObject({type:q.literal("event"),eventName:We,outputs:mc,timeoutSeconds:q.number().int().min(1).max(2592e3),received:We,timeout:We})])})]),Sc=q.strictObject({version:q.literal(4),entry:We,nodes:q.array(I0).min(1).max(tt.flowNodes)}),xc=Sc.superRefine((e,t)=>{A0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function qr(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 A0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,d,p)=>{n.push(l),t?.({message:l,reason:d,path:p?["nodes",e.nodes.indexOf(p)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>tt.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>tt.logicNodes)&&i("Flow node limit exceeded","budget");let o=new Set;for(let l of e.nodes){for(let d of qr(l))d===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(d)||i(`Missing target ${d}`,"missingTarget",l);l.type==="screen"&&(o.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),o.add(l.screenId))}let a=new Set,s=new Set,c=new Set;function u(l){if(a.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){a.add(l),c.add(l);for(let d of qr(r.get(l)))u(d);a.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}function w0(e,t){let n=e.cases.findIndex(r=>uc(r.condition,t));return{ruleIndex:n<0?null:n,target:n<0?e.default:e.cases[n].target}}function iN(e,t,n,r){let i=e.nodes.find(c=>c.id===t.nodeId),o=[...t.history];if(!i||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let a,s=[];switch(n.type){case"start":if(i.type!=="entry")throw new Error("Flow already started");a=i.next;break;case"next":if(i.type!=="screen"||!Object.hasOwn(i.outputs,n.output))throw new Error("Invalid screen output");a=i.outputs[n.output],o.push(i.id);break;case"back":if(i.type!=="screen"||!o.length)throw new Error("No previous screen");if(a=o.pop(),e.nodes.find(c=>c.id===a)?.type!=="screen")throw new Error("Invalid screen history");break;case"condition":if(i.type!=="condition")throw new Error("Not a condition node");{let c=w0(i,r);a=c.target,s.push({nodeId:i.id,...c})}break;case"feature":if(i.type!=="feature")throw new Error("Not a Feature node");a=i.next;break;case"configuration":if(i.type!=="offering"&&i.type!=="coupon")throw new Error("Not a configuration node");a=i.next;break;case"assignment":if(i.type!=="split")throw new Error("Not an Experiment node");if(a=n.variantId===null?i.notParticipating:i.routes[n.variantId],!a)throw new Error("Unknown native Variant key");break;case"result":if(i.type!=="action")throw new Error("Not a capability invocation");a=i[n.result];break;case"page":if(i.type!=="external_page")throw new Error("Not an external page");a=i[n.result];break;case"wait":if(i.type!=="wait")throw new Error("Not a wait node");if(i.wait.type==="duration"){if(n.result!=="elapsed")throw new Error("Invalid timer result");a=i.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid event result");a=i.wait[n.result]}break}if(!e.nodes.some(c=>c.id===a))throw new Error("Target does not exist");return{state:{nodeId:a,history:o.slice(-tt.pages),status:"running"},entered:[a],routed:s}}import{z as F}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 o=t[i];if(r)o==="\\"?i++:o==='"'&&(r=!1);else if(o==='"')r=!0;else if(o===":"||o===",")n++;else if(o==="-"||o>="0"&&o<="9"){let a=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t[i+1]);)i++;let s=t.slice(a,i+1);if(!/[eE]/.test(s))continue;let[c,u]=s.split(/[eE]/),l=c.replace(/^-/,""),d=l.replace(".","").length,p=(l.includes(".")?l.indexOf("."):d)+Number(u),g=p<=0?2-p+d:p>=d?p:d+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}function Wm(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,o=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of $i(c.condition))u.startsWith("results.")&&o(u.slice(8),!0)}if(e.type==="screen"&&e.offering?.source==="result"&&o(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="result"&&o(s.key);let a=e.type==="output"?e.value:e.type==="end"?e.output:null;return a?.type==="result"&&o(a.key),a?.type==="selection"&&o(a.offeringKey),[...i]}import{z as E}from"zod";var Vr=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ra=e=>E.record(E.string(),_e).refine(t=>ln(t)<=e,"Funnel evidence exceeds its byte budget"),mN=E.enum(["presentation","timer","event","operation"]),Ic=E.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Ac=E.discriminatedUnion("type",[E.strictObject({type:E.literal("flag"),key:E.string().min(1).max(128)}),E.strictObject({type:E.literal("experiment"),id:E.uuid()}),E.strictObject({type:E.literal("saved_group"),id:E.uuid()}),E.strictObject({type:E.literal("config"),key:E.string().min(1).max(128)}),E.strictObject({type:E.literal("constant"),key:E.string().min(1).max(128)}),E.strictObject({type:E.literal("paywall_version"),id:E.uuid()}),E.strictObject({type:E.literal("offering_version"),id:E.uuid()}),E.strictObject({type:E.literal("reward"),id:E.uuid()})]),fN=E.strictObject({schemaVersion:E.literal(1),kind:Ic,selector:Ac.nullable(),context:ra(131072),contract:E.strictObject({version:E.number().int().positive(),evaluator:E.string().min(1).max(128),policyRevision:E.number().int().nonnegative()})}).refine(e=>ln(e)<=131072,"Node input exceeds its byte budget"),gN=E.strictObject({schemaVersion:E.literal(1),kind:Ic,outcome:E.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ra(131072),route:E.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ra(131072)}).refine(e=>ln(e)<=131072,"Node result exceeds its byte budget"),hN=E.strictObject({schemaVersion:E.literal(1),operations:E.record(Vr,E.strictObject({attempts:E.number().int().nonnegative(),maxAttempts:E.number().int().min(1).max(5),deadlineAt:E.iso.datetime({offset:!0}),retryAt:E.iso.datetime({offset:!0}).nullable(),error:E.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:E.strictObject({type:Vr,id:E.uuid()}).nullable()}))}).refine(e=>ln(e)<=65536,"Execution state exceeds its byte budget"),br={receiptId:E.uuid()},vc=E.iso.datetime({offset:!0}),bN=E.discriminatedUnion("type",[E.strictObject({type:E.literal("node_entered"),details:E.strictObject({kind:Ic})}),E.strictObject({type:E.literal("presentation_shown"),details:E.strictObject({...br,source:E.literal("client"),occurredAt:vc.optional()})}),E.strictObject({type:E.literal("decision_accepted"),details:E.strictObject(br)}),E.strictObject({type:E.literal("signal_received"),details:E.strictObject({signalId:E.uuid(),nodeId:Vr,eventName:Vr,data:ra(8192),source:E.literal("server"),occurredAt:vc})}),E.strictObject({type:E.literal("signal_consumed"),details:E.strictObject({...br,signalId:E.uuid()})}),E.strictObject({type:E.literal("wait_elapsed"),details:E.strictObject(br)}),E.strictObject({type:E.literal("wait_timeout"),details:E.strictObject(br)}),E.strictObject({type:E.literal("operation_completed"),details:E.strictObject({...br,operation:Vr,reference:E.strictObject({type:Vr,id:E.uuid()}).nullable()})}),E.strictObject({type:E.literal("execution_recovered"),details:E.strictObject({generation:E.number().int().positive(),reason:E.enum(["interrupted","expired_lease","delivery_failed"])})}),E.strictObject({type:E.literal("execution_failed"),details:E.strictObject({generation:E.number().int().positive(),code:E.string().regex(/^[a-z_]{1,64}$/)})}),E.strictObject({type:E.literal("run_completed"),details:E.strictObject({outcome:E.enum(["completed","ineligible","failed"])})}),E.strictObject({type:E.literal("run_closed"),details:E.strictObject({source:E.enum(["client","server","expiry"])})}),E.strictObject({type:E.literal("treatment_used"),details:E.strictObject({...br,source:E.enum(["client","server"]),occurredAt:vc,reference:E.string().min(1).max(128).optional()})})]);var Zt=F.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),O0=F.discriminatedUnion("type",[F.strictObject({id:Zt,type:F.literal("owned"),document:Rt.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")}),F.strictObject({id:Zt,type:F.literal("paywall"),paywallVersionId:F.uuid()})]),Qm=F.strictObject({type:F.enum(["string","number","boolean","strings","json"]),nullable:F.boolean()}),Pc={kind:F.literal("funnel"),schemaVersion:F.literal(3),screens:F.array(O0).max(tt.pages),references:F.record(Zt,Ac).refine(e=>Object.keys(e).length<=500),inputs:F.array(F.strictObject({key:Zt,screenId:Zt,componentId:Zt,required:F.boolean()})).max(tt.questions),variables:F.record(_n,Qm).refine(e=>Object.keys(e).length<=tt.logicNodes),outputSchema:Qm,execution:F.strictObject({runTimeoutSeconds:F.number().int().min(1).max(2592e3),maxTransitions:F.number().int().min(1).max(1e4)})},qt=F.strictObject({...Pc,graph:Sc});function Ym(e,t){let n=(g,f,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:f}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),o=(g,f)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===f);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let a=e.graph.nodes.filter(g=>g.type==="screen");(a.length!==i.size||a.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(f=>g!==f&&f.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,f){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(f)]);let h=s.get(g)??new Set;h.add(f.id),s.set(g,h)}for(let[g,f]of e.graph.nodes.entries()){let h=["graph","nodes",g],v=f.type==="feature"?f.featureKey:f.type==="offering"&&f.configuration.source==="feature"?f.configuration.featureKey:f.type==="output"&&f.value.type==="feature"?f.value.featureKey:f.type==="end"&&f.output?.type==="feature"?f.output.featureKey:null;if(v&&!o("flag",v)&&n("Flag selectors require an explicit GB resource reference","feature",h),f.type==="feature"&&u(f.featureKey,f),(f.type==="offering"||f.type==="coupon")&&u(f.resultKey,f),f.type==="action"&&f.action.type==="api"&&u(f.action.resultKey,f),f.type==="action"&&f.action.type==="external_task")for(let I of Object.keys(f.action.outputs))u(`${f.id}.${I}`,f);if(f.type==="wait"&&f.wait.type==="event")for(let I of Object.keys(f.wait.outputs))u(`${f.id}.${I}`,f);if(f.type==="split"&&!o("experiment",f.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),f.type==="coupon"&&!o("reward",f.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),f.type==="action"&&f.action.type==="claim_offer"&&!o("reward",f.action.couponId)&&n("Coupon claims require a Reward reference","coupon",h),f.type==="offering"&&f.configuration.source==="fixed"&&!o("offering_version",f.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),f.type==="screen"){let I=i.get(f.screenId);if(f.offering?.source==="fixed"&&!o("offering_version",f.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),I?.type==="paywall"&&f.offering&&n("Paywall owns its fixed Offering Version","offering",h),I?.type==="paywall"&&!o("paywall_version",I.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),I?.type==="owned"){jr(I.document).some(R=>!R.complete)&&n("Owned screens require complete local content","translations",h);let S=new Set(I.document.actions.map(R=>R.id));(S.size!==Object.keys(f.outputs).length||Object.keys(f.outputs).some(R=>!S.has(R)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),hn(I.document.pages[0].root,R=>{!f.offering&&(R.type==="plan_picker"||(R.type==="stack"||R.type==="button")&&R.bind?.plan||R.type==="customer_data"&&["customer_plans","credit_packs"].includes(R.data.source))&&n("Product presentation requires an Offering Version","offering",h),R.type==="customer_data"&&Object.values(R.data.outputs??{}).some(D=>!S.has(D))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}if(f.type==="end"&&["completed","ineligible"].includes(f.outcome)&&!f.output&&n("Completed and ineligible ends require a declared output","output",h),f.type==="end"&&f.output?.type==="literal"&&!Zm(e.outputSchema,f.output.value)&&n("Terminal output does not match outputSchema","output",h),f.type==="output"&&f.value.type==="literal"&&!Zm(e.outputSchema,f.value.value)&&n("Terminal output does not match outputSchema","output",h),f.type==="condition")for(let I of f.cases){for(let S of li(I.condition))o("saved_group",S)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let S of $i(I.condition))S.startsWith("answers.")&&!e.inputs.some(R=>R.key===S.slice(8))&&n("Unknown answer reference","answer",h)}if(f.type==="output"&&f.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h),f.value.paywallVersionId&&!o("paywall_version",f.value.paywallVersionId)&&n("Bundle Paywall requires an explicit Version reference","paywall",h);for(let I of f.value.couponIds)o("reward",I)||n("Bundle Coupons require explicit Reward references","coupon",h)}}for(let[g,f]of e.graph.nodes.entries())for(let h of Wm(f,c)){let S=function(R){if(R===f.id)return!0;if(I.has(R))return!1;I.add(R);let D=e.graph.nodes.find(be=>be.id===R);return D?(v.has(R)?D.type==="action"?[D.cancel,D.unavailable,D.failure]:D.type==="wait"&&D.wait.type==="event"?[D.wait.timeout]:[]:qr(D)).some(S):!1};var p=S;if(!Object.hasOwn(e.variables,h)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let v=s.get(h)??new Set,I=new Set;(!v.size||S(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,f]of e.inputs.entries()){let h=i.get(f.screenId),v=h?.type==="owned"?Fi(h.document,f.componentId):null;(v?.type!=="stack"||!v.interaction||!["input","toggle","select","multiselect","tabs"].includes(v.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)g.type==="owned"&&(hn(g.document.pages[0].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 Jm=F.strictObject({...Pc,graph:xc}).superRefine(Ym),Xm=F.strictObject({...Pc,graph:xc,displayName:F.string().trim().min(1).max(80)}).superRefine(Ym);function Zm(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 wc=F.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),ia={requestId:F.uuid(),nodeId:Zt,visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),customerToken:wc.optional()},P0=F.discriminatedUnion("type",[F.strictObject({type:F.literal("screen"),output:Zt,answers:Gi,selection:F.record(Zt,F.union([F.string().max(200),F.boolean()])).optional()}),F.strictObject({type:F.literal("paywall_quote"),actionId:Zt,productVersionId:F.uuid(),offerId:F.uuid().optional(),nativeOffer:Un.optional()}),F.strictObject({type:F.literal("paywall_confirm"),operationId:F.uuid()}),F.strictObject({type:F.literal("paywall_cancel"),operationId:F.uuid()}),F.strictObject({type:F.literal("client_action"),receiptId:F.uuid(),outcome:F.enum(["success","cancel","failure","opened","failed"])})]),C0=F.object({nodeId:Zt,visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),components:F.record(Zt,F.object({resourceKey:F.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:F.number().int().min(1).max(1e5),after:Jo.nullable(),filter:F.enum(["all","purchase","refund","source","usage","debt","settlement"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ki=F.discriminatedUnion("operation",[F.strictObject({operation:F.literal("start"),funnelId:F.uuid(),requestId:F.uuid(),customer:Fr.optional(),customerData:Ur.optional(),locale:F.string().min(1).max(35),parameters:un}).refine(fr,gr),F.strictObject({operation:F.literal("get"),data:C0.optional(),purchase:F.strictObject({receiptId:F.uuid(),operationId:F.uuid()}).optional(),customerToken:wc.optional()}),F.strictObject({operation:F.literal("resume"),requestId:F.uuid(),customerToken:wc.optional()}),F.strictObject({operation:F.literal("submit"),...ia,input:P0}),F.strictObject({operation:F.literal("back"),...ia}),F.strictObject({operation:F.literal("shown"),...ia}),F.strictObject({operation:F.literal("close"),...ia})]);function Oc(e,t){if(e.hidden)return null;if(e.id===t)return e;if(e.type!=="stack")return null;for(let n of e.children){let r=Oc(n,t);if(r)return r}return null}function E0(e,t,n,r,i){let o=e.graph.nodes.find(u=>u.id===t);if(o?.type!=="screen")throw new Error("Input is only accepted on a screen");let a=e.screens.find(u=>u.id===o.screenId),s=e.inputs.filter(u=>u.screenId===o.screenId),c={...r};for(let[u,l]of Object.entries(n)){let d=s.find(f=>f.key===u);if(!d||a?.type!=="owned")throw new Error("Unknown screen input");let p=Oc(a.document.pages[0].root,d.componentId);if(p?.type!=="stack"||!p.interaction)throw new Error("Input is unavailable");let g=p.interaction;switch(g.type){case"input":if(typeof l!="string"||l.length>g.maxLength)throw new Error("Invalid input text");if(l&&g.keyboard==="email"&&!F.email().safeParse(l).success)throw new Error("Invalid email");if(l&&g.keyboard==="url"&&!F.url().safeParse(l).success)throw new Error("Invalid URL");break;case"toggle":if(typeof l!="boolean")throw new Error("Invalid toggle value");break;case"select":case"tabs":if(typeof l!="string"||!p.children.some(f=>f.id===l&&!f.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(f=>!p.children.some(h=>h.id===f&&!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)&&E0(e,t,{[u.key]:l},{},!1);let d=a?.type==="owned"?Oc(a.document.pages[0].root,u.componentId):null;if(d?.type==="stack"&&d.interaction?.type==="multiselect"&&Array.isArray(l)&&l.length<d.interaction.min)throw new Error("Not enough selected options")}return c}import{z as xe}from"zod";import{z as T0}from"zod";var Cc=T0.enum(["local","remote"]);var R0=xe.strictObject({id:xe.uuid(),projectId:xe.uuid(),environmentId:xe.uuid(),name:xe.string().min(1).max(80),revision:xe.number().int().nonnegative(),evaluationMode:Cc,evaluationRevision:xe.number().int().nonnegative(),state:xe.enum(["active","paused","archived"]),publishedVersionId:xe.uuid().nullable(),updatedAt:xe.iso.datetime({offset:!0}),draft:qt}),qN=xe.strictObject({rows:xe.array(R0).max(200),nextCursor:xe.uuid().nullable()}),VN=xe.discriminatedUnion("action",[xe.strictObject({action:xe.literal("setEvaluationMode"),id:xe.uuid(),revision:xe.number().int().nonnegative(),evaluationMode:Cc}),xe.strictObject({action:xe.literal("create"),requestId:xe.uuid(),name:xe.string().trim().min(1).max(80),document:qt}),xe.strictObject({action:xe.literal("save"),id:xe.uuid(),revision:xe.number().int().nonnegative(),name:xe.string().trim().min(1).max(80),document:qt}),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 $N(e){let t=e==="en",n=jm("popup",e);return n.name=t?"Welcome":"\u6B22\u8FCE",n.pages[0].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"},Jm.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 $r=re.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ec=re.enum(["running","waiting","completed","closed","ineligible","failed"]),k0=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:$r.optional()}),re.strictObject({type:re.literal("open_url"),receiptId:re.uuid(),url:_c,openIn:yc}),re.strictObject({type:re.literal("event"),receiptId:re.uuid(),event:$r})]),j0=re.strictObject({type:re.literal("funnel"),id:re.uuid(),versionId:re.uuid()}),ef=re.strictObject({type:re.literal("render"),url:Tm}),tf={id:$r,presentation:On,outputs:re.array($r).max(250),inputs:dc,offeringKey:_n.optional(),capabilities:Lo,customerData:Cp,dataCursors:re.record($r,Jo.nullable())},N0=re.strictObject({...tf,content:re.discriminatedUnion("type",[ef,re.strictObject({type:re.literal("document"),document:Rt})])}),Tc=re.strictObject({id:re.uuid(),source:j0,revision:re.number().int().nonnegative(),visit:re.number().int().nonnegative(),nodeId:$r,nodeType:re.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","output"]),status:Ec,stopped:re.boolean(),canBack:re.boolean(),authenticated:re.boolean(),locale:re.string().min(1).max(35),answers:Gi,parameters:un,variables:re.record(re.string(),_e),output:_e.nullable(),screen:N0.nullable(),paywall:re.strictObject({receiptId:re.uuid(),resolution:Go,quote:Ci.nullable(),operation:Cr.nullable(),purchaseRequestId:re.uuid().nullable()}).nullable(),instruction:k0.nullable(),pendingRequest:re.strictObject({requestId:re.uuid(),authenticationRequired:re.boolean()}).nullable(),runExpiresAt:re.iso.datetime({offset:!0}),credentialExpiresAt:re.iso.datetime({offset:!0}).nullable()}),D0=Tc.extend({screen:re.strictObject({...tf,content:ef}).nullable()}),nf=re.strictObject({scope:Fe,run:D0,purchase:re.strictObject({receiptId:re.uuid(),quote:Ci.nullable(),operation:Cr.nullable()}).optional(),runToken:re.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:re.uuid().optional()});import{z as jt}from"zod";import{z as oa}from"zod";var sD=oa.strictObject({operation:oa.literal("renew_run"),runId:oa.uuid(),customerId:oa.uuid()}),rf=nf.refine(e=>!!e.runToken,"Renewal returns a credential");var gD=jt.discriminatedUnion("operation",[jt.strictObject({operation:jt.literal("campaign_decide"),...gc}).refine(fr,gr),jt.strictObject({operation:jt.literal("campaign_start"),funnelId:jt.uuid(),requestId:jt.uuid(),customer:Fr,customerData:Ur.optional(),locale:jt.string().min(1).max(35),parameters:un,cooldownSeconds:jt.number().int().min(1).max(2592e3)}).refine(fr,gr)]),hD=jt.union([jt.strictObject({scope:Fe,suppressed:jt.literal(!0),reason:jt.enum(["frequency","in_progress"]),retryAt:jt.iso.datetime({offset:!0})}),rf]);import{z as $e}from"zod";function of(e,t){let n=new Set,r=new Set,i=new Set,o=[];function a(d){for(let p of li(d))s(p)}function s(d){i.has(d)||!Object.hasOwn(t.savedGroups,d)||(i.add(d),o.push(()=>{let p=t.savedGroups[d];!Array.isArray(p)&&p.type==="condition"&&a(p.condition)}))}function c(d){a(d.condition);for(let p of d.parentConditions??[])u(p.id),a(p.condition)}function u(d,p=!1){if(!Object.hasOwn(t.features,d)){if(p)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.push(()=>{for(let g of t.features[d].rules??[]){c(g);for(let f of g.tracks??[])c(f.experiment)}}))}function l(d){if(!Object.hasOwn(t.experiments,d))throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),o.push(()=>c(t.experiments[d])))}for(let d of e.graph.nodes){d.type==="feature"&&u(d.featureKey,!0),d.type==="split"&&l(d.experimentId),d.type==="condition"&&d.cases.forEach(g=>a(g.condition)),d.type==="offering"&&d.configuration.source==="feature"&&u(d.configuration.featureKey,!0);let p=d.type==="output"?d.value:d.type==="end"?d.output:null;p?.type==="feature"&&u(p.featureKey,!0)}for(let d=0;d<o.length;d++)o[d]();return{...t,features:Object.fromEntries([...n].map(d=>[d,t.features[d]])),experiments:Object.fromEntries([...r].map(d=>[d,t.experiments[d]])),savedGroups:Object.fromEntries([...i].map(d=>[d,t.savedGroups[d]]))}}var zi=$e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),sf=$e.strictObject({entry:zi,nodes:$e.array($e.strictObject({id:zi,type:$e.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","output"]),outputs:$e.record($e.string(),zi),resources:$e.strictObject({screenId:zi.optional(),paywallVersionId:$e.uuid().optional(),couponId:$e.uuid().optional(),experimentId:$e.uuid().optional(),featureKey:$e.string().optional(),offeringVersionId:$e.uuid().optional()})})).min(1).max(500)}),af={scope:Fe,funnelId:$e.uuid(),versionId:$e.uuid(),evaluationRevision:$e.number().int().nonnegative(),expiresAt:$e.iso.datetime({offset:!0}).nullable(),topology:sf},F0=$e.discriminatedUnion("evaluationMode",[$e.strictObject({...af,evaluationMode:$e.literal("local"),growth:bn,conditions:$e.record(zi,$e.array($e.strictObject({condition:xt,port:$e.string()})))}),$e.strictObject({...af,evaluationMode:$e.literal("remote")})]);function U0(e){return sf.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(o=>o.id===t.screenId);i?.type==="paywall"&&(r.paywallVersionId=i.paywallVersionId)}break;case"condition":t.cases.forEach((i,o)=>{n[`case:${o}`]=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 OD(e){let t=Xm.parse(e.document),n=e.evaluationMode==="local"?bn.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:U0(t)};return F0.parse(e.evaluationMode==="remote"?r:{...r,growth:of(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((o,a)=>({condition:o.condition,port:`case:${a}`}))]))})}import{z as L}from"zod";var uf={commands:tt.flowNodes*4,receipts:tt.flowNodes*2,requestBytes:tt.documentBytes+2e6},Gr=L.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),cf={requestId:L.uuid(),nodeId:Gr,visit:L.number().int().nonnegative(),revision:L.number().int().nonnegative()},M0=L.union([Ki.options[3].omit({customerToken:!0}),Ki.options[4].omit({customerToken:!0}),Ki.options[5].omit({customerToken:!0}),Ki.options[6].omit({customerToken:!0}),L.strictObject({operation:L.literal("wait"),...cf,result:L.enum(["elapsed","received","timeout"])}),L.strictObject({operation:L.literal("simulate"),...cf,outcome:L.enum(["success","cancel","failure","unavailable"])})]),Rc=L.enum(["success","cancel","failure","unavailable","pending"]),kc=L.strictObject({seed:L.uuid(),now:L.iso.datetime({offset:!0}),locale:L.string().min(2).max(35),currency:W,parameters:un,attributes:L.record(L.string(),Vi).refine(e=>Object.keys(e).length<=100),authenticated:L.boolean(),holdings:L.enum(["sample","empty"]),results:L.record(L.string(),_e).optional(),outcomes:L.record(Gr,Rc),variants:L.record(Gr,L.string().min(1).max(128).nullable())}),jc=L.strictObject({schemaVersion:L.literal(1),growth:bn,paywalls:L.record(L.uuid(),$o),offerings:L.record(L.uuid(),Tr),surfaces:L.record(Gr,_e)}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=1e6,"Preview dependencies exceed their byte budget"),L0=L.array(L.strictObject({command:M0,authenticated:L.boolean(),outcome:Rc})).max(uf.commands),B0=L.discriminatedUnion("type",[L.strictObject({type:L.literal("draft"),document:qt}),L.strictObject({type:L.literal("snapshot"),id:L.uuid()})]),LD=L.strictObject({previewId:L.uuid(),source:B0,scenario:kc,journal:L0,dependencySnapshot:jc.optional()}),BD=L.strictObject({mode:L.literal("simulation"),run:Tc,dependencySnapshot:jc,traceTruncated:L.boolean(),trace:L.array(L.strictObject({nodeId:Gr,visit:L.number().int().nonnegative(),type:L.enum(["entered","shown","assigned","feature_evaluated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:L.record(L.string(),L.union([L.string(),L.number(),L.boolean(),L.null()]))})).max(2e3),receipts:L.array(L.strictObject({id:L.uuid(),nodeId:Gr,visit:L.number().int().nonnegative(),outcome:Rc})).max(uf.receipts)}),qD=L.strictObject({id:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),document:qt,scenario:kc,dependencySnapshot:jc,expiresAt:L.iso.datetime({offset:!0})}),VD=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),requestId:L.uuid(),document:qt,scenario:kc}),L.strictObject({action:L.literal("revoke"),id:L.uuid()})]);import{z as Ie}from"zod";var KD=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 Nc={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 WD(e,t,n=[]){let r=Xn(t)??"en",[i,...o]=r.split("-"),a=i==="zh"&&!o.includes("Hans")&&o.some(f=>["Hant","TW","HK","MO"].includes(f))?"zh-Hant":i,s=Nc[a]??Nc.en,c=Nc[a]?r:"en",u=f=>new Intl.NumberFormat(c).format(f),l=f=>new Intl.DateTimeFormat(c,{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(new Date(f))+" 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]}${lf(e.eligibility.condition)?`: ${lf(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),p=[e.startsAt?`${s[5]}: ${l(e.startsAt)}`:null,e.endsAt?`${s[6]}: ${l(e.endsAt)}`:s[7]].filter(Boolean).join(" \xB7 "),g=[d,p,`${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:p,terms:g}}function lf(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 Dc={"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 df(e){return e.actions.map(t=>t.properties.templateKey).find(t=>typeof t=="string"&&t.startsWith("popup-coupon-"))}function JD(e,t){let n=df(e);if(!n||!Object.hasOwn(Dc,n))return e;let r=i=>{let o={...i.root.bind,coupon:t};return i.root.bind?.coupon!==t&&delete o.promotionCode,{bind:o}};return{...e,pages:e.pages.map(i=>({...i,root:{...i.root,...r(i)}})),actions:e.actions.map(i=>i.properties.templateKey===n&&i.type!=="close"?{id:i.id,type:"claim_offer",couponId:t,event:"offer.claimed",properties:i.properties,close:i.close}:i)}}function XD(e){let t=df(e),n=t?Dc[t]:void 0;return!n||e.actions.some(r=>r.type==="claim_offer")?e:{...e,strings:{...e.strings,locales:Object.fromEntries(Object.entries(e.strings.locales).map(([r,i])=>[r,Object.fromEntries(Object.entries(i).map(([o,a])=>[o,a.replaceAll("{{offer.discount}}",n.discount).replaceAll("{{offer.headline}}",r.startsWith("zh")?n.zh:n.en).replaceAll("{{offer.terms}}",r.startsWith("zh")?"\u6F14\u793A\u91D1\u989D \xB7 \u7ED1\u5B9A\u4F18\u60E0\u5238\u540E\u81EA\u52A8\u663E\u793A\u771F\u5B9E\u6761\u6B3E":"Demo amount \xB7 Bind a coupon to show actual terms")]))]))}}}import{z as te}from"zod";var Yt=te.string().min(1).max(255),qn=te.number().finite().nonnegative(),pf=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)}),q0=te.strictObject({feature_id:Yt,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()}),V0=te.strictObject({feature_id:Yt.optional(),enabled:te.boolean().default(!1),limit_type:te.enum(["absolute","usage_percentage"]).optional(),overage_limit:qn.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"),$0=te.strictObject({feature_id:Yt,enabled:te.boolean().default(!0),limit:qn,interval:te.enum(["day","week","month","year"]),anchor:te.enum(["billing_cycle","utc"]).optional(),filter:pf.optional()}),G0=te.strictObject({feature_id:Yt.optional(),enabled:te.boolean().default(!0),threshold:qn,threshold_type:te.enum(["usage","usage_percentage","remaining","remaining_percentage"]),basis:te.enum(["balance","included","recurring","usage_limit"]).default("balance"),filter:pf.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"),K0=te.strictObject({feature_id:Yt,enabled:te.boolean().default(!1)}),z0=te.strictObject({auto_topups:te.array(q0).nullable(),spend_limits:te.array(V0).nullable(),usage_limits:te.array($0).nullable(),usage_alerts:te.array(G0).nullable(),overage_allowed:te.array(K0).nullable()}),rF=z0.omit({auto_topups:!0}),H0=Dr,iF=te.strictObject({internal_id:te.uuid(),id:Yt.nullable(),project_id:te.uuid(),environment_id:te.uuid(),name:te.string().max(80).nullable(),email:te.string().max(254).nullable(),metadata:H0.nullable(),created_at:te.number().finite().nonnegative().max(864e13)}),oF=te.strictObject({id:Yt,internal_product_id:Yt,product_id:Yt.nullable(),status:te.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:qn.nullable(),free_trial_id:Yt.nullable(),trial_ends_at:qn.nullable(),starts_at:qn.nullable(),access_starts_at:qn.nullable(),ended_at:qn.nullable(),product:te.strictObject({internal_id:Yt,id:Yt,name:te.string(),version:te.number().int().positive(),is_add_on:te.boolean()})});function uF(e,t,n=[]){let r={nodes:{}},i=t.startsWith("zh"),o=(s,c)=>i?s:c,a=(s,c,u,l,d=[])=>({id:s,label:c,value:u,status:l,detail:d,facts:[]});return Ct(e,s=>{if(s.type!=="customer_data")return;let c={...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??o("\u521B\u4F5C\u79EF\u5206","Creative credits"),spendable:"3,840",available:"4,040",reserved:"200",expiry:o("1,200 \xB7 2026\u5E7411\u67081\u65E5","1,200 \xB7 November 1, 2026"),sources:[a("sample-monthly",o("\u4F1A\u5458\u6708\u5EA6\u79EF\u5206","Monthly membership credits"),"2,640",o("\u53EF\u7528","Available")),a("sample-pack",o("\u8D2D\u4E70\u79EF\u5206\u5305","Purchased credit pack"),"1,200",o("\u53EF\u7528","Available"))],sourceCount:2,sourcePage:1,hasNextSources:!1,hasPreviousSources:!1}]}else s.data.source==="credit_transactions"?(c.rows=[a("sample-usage-1",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67083\u65E5 09:42","Oct 3, 09:42")]),a("sample-usage-2",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u9884\u6263","Reserved"),[o("10\u67083\u65E5 09:30","Oct 3, 09:30")]),a("sample-usage-3",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u9000\u56DE","Refund"),[o("10\u67082\u65E5 16:10","Oct 2, 16:10")]),a("sample-usage-4",o("\u89C6\u9891\u751F\u6210","Video generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 15:24","Oct 2, 15:24")]),a("sample-usage-5",o("\u56FE\u50CF\u751F\u6210","Image generation"),"",o("\u6D88\u8D39","Usage"),[o("10\u67082\u65E5 14:08","Oct 2, 14:08")])].slice(0,s.data.pageSize),c.rows.forEach((u,l)=>{u.facts=[{label:o("\u521B\u4F5C\u79EF\u5206","Creative credits"),value:["12","180","12","180","24"][l]}]})):s.data.source==="membership"?c.rows=[a("sample-plan",o("\u4E13\u4E1A\u7248 \xB7 \u6708\u4ED8","Pro \xB7 Monthly"),"",o("\u6709\u6548","Active"),[o("\u5F53\u524D\u5468\u671F\u7ED3\u675F \xB7 2026\u5E7411\u67081\u65E5","Current period ends \xB7 November 1, 2026")])]:s.data.source==="customer_plans"?c.rows=[a("sample-free",o("\u57FA\u7840\u7248","Starter"),o("\u514D\u8D39","Free"),o("\u53EF\u9009\u62E9","Available")),a("sample-pro",o("\u4E13\u4E1A\u7248","Pro"),o("$29 / \u6708","$29 / month"),o("\u5F53\u524D\u5957\u9910","Current plan")),a("sample-team",o("\u56E2\u961F\u7248","Team"),o("$79 / \u6708","$79 / month"),o("\u53EF\u9009\u62E9","Available"))].slice(0,s.data.pageSize):s.data.source==="billing_controls"?c.rows=[a("sample-control",o("\u6708\u5EA6\u7528\u91CF\u4E0A\u9650","Monthly usage limit"),"240 / 1,000",o("\u793A\u4F8B \xB7 \u672A\u6388\u6743\u4ED8\u6B3E","Sample \xB7 Payments not authorized"),[o("\u4EC5\u5C55\u793A\u793A\u4F8B\uFF0C\u9884\u89C8\u4E0D\u4F1A\u542F\u7528\u81EA\u52A8\u5145\u503C\u6216\u540E\u4ED8\u8D39\u3002","Preview does not authorize auto top-ups or postpaid billing.")])]:s.data.source==="billing"?c.rows=[{...a("sample-invoice","GROW-2026-001","$29.00",o("\u5DF2\u652F\u4ED8","Paid"),["October 1, 2026"]),billingActions:[{action:"invoice_open",label:o("\u67E5\u770B\u53D1\u7968","View invoice")}]}]:s.data.source==="credit_packs"?c.rows=[a("sample-pack-small",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12","",[o("1,200 \u79EF\u5206 \xB7 90 \u5929\u6709\u6548","1,200 credits \xB7 90 days validity")]),a("sample-pack-large",o("\u521B\u4F5C\u6269\u5C55\u5305","Creative expansion"),"$40","",[o("5,000 \u79EF\u5206 \xB7 180 \u5929\u6709\u6548","5,000 credits \xB7 180 days validity")])].slice(0,s.data.pageSize).map((u,l)=>({...u,...s.data.allowPurchase?{purchaseId:`10000000-0000-4000-8000-${String(l+1).padStart(12,"0")}`}:{}})):s.data.source==="credit_pack_orders"?c.rows=[a("sample-order",o("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12",o("\u5DF2\u4ED8\u6B3E","Paid"),["2026-10-01 12:30"])]:c.rows=[a("sample-offer",o("\u4F1A\u5458\u7EED\u8D39\u4F18\u60E0","Membership renewal offer"),"",o("\u53EF\u7528","Available"),[o("2026\u5E7411\u67081\u65E5\u5230\u671F","Expires November 1, 2026")])];r.nodes[s.id]=c}),r}import{z as Te}from"zod";import{z as pe}from"zod";var W0=pe.enum(["customer","coupon","audience"]),Q0=pe.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),aa=pe.object({baseRevision:pe.number().int().nonnegative(),latestRevision:pe.number().int().nonnegative(),mode:pe.enum(["merge","use_latest"]),decisions:pe.array(pe.object({field:Q0,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),mf=pe.number().int().nonnegative().nullable(),Z0=pe.object({resource:W0,id:pe.uuid(),projectId:pe.uuid(),environmentId:pe.uuid(),fromRevision:mf,toRevision:mf,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:aa.safeExtend({source:pe.literal("client")}).nullable()}),Y0=pe.object({createdAt:pe.iso.datetime({offset:!0}),id:pe.uuid()}).strict(),pF=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:Z0})),nextCursor:Y0.nullable()});var bF={type:"condition",condition:{}},_F=Te.strictObject({id:Te.uuid(),name:Te.string().min(1).max(80),description:Te.string().max(500),config:bo,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})}),yF=Te.discriminatedUnion("action",[Te.strictObject({action:Te.literal("save"),id:Te.uuid().nullable(),audit:aa.nullable().optional(),revision:Te.number().int().min(0),name:Te.string().trim().min(1).max(80),description:Te.string().max(500),config:bo}),Te.strictObject({action:Te.literal("archive"),id:Te.uuid(),audit:aa.nullable().optional(),revision:Te.number().int().min(1)})]),J0=Te.object({id:Te.uuid(),name:Te.string().nullable(),external_user_id:Te.string(),attributes:Ut,created_at:Te.iso.datetime({offset:!0})}),SF=Te.object({customers:J0.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 Hi}from"zod";var AF=Hi.object({defaultLocale:nn,locales:Hi.record(nn,Hi.object({name:Hi.string().max(80),description:Hi.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 wF(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=_o([t],r,n.defaultLocale),o=n.locales[i],a=n.locales[n.defaultLocale];return{name:o?.name.trim()?o.name:a?.name.trim()?a.name:e.name,description:o?.description.trim()?o.description:a?.description.trim()?a.description:""}}var ff="#172033",sa="#667085",X0="#E2E6EE",ex="#2C3C96",Et=e=>({top:e,right:e,bottom:e,left:e}),bt=e=>({type:"color",color:e}),Vt=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,o=sa,a={}){return this.zh[t]=n,this.en[t]=r,{id:t,type:"text",text:t,variant:i>=30?"title":"body",style:{text:{size:i,color:o,weight:i>=30?600:400,lineHeight:1.35,...i>=30?{letterSpacing:-1.2}:{}},...a}}}stack(t,n,r={},i=!1){return{id:t,type:"stack",direction:i?"horizontal":"vertical",align:"stretch",justify:"start",children:n,style:{gap:i?40:24,...r}}}widget(t,n,r,i,o=!1,a={}){let s=t+"_title";return this.zh[s]=r,this.en[s]=i,{id:t,type:"customer_data",title:s,data:{source:n,layout:o?"compact":"full",pageSize:n==="credit_transactions"?5:4,showSources:n==="credit_balance"&&!o,allowPurchase:n==="credit_packs"},style:a}}rule(t,n=X0){return{id:t,type:"divider",style:{background:bt(n),height:1}}}header(t,n,r,i,o,a=!1){return this.stack("account_header",[this.stack("intro",[this.text("eyebrow","\u5DE5\u4F5C\u7A7A\u95F4 / \u8D26\u6237","WORKSPACE / ACCOUNT",11,a?"#A9B4CB":sa,{text:{size:11,color:a?"#A9B4CB":sa,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,a?"#FFFFFF":ff),this.text("description",r,i,14,a?"#A9B4CB":sa)],{gap:12,width:660,grow:!0}),...o?[o]:[]],{gap:32},!0)}document(t,n=!1){return Rt.parse({kind:"screen",schemaVersion:4,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:ex,background:n?"#101A30":"#F5F6FA",text:ff,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 ua="#19202E",tx="#667080",Fc="#2C3C96",gf="#DDE2E9",hf="#F0F3FA",nx=(e=72,t=ua)=>({text:{size:e,color:t,weight:600,font:"system"}}),ca=(e,t=1)=>({width:e,grow:t}),rx={background:bt("#FFFFFF"),shape:{type:"rect",radius:10}};function ix(e){return new Vt(e,{theme:{background:"#FFFFFF",text:ua,primary:Fc},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function ox(e,t,n,r,i){let o=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,Fc,{text:{size:13,color:Fc,weight:700,letterSpacing:.8}});return e.stack("page_header",[o,e.text("heading",t,n,40,ua,{text:{size:40,color:ua,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,tx)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function bf(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new Vt("\u8D26\u6237\u4E00\u89C8",{theme:{background:e,text:t,primary:n,radius:"none"},width:1120,gap:36,padding:{top:32,right:24,bottom:48,left:24}}),o=(a,s,c)=>i.text(a,s,c,12,n,{text:{size:12,color:n,font:"mono",weight:500,letterSpacing:1.1}});return i.document([i.stack("journal_masthead",[i.stack("journal_identity",[i.text("wordmark","GROW","GROW",22,t,{text:{size:22,color:t,weight:700,letterSpacing:-1}}),o("edition","\u8D26\u6237 / ACCOUNT","ACCOUNT / JOURNAL")],{gap:16},!0),i.rule("masthead_rule",t),i.stack("journal_intro",[i.text("heading","\u8D26\u6237\u4E00\u89C8","Your account.",64,t,{width:720,grow:2,text:{size:64,color:t,font:"serif",weight:400,lineHeight:1.12,letterSpacing:-2}}),i.stack("intro_note",[o("intro_index","\u4E3A\u4F60\u7684\u4E0B\u4E00\u6B21\u521B\u4F5C","FOR YOUR NEXT CHAPTER"),i.text("description",`\u4F60\u7684\u4F1A\u5458\u3001\u79EF\u5206\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C
2
+ \u5728\u4E00\u5904\u4ECE\u5BB9\u638C\u63E1\u3002`,`Membership, credits and purchases.
3
+ A little clarity for what's next.`,14,r)],{width:300,grow:1,gap:12,padding:{top:8,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("account_summary",[i.stack("member_column",[o("member_index","01 / \u4F1A\u5458","01 / MEMBERSHIP"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:t,font:"serif",size:40,weight:400}})],{width:660,grow:2,gap:16}),i.stack("balance_column",[o("balance_index","02 / \u79EF\u5206","02 / CREDITS"),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:t,font:"serif",size:64,weight:400}})],{width:340,grow:1,gap:16})],{gap:48,padding:{top:12,right:0,bottom:12,left:0}},!0),i.rule("records_rule","#D9CFC1"),i.stack("account_records",[i.stack("purchase_column",[o("purchase_index","03 / \u8D2D\u4E70\u8BB0\u5F55","03 / PURCHASES"),i.widget("orders","credit_pack_orders","\u6BCF\u4E00\u7B14\u8D2D\u4E70","Your purchases",!1,{text:{color:t}})],{width:660,grow:2,gap:16}),i.stack("offer_column",[o("offer_index","04 / \u4E13\u5C5E\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u53EF\u7528\u4F18\u60E0","Available offers",!0,{text:{color:t}})],{width:340,grow:1,gap:16})],{gap:48},!0),i.rule("catalog_rule","#D9CFC1"),i.stack("account_catalog",[o("catalog_index","05 / \u65B9\u6848","05 / PLANS"),i.widget("plans","customer_plans","\u63A2\u7D22\u9002\u5408\u4F60\u7684\u65B9\u6848","Find your next plan",!0,{text:{color:t}})],{gap:16}),i.text("journal_footer","GROW / \u8BA9\u521B\u4F5C\u7EE7\u7EED","GROW / KEEP CREATING",11,r,{text:{size:11,color:r,font:"mono",letterSpacing:1}})])}function _f(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new Vt("\u79EF\u5206\u5DE5\u4F5C\u53F0",{theme:{background:"#EDF1F7",text:e,primary:"#244F9E",radius:"sm"},width:1200,gap:24,padding:{top:24,right:24,bottom:40,left:24}}),i=(o,a,s)=>r.text(o,a,s,11,t,{text:{size:11,color:t,font:"mono",weight:500,letterSpacing:1}});return r.document([r.stack("terminal_header",[i("wordmark","GROW / \u79EF\u5206\u5DE5\u4F5C\u53F0","GROW / CREDIT WORKSPACE"),r.stack("terminal_intro",[r.text("heading","\u79EF\u5206\u4E0E\u7528\u91CF","Credits & usage",36,e,{width:780,grow:2,text:{size:36,color:e,weight:600,letterSpacing:-1.2,lineHeight:1.15}}),r.text("description","\u4F59\u989D\u3001\u5230\u671F\u6765\u6E90\u4E0E\u6BCF\u4E00\u7B14\u4F7F\u7528\u3002","Balance, expiry and every transaction.",13,t,{width:340,grow:1})],{gap:32},!0)],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),r.stack("terminal_workspace",[r.stack("ledger_workspace",[r.stack("credit_summary",[i("balance_index","01 / \u8D26\u6237\u4F59\u989D","01 / BALANCE"),r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{text:{size:80,color:e,font:"mono",weight:500}})],{gap:16,padding:Et(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:Et(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:Et(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:Et(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:Et(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 yf(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new Vt("\u4F1A\u5458\u4FF1\u4E50\u90E8",{theme:{background:t,text:e,primary:e,radius:"none"},width:1160,gap:32,padding:{top:28,right:24,bottom:48,left:24}}),o=(a,s,c,u=n)=>i.text(a,s,c,12,u,{text:{size:12,color:u,font:"mono",letterSpacing:1,weight:500}});return i.document([i.stack("club_masthead",[i.stack("club_identity",[i.text("wordmark","GROW CLUB","GROW CLUB",22,e,{text:{size:22,color:e,weight:700,letterSpacing:-.6}}),o("club_edition","\u4F1A\u5458 / MEMBERSHIP","MEMBERSHIP / YOUR SPACE")],{gap:20},!0),i.rule("club_rule",e),i.stack("club_intro",[i.text("heading","\u4F1A\u5458\u4E0E\u65B9\u6848","Room to grow.",64,e,{width:752,grow:2,text:{size:64,color:e,font:"serif",weight:400,lineHeight:1.1,letterSpacing:-2}}),i.stack("club_description",[o("club_intro_label","\u4E3A\u6301\u7EED\u7684\u521B\u9020\u529B","FOR WHAT COMES NEXT"),i.text("description",`\u67E5\u770B\u4F60\u7684\u4F1A\u5458\u72B6\u6001\uFF0C
4
+ \u627E\u5230\u9002\u5408\u4E0B\u4E00\u6B65\u7684\u65B9\u6848\u3002`,`Your membership, at a glance.
5
+ A plan for what comes next.`,14,n)],{width:320,grow:1,gap:12,padding:{top:10,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("membership_summary",[i.stack("member_spread",[o("member_index","01 / \u4F60\u7684\u4F1A\u5458","01 / YOUR MEMBERSHIP","#CCD9CA"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:"#FFFFFF",font:"serif",size:52,weight:400}})],{width:744,grow:2,gap:20,padding:Et(32),background:bt(e)}),i.stack("balance_inset",[o("balance_index","02 / \u521B\u4F5C\u4F59\u989D","02 / CREDIT BALANCE",e),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:e,size:60,weight:500}})],{width:376,grow:1,gap:20,padding:Et(28),background:bt(r)})],{gap:0},!0),i.stack("plan_comparison",[o("plans_index","03 / \u9009\u62E9\u4F60\u7684\u4E0B\u4E00\u6B65","03 / YOUR NEXT STEP"),i.widget("plans","customer_plans","\u627E\u5230\u9002\u5408\u4F60\u7684\u65B9\u6848","A plan to make it yours",!1,{text:{color:e,font:"serif"}})],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),i.rule("benefits_rule","#C8CEC2"),i.stack("benefit_records",[i.stack("member_offers",[o("offers_index","04 / \u4F60\u7684\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u4F1A\u5458\u4F18\u60E0","Member offers",!1,{text:{color:e}})],{width:556,grow:1,gap:16}),i.stack("member_purchases",[o("orders_index","05 / \u8D2D\u4E70\u8BB0\u5F55","05 / PURCHASES"),i.widget("orders","credit_pack_orders","\u8D2D\u4E70\u4E0E\u8BB0\u5F55","Purchases & records",!1,{text:{color:e}})],{width:556,grow:1,gap:16})],{gap:48},!0),i.rule("footer_rule","#C8CEC2"),o("club_footer","GROW CLUB / \u7559\u51FA\u521B\u9020\u7684\u7A7A\u95F4","GROW CLUB / ROOM FOR WHAT'S NEXT")])}function Sf(){let e=ix("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([ox(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,{...ca(784,2),...nx(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{...ca(328),background:bt(hf),padding:Et(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",gf),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,ca(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",gf),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{...ca(328),...rx,padding:Et(24),gap:24,background:bt(hf)})],{gap:48},!0)])}function xf(){return Sf()}var yn=(e,t=1)=>({width:e,grow:t}),la=(e=16)=>({shape:{type:"rect",radius:e}}),st=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),Pn=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function ax(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 sx(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 Wi(e,t,n,r,i,o="system"){let a=e.stack("masthead",[ax(e,t,n,r,o),sx(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return a.justify="between",a.align="center",a}function vf(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 cx(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new Vt("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:Pn(32,24,48)});return i.document([Wi(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))],{...yn(680,2),gap:32,padding:Pn(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,st(e))],{...yn(328),background:bt(r),padding:Et(24),...la(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),vf(i,t,!1,4)])}function ux(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new Vt("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:Pn(40,24,48)});return r.document([Wi(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"))],{...yn(628,2),padding:Pn(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))],{...yn(356),gap:20,padding:Pn(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 lx(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new Vt("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:Pn(32,24,48)});return i.document([Wi(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"))],{...yn(640,2),gap:24,background:bt(n),padding:Et(32),...la(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,st(e,64))],{...yn(400),background:bt("#E9EFE5"),padding:Et(28),...la(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 dx(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new Vt("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:Pn(32,24,48)});return r.document([Wi(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,{...yn(688,2),...st(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...yn(372),...st(e)})],{gap:72,padding:Pn(4,0,8)},!0),r.rule("activity_rule",n),vf(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,st(e))])}function px(){let e="#3F3029",t="#8B766A",n="#A34525",r=new Vt("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:Pn(32,24,48)});return r.document([Wi(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))],{...yn(304),gap:28,padding:Et(24),background:bt("#F1E5D9"),...la(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,st(e))],{...yn(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 If(){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:cx},{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:ux},{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:lx},{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:xf},{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:dx},{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:px}].map(({create:e,...t})=>({...t,document:e()}))}function mx(){return _f()}function fx(){return bf()}function gx(){return yf()}function MF(){return[...If(),{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:mx()},{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:fx()},{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:gx()}]}import{z as Nt}from"zod";var Af=Nt.object({id:Nt.string().min(1).max(136),name:Nt.string().min(1).max(128),type:Nt.enum(["entry","condition","feature"])}).strict(),hx=Nt.object({id:Nt.uuid(),name:Nt.string().min(1).max(80),status:Nt.enum(["draft","published","archived"]),draftNodes:Nt.array(Af).max(600),publishedNodes:Nt.array(Af).max(600),runningVersions:Nt.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"),qF=Nt.object({rows:Nt.array(hx).max(50),nextCursor:Nt.uuid().nullable()}).strict();import{z as ve}from"zod";var wt=ve.number().int().nonnegative(),wf=ve.strictObject({at:ve.iso.datetime({offset:!0}),id:ve.uuid()}),zF=ve.strictObject({versionId:ve.uuid().nullable(),from:ve.iso.datetime({offset:!0}).nullable(),to:ve.iso.datetime({offset:!0}).nullable(),after:wf.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),HF=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:wt,completed:wt,closed:wt,failed:wt,waiting:wt,paid:wt}),decisions:ve.strictObject({queries:wt,completed:wt,reportedUsed:wt,pending:wt,failed:wt}),revenue:ve.array(ve.strictObject({currency:W,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:wt,completed:wt,shown:wt,waiting:wt})).max(1e4),recentRuns:ve.array(ve.strictObject({id:ve.uuid(),versionId:ve.uuid(),customerId:ve.uuid(),status:Ec,nodeId:ve.string(),visit:wt,createdAt:ve.iso.datetime({offset:!0}),updatedAt:ve.iso.datetime({offset:!0})})).max(100),nextCursor:wf.nullable()});import{z as Vn}from"zod";var JF=Vn.object({requestId:Vn.uuid(),coupon:Ml,audienceId:Vn.uuid().nullable(),productVersionId:Vn.uuid().optional(),presentation:On,locale:Vn.enum(["en","zh-CN"])}).strict(),XF=Vn.object({couponId:Vn.uuid(),funnelId:Vn.uuid()}).strict();import{z as we}from"zod";var _t=we.number().int().nonnegative(),da=we.string().regex(/^-?\d+$/),bx=we.object({currency:W,grossMinor:da,refundMinor:da,netMinor:da,purchases:_t,refunds:_t}).strict(),rU=we.object({snapshotAt:we.iso.datetime({offset:!0}),customers:we.object({total:_t,created:_t,paid:_t}).strict(),memberships:we.object({active:_t,trial:_t,pastDue:_t,ended:_t}).strict(),runs:we.object({started:_t,completed:_t,closed:_t,paid:_t}).strict(),revenue:we.array(bx).max(100),unknownMoney:_t,funnels:we.array(we.object({id:we.uuid(),name:we.string(),started:_t,completed:_t,paid:_t}).strict()).max(50),daily:we.array(we.object({date:we.iso.date(),currency:W,netMinor:da}).strict()).max(9e3)}).strict(),iU=we.object({customerId:we.uuid(),rows:we.array(we.object({id:we.string().regex(/^\d+$/),funnelId:we.uuid(),funnelName:we.string(),versionId:we.uuid(),runId:we.uuid(),nodeId:we.string(),experimentId:we.uuid(),visit:we.number().int().nonnegative(),variationKey:we.string(),inExperiment:we.boolean(),hashUsed:we.boolean(),acceptedAt:we.iso.datetime({offset:!0}),runStatus:we.string()}).strict()).max(50),nextCursor:we.string().regex(/^\d+$/).nullable()}).strict();import{z as Jt}from"zod";import{z as yt}from"zod";var Of=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)})]),Pf=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 dU=Jt.strictObject({operation:Jt.literal("native_receipt"),requestId:Jt.uuid(),customerToken:Jt.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:Jt.uuid(),receiptId:Jt.uuid(),nativeEvidence:Of.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),pU=Jt.strictObject({scope:Fe,requestId:Jt.uuid(),orderId:Jt.uuid(),receiptId:Jt.uuid(),orderStatus:Jt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:Jt.boolean(),nativeCompletion:Pf.optional()});import{z as _x}from"zod";var yx=Mm.extend({document:_x.union([Rt.refine(e=>e.pages.length===1,"Use a single owned screen template"),qt.refine(e=>e.screens.every(t=>t.type==="owned"),"Flow templates own their screens")])}).superRefine((e,t)=>{if((e.document.kind==="funnel"?e.surface!=="onboarding":e.surface!==e.document.surface)&&t.addIssue({code:"custom",message:"Template category does not match its document"}),e.document.kind==="funnel"){let n=e.document,r=n.graph.nodes.filter(i=>i.type==="screen");(new Set(n.screens.map(i=>i.id)).size!==n.screens.length||new Set(n.graph.nodes.map(i=>i.id)).size!==n.graph.nodes.length||r.length!==n.screens.length||n.screens.some(i=>r.filter(o=>o.screenId===i.id).length!==1))&&t.addIssue({code:"custom",message:"Every template screen requires one unique flow node"})}});function xU(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 Sx(e,t){let n=structuredClone(yx.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"&&Cf(l.document);return qt.parse({...n,screens:n.screens.map(l=>l.type==="owned"?{...l,document:{...l.document,strings:{...l.document.strings,defaultLocale:Qs(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:Qs(n,[t])}},i=[{id:"entry",type:"entry",name:t==="en"?"Entry":"\u5165\u53E3",next:"screen"},{id:"done",name:t==="en"?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed",output:{type:"literal",value:null}},{id:"closed",name:t==="en"?"Closed":"\u5173\u95ED",type:"end",outcome:"closed"}],o={};r.actions=r.actions.map((c,u)=>{let l=`action_${u}`;return o[c.id]=c.close?"closed":"done",c.type==="open_url"?(o[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"&&(o[c.id]="unconnected"),{id:c.id,type:"event",event:c.id,properties:{},close:!1}}),Cf(r),i.push({id:"screen",name:e.label,type:"screen",screenId:"screen",presentation:e.surface==="page"?{type:"inline"}:n.presentation,outputs:o});let a=new Set(i.flatMap(qr));return qt.parse({references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",schemaVersion:3,inputs:(()=>{let c=[];return Ct(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"||a.has(c.id))}})}function vU(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=Sx(t,n),i=`tpl_${crypto.randomUUID().replaceAll("-","").slice(0,16)}_`,o=new Map,a=d=>d==="unconnected"?d:(o.has(d)||o.set(d,`${i}${crypto.randomUUID().replaceAll("-","").slice(0,24)}`),o.get(d)),s=r.graph.nodes.slice().sort((d,p)=>+(p.type==="screen")-+(d.type==="screen")).filter(d=>d.type!=="entry").map(d=>d.type==="screen"?{...d,id:a(d.id),screenId:a(d.screenId),outputs:Object.fromEntries(Object.entries(d.outputs).map(([p,g])=>[p,a(g)]))}:d.type==="action"?{...d,id:a(d.id),success:a(d.success),cancel:a(d.cancel),unavailable:a(d.unavailable),failure:a(d.failure)}:d.type==="external_page"?{...d,id:a(d.id),opened:a(d.opened),failed:a(d.failed)}:{...d,id:a(d.id)}),c=qt.parse({...e,screens:[...e.screens,...r.screens.map(d=>({...d,id:a(d.id)}))],inputs:[...e.inputs,...r.inputs.map(d=>({...d,screenId:a(d.screenId)}))],graph:{...e.graph,nodes:[...e.graph.nodes,...s]}}),u=0,l=0;for(let d of c.screens)d.type==="owned"&&(Ct(d.document,()=>{u++}),l+=d.document.actions.length);if(u>tt.components||l>tt.actions||ln(c)>tt.documentBytes)throw new Error("Template exceeds the flow capacity");return c}function Cf(e){Ct(e,t=>{t.type==="stack"&&t.bind?(delete t.bind.plan,delete t.bind.coupon,delete t.bind.promotionCode,Object.keys(t.bind).length||delete t.bind):t.type==="plan_picker"&&(delete t.planIds,delete t.defaultPlan)})}function xx(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function AU(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function Ef(e){return xx(e)?e.intervalCount??1:1}function wU(e,t){return e.interval===t.interval&&Ef(e)===Ef(t)}function OU(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],i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},o={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},a=e==="week"?`/${o[r]??o.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?a:`/${n} ${a.slice(1)}${r==="en"?"s":""}`}import{z as Ge}from"zod";var Tf=Ge.enum(["membership","trial","topup","manual","rollover","seat"]),Rf=Ge.enum(["scheduled","active","expired","revoked","unavailable"]),RU=Ge.strictObject({customerId:Ge.uuid().nullable(),entityId:Ge.uuid().nullable(),internal_feature_id:Ge.uuid().nullable(),reason:Tf.nullable(),status:Rf.nullable(),after:Ge.uuid().nullable(),limit:Ge.number().int().min(1).max(50)}),kU=Ge.strictObject({snapshotAt:Ge.iso.datetime({offset:!0}),rows:Ge.array(Ge.strictObject({id:Ge.uuid(),customerId:Ge.uuid(),fundingCustomerId:Ge.uuid(),entityId:Ge.uuid().nullable(),internal_feature_id:Ge.uuid(),key:tn,name:Ge.string().min(1).max(120),kind:Ge.enum(["access","metered","credit"]),reason:Tf,status:Rf,unlimited:Ge.boolean(),granted:Ye,available:Ye,held:Ye,spent:Ye,revoked:Ye,transferred:Ye,startsAt:Ge.iso.datetime({offset:!0}).nullable(),expiresAt:Ge.iso.datetime({offset:!0}).nullable(),grantId:Ge.uuid().nullable(),membershipId:Ge.uuid().nullable(),seatPoolId:Ge.uuid().nullable()})).max(50),nextCursor:Ge.uuid().nullable()});import{z as Le}from"zod";var kf=Le.string().regex(/^[a-f0-9]{64}$/),vx=Lr.omit({variations:!0,active:!0}).extend({changeId:kf,variations:Le.array(Le.strictObject({urlRedirect:Le.string().max(2048)})).min(2).max(20)}),MU=Le.strictObject({environmentId:Le.uuid(),trackExposures:Le.boolean(),generation:kf,experiments:Le.array(vx).max(100),savedGroups:Ui}),Ix=Le.strictObject({eventUuid:Le.uuid(),timestamp:Le.iso.datetime({offset:!0}).optional(),deviceId:Le.string().min(1).max(128),sessionId:Le.string().min(1).max(128).optional(),url:Le.url().max(2048),pageTitle:Le.string().max(512).optional(),experimentKey:Le.string().min(1).max(255),variationKey:Le.string().min(1).max(64)}),LU=Le.strictObject({events:Le.array(Ix).min(1).max(20)}),BU=Le.strictObject({inserted:Le.number().int().nonnegative(),duplicates:Le.number().int().nonnegative(),skipped:Le.number().int().nonnegative(),rejected:Le.array(Le.strictObject({index:Le.number().int().nonnegative(),reason:Le.string()}))});import{z as V}from"zod";var Nf=V.strictObject({property:V.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/),datatype:V.enum(["boolean","string","number","enum","string[]","number[]","object","array","json"]),enumValues:V.array(V.string()).min(1).nullable(),format:V.enum(["","version","date","isoCountryCode"]),hashAttribute:V.boolean(),stored:V.boolean(),description:V.string().max(2e3),status:V.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"})}),Df=V.strictObject({name:V.string().min(1).max(128),label:V.string().min(1).max(80),description:V.string().max(2e3),status:V.enum(["active","inactive"]),hashAttribute:V.string().min(1).max(128),seed:V.string().min(1).max(128)}),Uc={id:V.uuid(),revision:V.number().int().positive()},zU=V.strictObject({groups:V.array(V.strictObject({id:V.uuid(),name:V.string(),type:V.enum(["condition","list"])})),experiments:V.array(V.strictObject({...Uc,configuration:Ir,archivedAt:V.iso.datetime({offset:!0}).nullable()})),namespaces:V.array(V.strictObject({...Uc,configuration:Df})),attributes:V.array(V.strictObject({...Uc,configuration:Nf})),truncated:V.boolean()}),Mc={id:V.uuid().nullable(),revision:V.number().int().min(0)},HU=V.discriminatedUnion("resource",[V.strictObject({...Mc,resource:V.literal("experiment"),configuration:Ir.safeExtend({archivedAt:V.iso.datetime({offset:!0}).nullable()})}),V.strictObject({...Mc,resource:V.literal("namespace"),configuration:Df}),V.strictObject({...Mc,resource:V.literal("attribute"),configuration:Nf})]),WU=V.strictObject({operation:V.literal("evaluate"),attributes:Ut,condition:xt.optional(),features:Rl,featureKey:V.string().min(1).max(128),customerId:V.uuid().nullable()}),QU=V.strictObject({experimentId:V.uuid(),participants:V.number().int().nonnegative(),cohorts:V.array(V.strictObject({variationKey:V.string().nullable(),participants:V.number().int().nonnegative()})),phases:V.array(V.strictObject({phaseIndex:V.number().int().nonnegative(),participants:V.number().int().nonnegative()})),stickyIdentities:V.number().int().nonnegative(),snapshotAt:V.iso.datetime()}),jf=V.strictObject({resource:V.enum(["group","experiment","coupon"]),id:V.uuid()}),ZU=V.strictObject({rows:V.array(jf.extend({name:V.string(),status:V.string()})).max(50),total:V.number().int().nonnegative(),nextCursor:jf.nullable()});var pa=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Ax(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!pa(n.condition,r.condition)||!pa(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,p]of[...r.namespace.ranges].sort((g,f)=>g[0]-f[0]))d<=l&&p>l&&(l=p);return l<u})&&i.push("namespaceRange"),(!pa(n.variationWeights,r.variationWeights)||!pa(e.variations.map(c=>c.key),t.variations.map(c=>c.key)))&&i.push("weights"),(e.disableStickyBucketing!==t.disableStickyBucketing||n.seed!==r.seed)&&i.push("identity");let o=i.some(c=>["namespace","namespaceRange","weights","identity"].includes(c)),a=!t.disableStickyBucketing,s=o||i.length>0&&!a?"new-phase":a?"same-phase-sticky":"same-phase-everyone";return{reasons:i,disableSamePhase:o,recommended:s,risk:i.length?o?"danger":"warning":"safe"}}function XU(e,t,n,r,i){let o=structuredClone(t),a=o.phases.at(-1),s=!o.disableStickyBucketing;if(n==="same-phase-sticky"&&!s||n==="new-phase-block-sticky"&&!s)throw Error("Sticky bucketing is required");if(Ax(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");return o.bucketVersion=e.bucketVersion+(s&&n!=="same-phase-sticky"?1:0),o.minBucketVersion=n==="new-phase-block-sticky"?o.bucketVersion:e.minBucketVersion,n.startsWith("new-phase")&&(o.phases=structuredClone(e.phases),o.phases[o.phases.length-1].dateEnded=r,o.phases.push({...a,name:a.name,reason:a.reason,dateStarted:r,dateEnded:null,seed:i})),Ir.parse(o)}import{z as wx}from"zod";var nM=wx.enum(["owner","admin","developer","sales","member"]),Ox=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],Ff=Ox.flatMap(e=>e==="analytics"?["analytics:read"]:[`${e}:read`,`${e}:write`]),Uf={owner:Ff,admin:Ff,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 rM(e,t){if(!e||!Object.hasOwn(Uf,e))return!1;let n=Uf[e];return n.includes(t)||t.endsWith(":read")&&n.includes(t.replace(/:read$/,":write"))}var oM=["boolean","metered","credit_system","ai_credit_system"];function aM(e,t,n,r=!1){let i=[],o=(a,s)=>i.push({field:a,code:s});return e.type!==t.type&&(e.type==="credit_system"!=(t.type==="credit_system")&&o("type","type_switch_credit_system"),n.customerHistory&&o("type","attached_to_customer"),n.entityFeature&&o("type","used_as_entity_feature"),n.usagePrice&&o("type","has_usage_price"),n.creditSystems&&o("type","used_in_credit_system"),n.productEntitlements&&(e.type==="credit_system"||t.type==="credit_system")&&o("type","used_in_product_credit_system")),e.id!==t.id&&(r&&o("id","id_already_exists"),n.customerHistory&&o("id","attached_to_customer")),e.type!=="boolean"&&t.type!=="boolean"&&e.config?.usage_type!==t.config?.usage_type&&t.config?.usage_type&&(n.creditSystems&&o("usage_type","used_in_credit_system"),n.entityFeature&&o("usage_type","used_as_entity_feature"),n.customerHistory&&o("usage_type","attached_to_customer")),i}/*!
6
+ * decimal.js v10.6.0
7
+ * An arbitrary-precision Decimal type for JavaScript.
8
+ * https://github.com/MikeMcl/decimal.js
9
+ * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
10
+ * MIT Licence
11
+ */var Kr=9e15,zn=1e9,Lc="0123456789abcdef",ga="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",ha="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Bc={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Kr,maxE:Kr,crypto:!1},qf,Cn,le=!0,_a="[DecimalError] ",Kn=_a+"Invalid argument: ",Vf=_a+"Precision limit exceeded",$f=_a+"crypto unavailable",Gf="[object Decimal]",Ot=Math.floor,ct=Math.pow,Px=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Cx=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Ex=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Kf=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,dn=1e7,ie=7,Tx=9007199254740991,Rx=ga.length-1,qc=ha.length-1,T={toStringTag:Gf};T.absoluteValue=T.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),X(e)};T.ceil=function(){return X(new this.constructor(this),this.e+1,2)};T.clampedTo=T.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(Kn+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};T.comparedTo=T.cmp=function(e){var t,n,r,i,o=this,a=o.d,s=(e=new o.constructor(e)).d,c=o.s,u=e.s;if(!a||!s)return!c||!u?NaN:c!==u?c:a===s?0:!a^c<0?1:-1;if(!a[0]||!s[0])return a[0]?c:s[0]?-u:0;if(c!==u)return c;if(o.e!==e.e)return o.e>e.e^c<0?1:-1;for(r=a.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(a[t]!==s[t])return a[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1};T.cosine=T.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=kx(r,Zf(r,n)),r.precision=e,r.rounding=t,X(Cn==2||Cn==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};T.cubeRoot=T.cbrt=function(){var e,t,n,r,i,o,a,s,c,u,l=this,d=l.constructor;if(!l.isFinite()||l.isZero())return new d(l);for(le=!1,o=l.s*ct(l.s*l,1/3),!o||Math.abs(o)==1/0?(n=St(l.d),e=l.e,(o=(e-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=ct(n,1/3),e=Ot((e+1)/3)-(e%3==(e<0?-1:2)),o==1/0?n="5e"+e:(n=o.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new d(n),r.s=l.s):r=new d(o.toString()),a=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),u=c.plus(l),r=Be(u.plus(l).times(s),u.plus(c),a+2,1),St(s.d).slice(0,a)===(n=St(r.d)).slice(0,a))if(n=n.slice(a-3,a+1),n=="9999"||!i&&n=="4999"){if(!i&&(X(s,e+1,0),s.times(s).times(s).eq(l))){r=s;break}a+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(X(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return le=!0,X(r,e,d.rounding,t)};T.decimalPlaces=T.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-Ot(this.e/ie))*ie,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};T.dividedBy=T.div=function(e){return Be(this,new this.constructor(e))};T.dividedToIntegerBy=T.divToInt=function(e){var t=this,n=t.constructor;return X(Be(t,new n(e),0,1,1),n.precision,n.rounding)};T.equals=T.eq=function(e){return this.cmp(e)===0};T.floor=function(){return X(new this.constructor(this),this.e+1,3)};T.greaterThan=T.gt=function(e){return this.cmp(e)>0};T.greaterThanOrEqualTo=T.gte=function(e){var t=this.cmp(e);return t==1||t===0};T.hyperbolicCosine=T.cosh=function(){var e,t,n,r,i,o=this,a=o.constructor,s=new a(1);if(!o.isFinite())return new a(o.s?1/0:NaN);if(o.isZero())return s;n=a.precision,r=a.rounding,a.precision=n+Math.max(o.e,o.sd())+4,a.rounding=1,i=o.d.length,i<32?(e=Math.ceil(i/3),t=(1/Sa(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),o=zr(a,1,o.times(t),new a(1),!0);for(var c,u=e,l=new a(8);u--;)c=o.times(o),o=s.minus(c.times(l.minus(c.times(l))));return X(o,a.precision=n,a.rounding=r,!0)};T.hyperbolicSine=T.sinh=function(){var e,t,n,r,i=this,o=i.constructor;if(!i.isFinite()||i.isZero())return new o(i);if(t=o.precision,n=o.rounding,o.precision=t+Math.max(i.e,i.sd())+4,o.rounding=1,r=i.d.length,r<3)i=zr(o,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/Sa(5,e)),i=zr(o,2,i,i,!0);for(var a,s=new o(5),c=new o(16),u=new o(20);e--;)a=i.times(i),i=i.times(s.plus(a.times(c.times(a).plus(u))))}return o.precision=t,o.rounding=n,X(i,t,n,!0)};T.hyperbolicTangent=T.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Be(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};T.inverseCosine=T.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()?Sn(t,r,i):new t(0):new t(NaN):e.isZero()?Sn(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))};T.inverseHyperbolicCosine=T.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)};T.inverseHyperbolicSine=T.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())};T.inverseHyperbolicTangent=T.atanh=function(){var e,t,n,r,i=this,o=i.constructor;return i.isFinite()?i.e>=0?new o(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=o.precision,t=o.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?X(new o(i),e,t,!0):(o.precision=n=r-i.e,i=Be(i.plus(1),new o(1).minus(i),n+e,1),o.precision=e+4,o.rounding=1,i=i.ln(),o.precision=e,o.rounding=t,i.times(.5))):new o(NaN)};T.inverseSine=T.asin=function(){var e,t,n,r,i=this,o=i.constructor;return i.isZero()?new o(i):(t=i.abs().cmp(1),n=o.precision,r=o.rounding,t!==-1?t===0?(e=Sn(o,n+4,r).times(.5),e.s=i.s,e):new o(NaN):(o.precision=n+6,o.rounding=1,i=i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(),o.precision=n,o.rounding=r,i.times(2)))};T.inverseTangent=T.atan=function(){var e,t,n,r,i,o,a,s,c,u=this,l=u.constructor,d=l.precision,p=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&d+4<=qc)return a=Sn(l,d+4,p).times(.25),a.s=u.s,a}else{if(!u.s)return new l(NaN);if(d+4<=qc)return a=Sn(l,d+4,p).times(.5),a.s=u.s,a}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),a=new l(u),i=u;e!==-1;)if(i=i.times(c),o=a.minus(i.div(r+=2)),i=i.times(c),a=o.plus(i.div(r+=2)),a.d[t]!==void 0)for(e=t;a.d[e]===o.d[e]&&e--;);return n&&(a=a.times(2<<n-1)),le=!0,X(a,l.precision=d,l.rounding=p,!0)};T.isFinite=function(){return!!this.d};T.isInteger=T.isInt=function(){return!!this.d&&Ot(this.e/ie)>this.d.length-2};T.isNaN=function(){return!this.s};T.isNegative=T.isNeg=function(){return this.s<0};T.isPositive=T.isPos=function(){return this.s>0};T.isZero=function(){return!!this.d&&this.d[0]===0};T.lessThan=T.lt=function(e){return this.cmp(e)<0};T.lessThanOrEqualTo=T.lte=function(e){return this.cmp(e)<1};T.logarithm=T.log=function(e){var t,n,r,i,o,a,s,c,u=this,l=u.constructor,d=l.precision,p=l.rounding,g=5;if(e==null)e=new l(10),t=!0;else{if(e=new l(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new l(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new l(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)o=!0;else{for(i=n[0];i%10===0;)i/=10;o=i!==1}if(le=!1,s=d+g,a=Gn(u,s),r=t?ba(l,s+10):Gn(e,s),c=Be(a,r,s,1),Qi(c.d,i=d,p))do if(s+=10,a=Gn(u,s),r=t?ba(l,s+10):Gn(e,s),c=Be(a,r,s,1),!o){+St(c.d).slice(i+1,i+15)+1==1e14&&(c=X(c,d+1,0));break}while(Qi(c.d,i+=10,p));return le=!0,X(c,d,p)};T.minus=T.sub=function(e){var t,n,r,i,o,a,s,c,u,l,d,p,g=this,f=g.constructor;if(e=new f(e),!g.d||!e.d)return!g.s||!e.s?e=new f(NaN):g.d?e.s=-e.s:e=new f(e.d||g.s!==e.s?g:NaN),e;if(g.s!=e.s)return e.s=-e.s,g.plus(e);if(u=g.d,p=e.d,s=f.precision,c=f.rounding,!u[0]||!p[0]){if(p[0])e.s=-e.s;else if(u[0])e=new f(g);else return new f(c===3?-0:0);return le?X(e,s,c):e}if(n=Ot(e.e/ie),l=Ot(g.e/ie),u=u.slice(),o=l-n,o){for(d=o<0,d?(t=u,o=-o,a=p.length):(t=p,n=l,a=u.length),r=Math.max(Math.ceil(s/ie),a)+2,o>r&&(o=r,t.length=1),t.reverse(),r=o;r--;)t.push(0);t.reverse()}else{for(r=u.length,a=p.length,d=r<a,d&&(a=r),r=0;r<a;r++)if(u[r]!=p[r]){d=u[r]<p[r];break}o=0}for(d&&(t=u,u=p,p=t,e.s=-e.s),a=u.length,r=p.length-a;r>0;--r)u[a++]=0;for(r=p.length;r>o;){if(u[--r]<p[r]){for(i=r;i&&u[--i]===0;)u[i]=dn-1;--u[i],u[r]+=dn}u[r]-=p[r]}for(;u[--a]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=ya(u,n),le?X(e,s,c):e):new f(c===3?-0:0)};T.modulo=T.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=Be(n,e.abs(),0,3,1),t.s*=e.s):t=Be(n,e,0,r.modulo,1),t=t.times(e),le=!0,n.minus(t))};T.naturalExponential=T.exp=function(){return Vc(this)};T.naturalLogarithm=T.ln=function(){return Gn(this)};T.negated=T.neg=function(){var e=new this.constructor(this);return e.s=-e.s,X(e)};T.plus=T.add=function(e){var t,n,r,i,o,a,s,c,u,l,d=this,p=d.constructor;if(e=new p(e),!d.d||!e.d)return!d.s||!e.s?e=new p(NaN):d.d||(e=new p(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(u=d.d,l=e.d,s=p.precision,c=p.rounding,!u[0]||!l[0])return l[0]||(e=new p(d)),le?X(e,s,c):e;if(o=Ot(d.e/ie),r=Ot(e.e/ie),u=u.slice(),i=o-r,i){for(i<0?(n=u,i=-i,a=l.length):(n=l,r=o,a=u.length),o=Math.ceil(s/ie),a=o>a?o+1:a+1,i>a&&(i=a,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(a=u.length,i=l.length,a-i<0&&(i=a,n=l,l=u,u=n),t=0;i;)t=(u[--i]=u[i]+l[i]+t)/dn|0,u[i]%=dn;for(t&&(u.unshift(t),++r),a=u.length;u[--a]==0;)u.pop();return e.d=u,e.e=ya(u,r),le?X(e,s,c):e};T.precision=T.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Kn+e);return n.d?(t=zf(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};T.round=function(){var e=this,t=e.constructor;return X(new t(e),e.e+1,t.rounding)};T.sine=T.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=Nx(r,Zf(r,n)),r.precision=e,r.rounding=t,X(Cn>2?n.neg():n,e,t,!0)):new r(NaN)};T.squareRoot=T.sqrt=function(){var e,t,n,r,i,o,a=this,s=a.d,c=a.e,u=a.s,l=a.constructor;if(u!==1||!s||!s[0])return new l(!u||u<0&&(!s||s[0])?NaN:s?a:1/0);for(le=!1,u=Math.sqrt(+a),u==0||u==1/0?(t=St(s),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=Ot((c+1)/2)-(c<0||c%2),u==1/0?t="5e"+c:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new l(t)):r=new l(u.toString()),n=(c=l.precision)+3;;)if(o=r,r=o.plus(Be(a,o,n+2,1)).times(.5),St(o.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(o,c+1,0),o.times(o).eq(a))){r=o;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(X(r,c+1,1),e=!r.times(r).eq(a));break}return le=!0,X(r,c,l.rounding,e)};T.tangent=T.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Be(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,X(Cn==2||Cn==4?n.neg():n,e,t,!0)):new r(NaN)};T.times=T.mul=function(e){var t,n,r,i,o,a,s,c,u,l=this,d=l.constructor,p=l.d,g=(e=new d(e)).d;if(e.s*=l.s,!p||!p[0]||!g||!g[0])return new d(!e.s||p&&!p[0]&&!g||g&&!g[0]&&!p?NaN:!p||!g?e.s/0:e.s*0);for(n=Ot(l.e/ie)+Ot(e.e/ie),c=p.length,u=g.length,c<u&&(o=p,p=g,g=o,a=c,c=u,u=a),o=[],a=c+u,r=a;r--;)o.push(0);for(r=u;--r>=0;){for(t=0,i=c+r;i>r;)s=o[i]+g[r]*p[i-r-1]+t,o[i--]=s%dn|0,t=s/dn|0;o[i]=(o[i]+t)%dn|0}for(;!o[--a];)o.pop();return t?++n:o.shift(),e.d=o,e.e=ya(o,n),le?X(e,d.precision,d.rounding):e};T.toBinary=function(e,t){return $c(this,2,e,t)};T.toDecimalPlaces=T.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Dt(e,0,zn),t===void 0?t=r.rounding:Dt(t,0,8),X(n,e+n.e+1,t))};T.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=xn(r,!0):(Dt(e,0,zn),t===void 0?t=i.rounding:Dt(t,0,8),r=X(new i(r),e+1,t),n=xn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};T.toFixed=function(e,t){var n,r,i=this,o=i.constructor;return e===void 0?n=xn(i):(Dt(e,0,zn),t===void 0?t=o.rounding:Dt(t,0,8),r=X(new o(i),e+i.e+1,t),n=xn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};T.toFraction=function(e){var t,n,r,i,o,a,s,c,u,l,d,p,g=this,f=g.d,h=g.constructor;if(!f)return new h(g);if(u=n=new h(1),r=c=new h(0),t=new h(r),o=t.e=zf(f)-g.e-1,a=o%ie,t.d[0]=ct(10,a<0?ie+a:a),e==null)e=o>0?t:u;else{if(s=new h(e),!s.isInt()||s.lt(u))throw Error(Kn+s);e=s.gt(t)?o>0?t:u:s}for(le=!1,s=new h(St(f)),l=h.precision,h.precision=o=f.length*ie*2;d=Be(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=c.plus(d.times(i)),c=i,i=t,t=s.minus(d.times(i)),s=i;return i=Be(e.minus(n),r,0,1,1),c=c.plus(i.times(u)),n=n.plus(i.times(r)),c.s=u.s=g.s,p=Be(u,r,o,1).minus(g).abs().cmp(Be(c,n,o,1).minus(g).abs())<1?[u,r]:[c,n],h.precision=l,le=!0,p};T.toHexadecimal=T.toHex=function(e,t){return $c(this,16,e,t)};T.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:Dt(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=Be(n,e,0,t,1).times(e),le=!0,X(n)):(e.s=n.s,n=e),n};T.toNumber=function(){return+this};T.toOctal=function(e,t){return $c(this,8,e,t)};T.toPower=T.pow=function(e){var t,n,r,i,o,a,s=this,c=s.constructor,u=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(ct(+s,u));if(s=new c(s),s.eq(1))return s;if(r=c.precision,o=c.rounding,e.eq(1))return X(s,r,o);if(t=Ot(e.e/ie),t>=e.d.length-1&&(n=u<0?-u:u)<=Tx)return i=Hf(c,s,n,r),e.s<0?new c(1).div(i):X(i,r,o);if(a=s.s,a<0){if(t<e.d.length-1)return new c(NaN);if((e.d[t]&1)==0&&(a=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=a,s}return n=ct(+s,u),t=n==0||!isFinite(n)?Ot(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?a/0:0):(le=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Vc(e.times(Gn(s,r+n)),r),i.d&&(i=X(i,r+5,1),Qi(i.d,r,o)&&(t=r+10,i=X(Vc(e.times(Gn(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=a,le=!0,c.rounding=o,X(i,r,o))};T.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=xn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Dt(e,1,zn),t===void 0?t=i.rounding:Dt(t,0,8),r=X(new i(r),e,t),n=xn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};T.toSignificantDigits=T.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Dt(e,1,zn),t===void 0?t=r.rounding:Dt(t,0,8)),X(new r(n),e,t)};T.toString=function(){var e=this,t=e.constructor,n=xn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};T.truncated=T.trunc=function(){return X(new this.constructor(this),this.e+1,1)};T.valueOf=T.toJSON=function(){var e=this,t=e.constructor,n=xn(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,o="",a=e[0];if(i>0){for(o+=a,t=1;t<i;t++)r=e[t]+"",n=ie-r.length,n&&(o+=$n(n)),o+=r;a=e[t],r=a+"",n=ie-r.length,n&&(o+=$n(n))}else if(a===0)return"0";for(;a%10===0;)a/=10;return o+a}function Dt(e,t,n){if(e!==~~e||e<t||e>n)throw Error(Kn+e)}function Qi(e,t,n,r){var i,o,a,s;for(o=e[0];o>=10;o/=10)--t;return--t<0?(t+=ie,i=0):(i=Math.ceil((t+1)/ie),t%=ie),o=ct(10,ie-t),s=e[i]%o|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),a=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):a=(n<4&&s+1==o||n>3&&s+1==o/2)&&(e[i+1]/o/100|0)==ct(10,t-2)-1||(s==o/2||s==0)&&(e[i+1]/o/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),a=(r||n<4)&&s==9999||!r&&n>3&&s==4999):a=((r||n<4)&&s+1==o||!r&&n>3&&s+1==o/2)&&(e[i+1]/o/1e3|0)==ct(10,t-3)-1,a}function ma(e,t,n){for(var r,i=[0],o,a=0,s=e.length;a<s;){for(o=i.length;o--;)i[o]*=t;for(i[0]+=Lc.indexOf(e.charAt(a++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function kx(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/Sa(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=zr(e,1,t.times(i),new e(1));for(var o=n;o--;){var a=t.times(t);t=a.times(a).minus(a).times(8).plus(1)}return e.precision-=n,t}var Be=(function(){function e(r,i,o){var a,s=0,c=r.length;for(r=r.slice();c--;)a=r[c]*i+s,r[c]=a%o|0,s=a/o|0;return s&&r.unshift(s),r}function t(r,i,o,a){var s,c;if(o!=a)c=o>a?1:-1;else for(s=c=0;s<o;s++)if(r[s]!=i[s]){c=r[s]>i[s]?1:-1;break}return c}function n(r,i,o,a){for(var s=0;o--;)r[o]-=s,s=r[o]<i[o]?1:0,r[o]=s*a+r[o]-i[o];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,o,a,s,c){var u,l,d,p,g,f,h,v,I,S,R,D,P,be,nt,Qe,je,ue,$,De,Q=r.constructor,pt=r.s==i.s?1:-1,me=r.d,ce=i.d;if(!me||!me[0]||!ce||!ce[0])return new Q(!r.s||!i.s||(me?ce&&me[0]==ce[0]:!ce)?NaN:me&&me[0]==0||!ce?pt*0:pt/0);for(c?(g=1,l=r.e-i.e):(c=dn,g=ie,l=Ot(r.e/g)-Ot(i.e/g)),$=ce.length,je=me.length,I=new Q(pt),S=I.d=[],d=0;ce[d]==(me[d]||0);d++);if(ce[d]>(me[d]||0)&&l--,o==null?(be=o=Q.precision,a=Q.rounding):s?be=o+(r.e-i.e)+1:be=o,be<0)S.push(1),f=!0;else{if(be=be/g+2|0,d=0,$==1){for(p=0,ce=ce[0],be++;(d<je||p)&&be--;d++)nt=p*c+(me[d]||0),S[d]=nt/ce|0,p=nt%ce|0;f=p||d<je}else{for(p=c/(ce[0]+1)|0,p>1&&(ce=e(ce,p,c),me=e(me,p,c),$=ce.length,je=me.length),Qe=$,R=me.slice(0,$),D=R.length;D<$;)R[D++]=0;De=ce.slice(),De.unshift(0),ue=ce[0],ce[1]>=c/2&&++ue;do p=0,u=t(ce,R,$,D),u<0?(P=R[0],$!=D&&(P=P*c+(R[1]||0)),p=P/ue|0,p>1?(p>=c&&(p=c-1),h=e(ce,p,c),v=h.length,D=R.length,u=t(h,R,v,D),u==1&&(p--,n(h,$<v?De:ce,v,c))):(p==0&&(u=p=1),h=ce.slice()),v=h.length,v<D&&h.unshift(0),n(R,h,D,c),u==-1&&(D=R.length,u=t(ce,R,$,D),u<1&&(p++,n(R,$<D?De:ce,D,c))),D=R.length):u===0&&(p++,R=[0]),S[d++]=p,u&&R[0]?R[D++]=me[Qe]||0:(R=[me[Qe]],D=1);while((Qe++<je||R[0]!==void 0)&&be--);f=R[0]!==void 0}S[0]||S.shift()}if(g==1)I.e=l,qf=f;else{for(d=1,p=S[0];p>=10;p/=10)d++;I.e=d+l*g-1,X(I,s?o+I.e+1:o,a,f)}return I}})();function X(e,t,n,r){var i,o,a,s,c,u,l,d,p,g=e.constructor;e:if(t!=null){if(d=e.d,!d)return e;for(i=1,s=d[0];s>=10;s/=10)i++;if(o=t-i,o<0)o+=ie,a=t,l=d[p=0],c=l/ct(10,i-a-1)%10|0;else if(p=Math.ceil((o+1)/ie),s=d.length,p>=s)if(r){for(;s++<=p;)d.push(0);l=c=0,i=1,o%=ie,a=o-ie+1}else break e;else{for(l=s=d[p],i=1;s>=10;s/=10)i++;o%=ie,a=o-ie+i,c=a<0?0:l/ct(10,i-a-1)%10|0}if(r=r||t<0||d[p+1]!==void 0||(a<0?l:l%ct(10,i-a-1)),u=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(o>0?a>0?l/ct(10,i-a):0:d[p-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,u?(t-=e.e+1,d[0]=ct(10,(ie-t%ie)%ie),e.e=-t||0):d[0]=e.e=0,e;if(o==0?(d.length=p,s=1,p--):(d.length=p+1,s=ct(10,ie-o),d[p]=a>0?(l/ct(10,i-a)%ct(10,a)|0)*s:0),u)for(;;)if(p==0){for(o=1,a=d[0];a>=10;a/=10)o++;for(a=d[0]+=s,s=1;a>=10;a/=10)s++;o!=s&&(e.e++,d[0]==dn&&(d[0]=1));break}else{if(d[p]+=s,d[p]!=dn)break;d[p--]=0,s=1}for(o=d.length;d[--o]===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 xn(e,t,n){if(!e.isFinite())return Qf(e);var r,i=e.e,o=St(e.d),a=o.length;return t?(n&&(r=n-a)>0?o=o.charAt(0)+"."+o.slice(1)+$n(r):a>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(e.e<0?"e":"e+")+e.e):i<0?(o="0."+$n(-i-1)+o,n&&(r=n-a)>0&&(o+=$n(r))):i>=a?(o+=$n(i+1-a),n&&(r=n-i-1)>0&&(o=o+"."+$n(r))):((r=i+1)<a&&(o=o.slice(0,r)+"."+o.slice(r)),n&&(r=n-a)>0&&(i+1===a&&(o+="."),o+=$n(r))),o}function ya(e,t){var n=e[0];for(t*=ie;n>=10;n/=10)t++;return t}function ba(e,t,n){if(t>Rx)throw le=!0,n&&(e.precision=n),Error(Vf);return X(new e(ga),t,1,!0)}function Sn(e,t,n){if(t>qc)throw Error(Vf);return X(new e(ha),t,n,!0)}function zf(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 $n(e){for(var t="";e--;)t+="0";return t}function Hf(e,t,n,r){var i,o=new e(1),a=Math.ceil(r/ie+4);for(le=!1;;){if(n%2&&(o=o.times(t),Lf(o.d,a)&&(i=!0)),n=Ot(n/2),n===0){n=o.d.length-1,i&&o.d[n]===0&&++o.d[n];break}t=t.times(t),Lf(t.d,a)}return le=!0,o}function Mf(e){return e.d[e.d.length-1]&1}function Wf(e,t,n){for(var r,i,o=new e(t[0]),a=0;++a<t.length;){if(i=new e(t[a]),!i.s){o=i;break}r=o.cmp(i),(r===n||r===0&&o.s===n)&&(o=i)}return o}function Vc(e,t){var n,r,i,o,a,s,c,u=0,l=0,d=0,p=e.constructor,g=p.rounding,f=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(le=!1,c=f):c=t,s=new p(.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=o=a=new p(1),p.precision=c;;){if(o=X(o.times(e),c,1),n=n.times(++l),s=a.plus(Be(o,n,c,1)),St(s.d).slice(0,c)===St(a.d).slice(0,c)){for(i=d;i--;)a=X(a.times(a),c,1);if(t==null)if(u<3&&Qi(a.d,c-r,g,u))p.precision=c+=10,n=o=s=new p(1),l=0,u++;else return X(a,p.precision=f,g,le=!0);else return p.precision=f,a}a=s}}function Gn(e,t){var n,r,i,o,a,s,c,u,l,d,p,g=1,f=10,h=e,v=h.d,I=h.constructor,S=I.rounding,R=I.precision;if(h.s<0||!v||!v[0]||!h.e&&v[0]==1&&v.length==1)return new I(v&&!v[0]?-1/0:h.s!=1?NaN:v?0:h);if(t==null?(le=!1,l=R):l=t,I.precision=l+=f,n=St(v),r=n.charAt(0),Math.abs(o=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=St(h.d),r=n.charAt(0),g++;o=h.e,r>1?(h=new I("0."+n),o++):h=new I(r+"."+n.slice(1))}else return u=ba(I,l+2,R).times(o+""),h=Gn(new I(r+"."+n.slice(1)),l-f).plus(u),I.precision=R,t==null?X(h,R,S,le=!0):h;for(d=h,c=a=h=Be(h.minus(1),h.plus(1),l,1),p=X(h.times(h),l,1),i=3;;){if(a=X(a.times(p),l,1),u=c.plus(Be(a,new I(i),l,1)),St(u.d).slice(0,l)===St(c.d).slice(0,l))if(c=c.times(2),o!==0&&(c=c.plus(ba(I,l+2,R).times(o+""))),c=Be(c,new I(g),l,1),t==null)if(Qi(c.d,l-f,S,s))I.precision=l+=f,u=a=h=Be(d.minus(1),d.plus(1),l,1),p=X(h.times(h),l,1),i=s=1;else return X(c,I.precision=R,S,le=!0);else return I.precision=R,c;c=u,i+=2}}function Qf(e){return String(e.s*e.s/0)}function fa(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 jx(e,t){var n,r,i,o,a,s,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Kf.test(t))return fa(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Cx.test(t))n=16,t=t.toLowerCase();else if(Px.test(t))n=2;else if(Ex.test(t))n=8;else throw Error(Kn+t);for(o=t.search(/p/i),o>0?(c=+t.slice(o+1),t=t.substring(2,o)):t=t.slice(2),o=t.indexOf("."),a=o>=0,r=e.constructor,a&&(t=t.replace(".",""),s=t.length,o=s-o,i=Hf(r,new r(n),o,o*2)),u=ma(t,n,dn),l=u.length-1,o=l;u[o]===0;--o)u.pop();return o<0?new r(e.s*0):(e.e=ya(u,l),e.d=u,le=!1,a&&(e=Be(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?ct(2,c):pn.pow(2,c))),le=!0,e)}function Nx(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/Sa(5,n)),t=zr(e,2,t,t);for(var i,o=new e(5),a=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(o.plus(i.times(a.times(i).minus(s))));return t}function zr(e,t,n,r,i){var o,a,s,c,u=1,l=e.precision,d=Math.ceil(l/ie);for(le=!1,c=n.times(n),s=new e(r);;){if(a=Be(s.times(c),new e(t++*t++),l,1),s=i?r.plus(a):r.minus(a),r=Be(a.times(c),new e(t++*t++),l,1),a=s.plus(r),a.d[d]!==void 0){for(o=d;a.d[o]===s.d[o]&&o--;);if(o==-1)break}o=s,s=r,r=a,a=o,u++}return le=!0,a.d.length=d+1,a}function Sa(e,t){for(var n=e;--t;)n*=e;return n}function Zf(e,t){var n,r=t.s<0,i=Sn(e,e.precision,1),o=i.times(.5);if(t=t.abs(),t.lte(o))return Cn=r?4:1,t;if(n=t.divToInt(i),n.isZero())Cn=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(o))return Cn=Mf(n)?r?2:3:r?4:1,t;Cn=Mf(n)?r?1:4:r?3:2}return t.minus(i).abs()}function $c(e,t,n,r){var i,o,a,s,c,u,l,d,p,g=e.constructor,f=n!==void 0;if(f?(Dt(n,1,zn),r===void 0?r=g.rounding:Dt(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())l=Qf(e);else{for(l=xn(e),a=l.indexOf("."),f?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,a>=0&&(l=l.replace(".",""),p=new g(1),p.e=l.length-a,p.d=ma(xn(p),10,i),p.e=p.d.length),d=ma(l,10,i),o=c=d.length;d[--c]==0;)d.pop();if(!d[0])l=f?"0p+0":"0";else{if(a<0?o--:(e=new g(e),e.d=d,e.e=o,e=Be(e,p,n,r,0,i),d=e.d,o=e.e,u=qf),a=d[n],s=i/2,u=u||d[n+1]!==void 0,u=r<4?(a!==void 0||u)&&(r===0||r===(e.s<0?3:2)):a>s||a===s&&(r===4||u||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,u)for(;++d[--n]>i-1;)d[n]=0,n||(++o,d.unshift(1));for(c=d.length;!d[c-1];--c);for(a=0,l="";a<c;a++)l+=Lc.charAt(d[a]);if(f){if(c>1)if(t==16||t==8){for(a=t==16?4:3,--c;c%a;c++)l+="0";for(d=ma(l,i,t),c=d.length;!d[c-1];--c);for(a=1,l="1.";a<c;a++)l+=Lc.charAt(d[a])}else l=l.charAt(0)+"."+l.slice(1);l=l+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)l="0"+l;l="0."+l}else if(++o>c)for(o-=c;o--;)l+="0";else o<c&&(l=l.slice(0,o)+"."+l.slice(o))}l=(t==16?"0x":t==2?"0b":t==8?"0o":"")+l}return e.s<0?"-"+l:l}function Lf(e,t){if(e.length>t)return e.length=t,!0}function Dx(e){return new this(e).abs()}function Fx(e){return new this(e).acos()}function Ux(e){return new this(e).acosh()}function Mx(e,t){return new this(e).plus(t)}function Lx(e){return new this(e).asin()}function Bx(e){return new this(e).asinh()}function qx(e){return new this(e).atan()}function Vx(e){return new this(e).atanh()}function $x(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,o=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=Sn(this,o,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?Sn(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=Sn(this,o,1).times(.5),n.s=e.s):t.s<0?(this.precision=o,this.rounding=1,n=this.atan(Be(e,t,o,1)),t=Sn(this,o,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Be(e,t,o,1)),n}function Gx(e){return new this(e).cbrt()}function Kx(e){return X(e=new this(e),e.e+1,2)}function zx(e,t,n){return new this(e).clamp(t,n)}function Hx(e){if(!e||typeof e!="object")throw Error(_a+"Object expected");var t,n,r,i=e.defaults===!0,o=["precision",1,zn,"rounding",0,8,"toExpNeg",-Kr,0,"toExpPos",0,Kr,"maxE",0,Kr,"minE",-Kr,0,"modulo",0,9];for(t=0;t<o.length;t+=3)if(n=o[t],i&&(this[n]=Bc[n]),(r=e[n])!==void 0)if(Ot(r)===r&&r>=o[t+1]&&r<=o[t+2])this[n]=r;else throw Error(Kn+n+": "+r);if(n="crypto",i&&(this[n]=Bc[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($f);else this[n]=!1;else throw Error(Kn+n+": "+r);return this}function Wx(e){return new this(e).cos()}function Qx(e){return new this(e).cosh()}function Yf(e){var t,n,r;function i(o){var a,s,c,u=this;if(!(u instanceof i))return new i(o);if(u.constructor=i,Bf(o)){u.s=o.s,le?!o.d||o.e>i.maxE?(u.e=NaN,u.d=null):o.e<i.minE?(u.e=0,u.d=[0]):(u.e=o.e,u.d=o.d.slice()):(u.e=o.e,u.d=o.d?o.d.slice():o.d);return}if(c=typeof o,c==="number"){if(o===0){u.s=1/o<0?-1:1,u.e=0,u.d=[0];return}if(o<0?(o=-o,u.s=-1):u.s=1,o===~~o&&o<1e7){for(a=0,s=o;s>=10;s/=10)a++;le?a>i.maxE?(u.e=NaN,u.d=null):a<i.minE?(u.e=0,u.d=[0]):(u.e=a,u.d=[o]):(u.e=a,u.d=[o]);return}if(o*0!==0){o||(u.s=NaN),u.e=NaN,u.d=null;return}return fa(u,o.toString())}if(c==="string")return(s=o.charCodeAt(0))===45?(o=o.slice(1),u.s=-1):(s===43&&(o=o.slice(1)),u.s=1),Kf.test(o)?fa(u,o):jx(u,o);if(c==="bigint")return o<0?(o=-o,u.s=-1):u.s=1,fa(u,o.toString());throw Error(Kn+o)}if(i.prototype=T,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=Hx,i.clone=Yf,i.isDecimal=Bf,i.abs=Dx,i.acos=Fx,i.acosh=Ux,i.add=Mx,i.asin=Lx,i.asinh=Bx,i.atan=qx,i.atanh=Vx,i.atan2=$x,i.cbrt=Gx,i.ceil=Kx,i.clamp=zx,i.cos=Wx,i.cosh=Qx,i.div=Zx,i.exp=Yx,i.floor=Jx,i.hypot=Xx,i.ln=ev,i.log=tv,i.log10=rv,i.log2=nv,i.max=iv,i.min=ov,i.mod=av,i.mul=sv,i.pow=cv,i.random=uv,i.round=lv,i.sign=dv,i.sin=pv,i.sinh=mv,i.sqrt=fv,i.sub=gv,i.sum=hv,i.tan=bv,i.tanh=_v,i.trunc=yv,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 Zx(e,t){return new this(e).div(t)}function Yx(e){return new this(e).exp()}function Jx(e){return X(e=new this(e),e.e+1,3)}function Xx(){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 Bf(e){return e instanceof pn||e&&e.toStringTag===Gf||!1}function ev(e){return new this(e).ln()}function tv(e,t){return new this(e).log(t)}function nv(e){return new this(e).log(2)}function rv(e){return new this(e).log(10)}function iv(){return Wf(this,arguments,-1)}function ov(){return Wf(this,arguments,1)}function av(e,t){return new this(e).mod(t)}function sv(e,t){return new this(e).mul(t)}function cv(e,t){return new this(e).pow(t)}function uv(e){var t,n,r,i,o=0,a=new this(1),s=[];if(e===void 0?e=this.precision:Dt(e,1,zn),r=Math.ceil(e/ie),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));o<r;)i=t[o],i>=429e7?t[o]=crypto.getRandomValues(new Uint32Array(1))[0]:s[o++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);o<r;)i=t[o]+(t[o+1]<<8)+(t[o+2]<<16)+((t[o+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,o):(s.push(i%1e7),o+=4);o=r/4}else throw Error($f);else for(;o<r;)s[o++]=Math.random()*1e7|0;for(r=s[--o],e%=ie,r&&e&&(i=ct(10,ie-e),s[o]=(r/i|0)*i);s[o]===0;o--)s.pop();if(o<0)n=0,s=[0];else{for(n=-1;s[0]===0;n-=ie)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<ie&&(n-=ie-r)}return a.e=n,a.d=s,a}function lv(e){return X(e=new this(e),e.e+1,this.rounding)}function dv(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function pv(e){return new this(e).sin()}function mv(e){return new this(e).sinh()}function fv(e){return new this(e).sqrt()}function gv(e,t){return new this(e).sub(t)}function hv(){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 bv(e){return new this(e).tan()}function _v(e){return new this(e).tanh()}function yv(e){return X(e=new this(e),e.e+1,1)}T[Symbol.for("nodejs.util.inspect.custom")]=T.toString;T[Symbol.toStringTag]="Decimal";var pn=T.constructor=Yf(Bc);ga=new pn(ga);ha=new pn(ha);var{PAYLOAD_BYTES:Sv}={PAYLOAD_BYTES:20},{KSUID_EPOCH:xv}={KSUID_EPOCH:14e8},{getRandomBytes:vv}={getRandomBytes:({size:t})=>{let n=new Uint8Array(t);return globalThis.crypto.getRandomValues(n),n}},{ALPHABET:Iv}={ALPHABET:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},{ENCODED_LENGTH:Av}={ENCODED_LENGTH:27},{base62Encode:wv}=(e=>({base62Encode:({bytes:n,padTo:r})=>{let i=[],o=new Uint8Array(n),a=!1;for(;!a;){a=!0;let s=0;for(let c=0;c<o.length;c++){let u=s*256+o[c];o[c]=Math.floor(u/62),s=u%62,o[c]!==0&&(a=!1)}i.push(s)}for(i.reverse();i.length<r;)i.unshift(0);return i.map(s=>e[s]).join("")}}))(Iv),{generateKsuid:Jf}=((e,t,n,r,i)=>({generateKsuid:({prefix:a=""}={})=>{let s=new Uint8Array(e),c=Math.floor(Date.now()/1e3)-t;s[0]=c>>>24&255,s[1]=c>>>16&255,s[2]=c>>>8&255,s[3]=c&255;let u=n({size:16});s.set(u,4);let l=r({bytes:s,padTo:i});return`${a}${l}`}}))(Sv,xv,vv,wv,Av);var Xf={randomSync:()=>({string:Jf({})})};import{z as Ae}from"zod/v4";var Ov=202,Pv=502,Cv=400,Ev=409,Tv=100,Rv=201,kv=417;var jv=403,Nv=504,Dv=410,Fv=505,Uv=418,Mv=419,Lv=507,Bv=500,qv=411,Vv=423,$v=420,Gv=405,Kv=301,zv=302,Hv=207,Wv=300,Qv=511,Zv=204,Yv=203,Jv=406,Xv=404,eI=501,tI=304,nI=200,rI=206,iI=402,oI=308,aI=412,sI=428,cI=102,uI=407,lI=431,dI=408,pI=413,mI=414,fI=416,gI=205,hI=303,bI=503,_I=101,yI=307,SI=429,xI=401,vI=422,II=415,AI=305,eg={ACCEPTED:Ov,BAD_GATEWAY:Pv,BAD_REQUEST:Cv,CONFLICT:Ev,CONTINUE:Tv,CREATED:Rv,EXPECTATION_FAILED:kv,FORBIDDEN:jv,GATEWAY_TIMEOUT:Nv,GONE:Dv,HTTP_VERSION_NOT_SUPPORTED:Fv,IM_A_TEAPOT:Uv,INSUFFICIENT_SPACE_ON_RESOURCE:Mv,INSUFFICIENT_STORAGE:Lv,INTERNAL_SERVER_ERROR:Bv,LENGTH_REQUIRED:qv,LOCKED:Vv,METHOD_FAILURE:$v,METHOD_NOT_ALLOWED:Gv,MOVED_PERMANENTLY:Kv,MOVED_TEMPORARILY:zv,MULTI_STATUS:Hv,MULTIPLE_CHOICES:Wv,NETWORK_AUTHENTICATION_REQUIRED:Qv,NO_CONTENT:Zv,NON_AUTHORITATIVE_INFORMATION:Yv,NOT_ACCEPTABLE:Jv,NOT_FOUND:Xv,NOT_IMPLEMENTED:eI,NOT_MODIFIED:tI,OK:nI,PARTIAL_CONTENT:rI,PAYMENT_REQUIRED:iI,PERMANENT_REDIRECT:oI,PRECONDITION_FAILED:aI,PRECONDITION_REQUIRED:sI,PROCESSING:cI,PROXY_AUTHENTICATION_REQUIRED:uI,REQUEST_HEADER_FIELDS_TOO_LARGE:lI,REQUEST_TIMEOUT:dI,REQUEST_TOO_LONG:pI,REQUEST_URI_TOO_LONG:mI,REQUESTED_RANGE_NOT_SATISFIABLE:fI,RESET_CONTENT:gI,SEE_OTHER:hI,SERVICE_UNAVAILABLE:bI,SWITCHING_PROTOCOLS:_I,TEMPORARY_REDIRECT:yI,TOO_MANY_REQUESTS:SI,UNAUTHORIZED:xI,UNPROCESSABLE_ENTITY:vI,UNSUPPORTED_MEDIA_TYPE:II,USE_PROXY:AI};var tg={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"},ng={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 wI(e){var t=tg[e.toString()];if(!t)throw new Error("Status code does not exist: "+e);return t}function rg(e){var t=ng[e];if(!t)throw new Error("Reason phrase does not exist: "+e);return t}var ig=wI;var Hn;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.MOVED_TEMPORARILY=302]="MOVED_TEMPORARILY",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.REQUEST_TOO_LONG=413]="REQUEST_TOO_LONG",e[e.REQUEST_URI_TOO_LONG=414]="REQUEST_URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.REQUESTED_RANGE_NOT_SATISFIABLE=416]="REQUESTED_RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.IM_A_TEAPOT=418]="IM_A_TEAPOT",e[e.INSUFFICIENT_SPACE_ON_RESOURCE=419]="INSUFFICIENT_SPACE_ON_RESOURCE",e[e.METHOD_FAILURE=420]="METHOD_FAILURE",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(Hn||(Hn={}));var xa=function(){return xa=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},xa.apply(this,arguments)},yM=xa(xa({},eg),{getStatusCode:rg,getStatusText:ig});var{generateId:Hr}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(Xf),{BILLING_CONTROL_KEYS:va}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:OI}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:og}={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:Xt}={nullish:t=>t==null},{FeatureType:Pt}=(()=>{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:Ia}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:Zi}={Infinite:"inf"},{EntInterval:Wr}=(()=>{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:En}=(()=>{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:PI}={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:CI}={usageCurrenciesToTiers:(t,n)=>{if(!t||n<=0)return;let r=Object.entries(t);if(r.length===0)return;let i=Array.from({length:n},()=>[]);for(let[o,a]of r)(a.usage_tiers??[]).forEach((s,c)=>{c<n&&i[c].push({currency:o,amount:s.amount,...s.flat_amount!==void 0?{flat_amount:s.flat_amount}:{}})});return i}},{TierInfinite:Gc}={TierInfinite:"inf"},{FeatureUsageType:Wn}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:Qr}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Usage="usage"})(e||(e={})),{PriceType:e}})(),{BillingType:Zr}=(()=>{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:Yi}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Qn}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:Tn}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:Yr}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{InternalError:EI}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=500,data:o}){super(n),this.name="InternalError",this.code=r||"internal_error",this.statusCode=i,this.data=o}}return{InternalError:e}})(),{getItemFeatureType:ag}=((e,t)=>({getItemFeatureType:({item:r,features:i})=>{let o=i.find(a=>a.id===r.feature_id);if(o)return o.type===e.Boolean?t.Static:o.type===e.CreditSystem?t.SingleUse:o.config?.usage_type}}))(Pt,Tn),{billingControlsFromColumns:sg}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(va),{nullish:Jr}={nullish:t=>t==null},{RecaseError:Ft}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=400,data:o}){super(n),this.name="RecaseError",this.code=r||"invalid_request",this.statusCode=i,this.data=o}}return{RecaseError:e}})(),{ErrCode:$t}={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:TI}=((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})}}))(Ft,$t),{notNullish:Xr}=(e=>({notNullish:n=>!e(n)}))(Jr),{keyToTitle:cg}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:RI}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:kI}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ApiFeatureType:jI}=(()=>{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:Kc}=(()=>{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:ug}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:NI}={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:DI}=(e=>({COMMON_SET:new Set(e)}))(ug),{hasNoDuplicateCurrencies:lg}={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:dg}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{TierBehavior:Aa}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:ei}=(()=>{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:Ji}=(()=>{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:zc}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:FI}=(()=>{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:UI}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:MI}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:pg}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ae),{flatCreditRateShape:mg}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(Ae),{CreditTierSchema:LI}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(Ae),{CreditMultiplierSchema:BI}=((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,pg),{MarkupEntrySchema:fg}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ae),{ModelMarkupsSchema:qI}=((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,fg),{isFeaturePriceItem:Hc}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(Xr),{notNullish:_r}={notNullish:t=>t!=null},{isAiCreditSystem:Wc}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(Pt),{VIOLATION_MESSAGES:VI}={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:$I}={sameSpecificity:(t,n)=>Object.keys(t.match).length===Object.keys(n.match).length&&(t.priority??null)===(n.priority??null)},{matchesCanCoexist:gg}={matchesCanCoexist:(t,n)=>Object.entries(t).every(([r,i])=>{let o=Object.entries(n).find(([a])=>a===r)?.[1];return o===void 0||o===i})},{formatCreditMatch:GI}={formatCreditMatch:t=>Object.entries(t).map(([n,r])=>`${n}=${r}`).join(", ")},{validateMultiplierShape:KI}={validateMultiplierShape:({name:t,multiplier:n,invalidCreditSystem:r})=>{let i=n.factor!==void 0,o=n.add!==void 0;!i&&!o&&r(`Multiplier "${t}" needs a factor or an add.`);let a=Number(n.factor);i&&!(Number.isFinite(a)&&a>0)&&r(`Multiplier "${t}" factor must be greater than zero.`);let s=Number(n.add);o&&!Number.isFinite(s)&&r(`Multiplier "${t}" add must be a number.`),i&&(n.factor=a),o&&(n.add=s)}},{minimumCreditRateAmount:zI}={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:HI}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((o,a)=>{let s=[];for(let u of r){let l=u.factor!==void 0&&u.factor<1||u.add!==void 0&&u.add<0,d=s.every(p=>e(p.match,u.match));(l||u===a)&&e(a.match,u.match)&&d&&s.push(u)}let c=s.reduce((u,l)=>u.mul(l.factor!==void 0&&l.factor<1?l.factor:1).add(l.add!==void 0&&l.add<0?l.add:0),new t(i));return t.min(o,c)},new t(i))}))(gg,pn),{validateCreditSystemSchemaReferences:WI}=((e,t,n,r)=>({validateCreditSystemSchemaReferences:({config:o,allFeatures:a,selfFeatureId:s})=>{let c=Array.isArray(o?.schema)?o.schema:[];if(c.length!==0)for(let u of c){let l=u.metered_feature_id;if(!l||l===s)continue;let d=a.find(p=>p.id===l);if(d){if(d.type===e.CreditSystem)throw new t({message:`Credit system schema cannot reference another credit system (${l}). Only metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Boolean)throw new t({message:`Credit system schema cannot reference boolean feature ${l}. Only consumable (single-use) metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Metered&&d.config?.usage_type===r.Continuous)throw new t({message:`Credit system schema cannot reference continuous feature ${l}. Only consumable (single-use) metered features are allowed.`,code:n.InvalidFeature,statusCode:400})}}}}))(Pt,Ft,$t,Wn),{isPriceItem:Qc}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(Xr,Jr),{isFeatureItem:wa}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(Xr,Jr),{itemToBillingInterval:Zn}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(Xt,En),{rolloverConfigToIssue:QI}={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:Oa}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(Xt,Wr,Tn),{itemToEntIntervalCount:Pa}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:ti}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:Ca}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(_r,Xt),{toKey:hg}={toKey:t=>t.toLowerCase()},{priceOwnedStripePriceId:ZI}=(e=>({priceOwnedStripePriceId:({price:n})=>{let r=n.config,i=r.stripe_prepaid_price_v2_id||r.stripe_price_id;return e(i)?null:i}}))(Xt),{UsageTierSchema:Zc}=((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,Zi),{IgnoredFixedPriceMetadataSchema:YI}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(Ae),{hasCatalogCurrencies:JI}={hasCatalogCurrencies:t=>Object.keys(t??{}).length>0},{usageTiersToComparisonShape:XI}={usageTiersToComparisonShape:t=>t.map((n,r)=>({amount:n.amount,flat_amount:n.flat_amount??0,to:r===t.length-1?null:n.to}))},{normalizedAllocatedBillingBehavior:e1}=(e=>({normalizedAllocatedBillingBehavior:n=>n.allocated_billing_behavior??(n.should_prorate?e.Prorated:e.Arrear)}))(Qn),{getResetUsage:bg}=((e,t,n,r)=>({getResetUsage:({item:o,feature:a})=>{if(o.feature_id)return e(o.reset_usage_when_enabled)&&(t(o)||n(o))&&a?a?.config?.usage_type===r.Single:o.reset_usage_when_enabled}}))(Jr,wa,Hc,Wn),{hasUnlimitedAllowanceType:t1}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(Ia),{normalizedEntitlementInterval:_g}=(e=>({normalizedEntitlementInterval:n=>n.interval??e.Lifetime}))(Wr),{normalizedEntitlementIntervalCount:n1}=((e,t)=>({normalizedEntitlementIntervalCount:r=>e(r)===t.Lifetime?1:r.interval_count??1}))(_g,Wr),{normalizeOptionalId:r1}={normalizeOptionalId:t=>t||null},{rolloversAreSame:i1}=(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}))(zc),{deterministicStringify:Yc}=(()=>{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:o1}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:a1}={expiriesAreSame:(t,n)=>(t.expiry_duration??null)===(n.expiry_duration??null)&&(t.expiry_length??null)==(n.expiry_length??null)},{itemToFeature:yg}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{isFeaturePriceItem:ni}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(_r),{ProductErrorCode:s1}={ProductErrorCode:{ProductNotFound:"product_not_found",ProductAlreadyExists:"product_already_exists",InvalidProductItem:"invalid_product_item"}},{buildUsagePriceCurrencies:c1}=(e=>({buildUsagePriceCurrencies:({baseTiers:n,itemTiers:r,flatCurrencies:i})=>{if(r?.length){let o=[...new Set(r.flatMap(s=>(s.additional_currencies??[]).map(c=>e(c.currency))))];if(o.length===0)return;let a={};for(let s of o)a[s]={usage_tiers:n.map((c,u)=>{let l=(r[u]?.additional_currencies??[]).find(d=>e(d.currency)===s);return{to:c.to,amount:l?.amount??0,...l?.flat_amount!==void 0?{flat_amount:l.flat_amount}:{}}})};return a}if(i?.length&&n.length>0){let o={};for(let{currency:a,amount:s}of i)o[e(a)]={usage_tiers:[{to:n[0].to,amount:s}]};return o}}}))(hg),{itemToFeature:u1}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{shouldProrate:l1}=((e,t)=>({shouldProrate:r=>r?r===e.ProrateNextCycle||r===e.ProrateImmediately||r===t.ProrateImmediately||r===t.ProrateNextCycle:!0}))(ei,Ji),{getBillingType:d1}=((e,t,n,r)=>({getBillingType:o=>{if(o.type===e.Fixed&&o.interval===t.OneOff)return n.OneOff;if(o.type===e.Fixed)return n.FixedCycle;let a=o;return a.bill_when===r.InAdvance||a.bill_when===r.StartOfPeriod?n.UsageInAdvance:a.bill_when===r.EndOfPeriod&&a.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Qr,En,Zr,Yi),{stripeResourceFields:p1}={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:m1}={PREVIEW_STRIPE_PRICE_ID_PREFIX:"price_PREVIEW_"},{PREVIEW_STRIPE_PRODUCT_ID_PREFIX:f1}={PREVIEW_STRIPE_PRODUCT_ID_PREFIX:"prod_PREVIEW_"},{normalizeOptionalId:g1}={normalizeOptionalId:t=>t||null},{stripeProductOnlyFields:h1}={stripeProductOnlyFields:["stripe_product_id","stripe_meter_id"]},{copyField:b1}=(e=>({copyField:({fromConfig:n,toConfig:r,field:i})=>!e(r[i])||e(n[i])?!1:(r[i]=n[i],!0)}))(Xt),{stripeResourceFields:_1}={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:y1}={handleCustomProductItems:({newPrices:t,newEnts:n,updatedPrices:r,updatedEnts:i,samePrices:o,sameEnts:a,features:s})=>({prices:[...t,...r,...o],entitlements:[...n,...i,...a].map(c=>({...c,feature:s.find(u=>u.id===c.feature_id)})),customPrices:[...t,...r],customEnts:[...n,...i],features:s})},{validateLicenseBillingMode:S1}=((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})}}))(Ft,$t),{PlanItemMatchPrecision:x1}=(()=>{var e;return(function(t){t.FeatureBillingMethodCadence="feature_billing_method_cadence",t.FeatureCadence="feature_cadence"})(e||(e={})),{PlanItemMatchPrecision:e}})(),{catalogPlanItemIdentity:v1}={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:I1}={applyPrice:(t,n)=>n===void 0?t:n===null?null:{...n}},{planItemMatchesFilter:A1}={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:w1}={isFreeNonResetEntitlement:t=>t.price==null&&t.reset==null},{toApiPlanItemPrice:O1}={toApiPlanItemPrice:t=>t?{...t,billing_units:t.billing_units??1,max_purchase:t.max_purchase??null}:null},{toApiPlanItemRollover:P1}={toApiPlanItemRollover:t=>{if(t)return{...t,max:t.max??null}}},{applyFreeTrial:C1}={applyFreeTrial:(t,n)=>{if(n===void 0)return t;if(n!==null)return{...n}}},{applyLicenseUpsert:E1}={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:Sg}=(()=>{var e;return(function(t){t.Identity="identity",t.IdentityAndIncluded="identity_and_included"})(e||(e={})),{PlanItemFilterPrecision:e}})(),{additionalCurrenciesCompatible:Jc}={additionalCurrenciesCompatible:(t,n)=>(t??[]).every(r=>{let i=(n??[]).find(o=>o.currency.toLowerCase()===r.currency.toLowerCase());return!i||(r.amount??null)===(i.amount??null)&&(r.flat_amount??null)===(i.flat_amount??null)})},{toBasePriceParams:T1}={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:R1}=(e=>({tiersEqual:(n,r)=>!n?.length&&!r?.length?!0:!n||!r||n.length!==r.length?!1:n.every((i,o)=>{let a=r[o];return i.to===a.to&&(i.amount??0)===(a.amount??0)&&(i.flat_amount??null)===(a.flat_amount??null)&&e(i.additional_currencies,a.additional_currencies)})}))(Jc),{rolloversEqual:k1}={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:j1}={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:N1}=(e=>({creditSchemaFingerprint:n=>e(Object.fromEntries((n??[]).map(r=>[r.metered_feature_id,{...r,billing_units:r.billing_units??1}])))}))(Yc),{toCreatePlanItemParams:D1}={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:F1}=(e=>({buildRemoveFilter:({item:n,filterPrecision:r})=>{let i={feature_id:n.feature_id};n.price?.billing_method!==void 0&&(i.billing_method=n.price.billing_method);let o=n.price?.interval??n.reset?.interval;o!==void 0&&(i.interval=o);let a=n.price?.interval_count??n.reset?.interval_count;return o!==void 0&&(i.interval_count=a??1),r===e.IdentityAndIncluded&&typeof n.included=="number"&&n.unlimited!==!0&&(n.reset!=null||n.price!=null)&&(i.included=n.included),i}}))(Sg),{FreeTrialDuration:U1}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{arraysEqual:M1}={arraysEqual:({left:t,right:n,equals:r})=>{if(!t?.length&&!n?.length)return!0;if(!t||!n||t.length!==n.length)return!1;let i=[...n];return t.every(o=>{let a=i.findIndex(s=>r(o,s));return a===-1?!1:(i.splice(a,1),!0)})}},{normalizeIntervalCount:L1}={normalizeIntervalCount:({interval:t,intervalCount:n})=>t?n??1:n??""},{hasLicenseCustomize:xg}={hasLicenseCustomize:t=>t!=null&&(t.price!==void 0||t.add_items!==void 0||t.remove_items!==void 0)},{byLicensePlanId:B1}={byLicensePlanId:(t,n)=>t.license_plan_id.localeCompare(n.license_plan_id)},{variantSettingKeys:q1}={variantSettingKeys:["name","description","group","add_on","config","billing_controls","metadata"]},{valuesEqual:V1}={valuesEqual:(t,n)=>JSON.stringify(t)===JSON.stringify(n)},{omitVariantOwnedSettings:PM}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:$1}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(Xt),{isPriceItem:Ea}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(_r,Xt),{isDefaultTrialV2:CM}=(e=>({isDefaultTrialV2:({freeTrial:n,items:r,isDefault:i})=>n?n.card_required===!1&&i&&!e({items:r}):!1}))($1),{variantSettingsFields:G1}={variantSettingsFields:["description","group","is_add_on","is_default","config","billing_controls","metadata"]},{sortDeep:vg}=(()=>{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:K1}={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:z1}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:H1}={licenseParentTargetKey:({planId:t,version:n})=>`${t}@${n}`},{STRIPE_ZERO_DECIMAL_CURRENCIES:Ig}={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:W1}={STRIPE_THREE_DECIMAL_CURRENCIES:new Set(["bhd","jod","kwd","omr","tnd"])},{currencyInputDecimals:Ag}=(e=>({currencyInputDecimals:n=>e.has((n??"usd").toLowerCase())?0:2}))(Ig),{entIntervalToValue:Q1}=((e,t)=>({entIntervalToValue:(r,i)=>{if(!r)return new e(1e7);let a={[t.Minute]:1,[t.Hour]:60,[t.Day]:1440,[t.Week]:1440*7,[t.Month]:1440*30,[t.Quarter]:1440*90,[t.SemiAnnual]:1440*180,[t.Year]:1440*365,[t.Lifetime]:1e9}[r];return new e(a).mul(i??1)}}))(pn,Wr),{intervalToValue:Z1}=(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)}))(En),{normalizeIncludedUsage:wg}={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:Y1}=((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)}))(ei,Ji),{itemToExplicitAllocatedBillingBehavior:J1}=((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)}))(_r,Qn),{additionalCurrenciesAreSame:Xc}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let o=(c,u)=>c.currency.localeCompare(u.currency),a=[...r].sort(o),s=[...i].sort(o);return a.every((c,u)=>c.currency===s[u].currency&&(c.amount??null)===(s[u].amount??null)&&(c.flat_amount??null)===(s[u].flat_amount??null))}},{itemPricingTiers:X1}={itemPricingTiers:t=>t.tiers?.length?t.tiers:t.price!=null?[{amount:t.price,to:"inf"}]:null},{priceItemsAreSame:eA}=((e,t,n)=>({priceItemsAreSame:({item1:i,item2:o,logDifferences:a=!1})=>{let s=i.price===o.price&&e({item:i})==e({item:o})&&t({item:i})==t({item:o})&&n(i.additional_currencies,o.additional_currencies);return!s&&a&&console.log(`Price items different: ${i.price}`),s}}))(Zn,ti,Xc),{calculateProrationAmount:tA}=(e=>({calculateProrationAmount:({periodEnd:n,periodStart:r,now:i,amount:o,allowNegative:a=!1})=>{let s=new e(n).minus(i),c=new e(n).minus(r),u=s.div(c).mul(o);return u.lte(0)&&!a?0:u.toNumber()}}))(pn),{getResetUsage:nA}=((e,t,n,r)=>({getResetUsage:({item:o,feature:a})=>{if(o.feature_id)return e(o.reset_usage_when_enabled)&&(t(o)||n(o))&&a?a?.config?.usage_type===r.Single:o.reset_usage_when_enabled}}))(Xt,Ca,ni,Wn),{compareDetails:rA}={compareDetails:({newProductV2:t,curProductV2:n})=>{let r={is_add_on:{condition:t?.is_add_on===n?.is_add_on,message:`Is add-on different: ${t?.is_add_on} !== ${n?.is_add_on}`},is_default:{condition:t?.is_default===n?.is_default,message:`Is default different: ${t?.is_default} !== ${n?.is_default}`},archived:{condition:t?.archived===n?.archived,message:`Archived different: ${t?.archived} !== ${n?.archived}`},group:{condition:t?.group==n?.group,message:`Group different: ${t?.group} !== ${n?.group}`},name:{condition:t?.name==n?.name,message:`Name different: ${t?.name} !== ${n?.name}`},id:{condition:t?.id===n?.id,message:`ID different: ${t?.id} !== ${n?.id}`}};return Object.values(r).every(o=>o.condition)}},{compareConfig:iA}={compareConfig:({newConfig:t,curConfig:n})=>{let r={ignore_past_due:{condition:!!t?.ignore_past_due==!!n?.ignore_past_due,message:`Ignore past due different: ${t?.ignore_past_due} !== ${n?.ignore_past_due}`}};return Object.values(r).every(o=>o.condition)}},{normalizeBillingControlsForCompare:oA}=(e=>({normalizeBillingControlsForCompare:n=>{if(!n)return;let r=n.spend_limits?.map(o=>{if(o.skip_overage_billing===!0)return o;let{skip_overage_billing:a,...s}=o;return s}),i=Object.fromEntries(e.flatMap(o=>{let a=o==="spend_limits"?r:n[o];return a==null||a.length===0?[]:[[o,a]]}));return Object.keys(i).length>0?i:void 0}}))(va),{sortControls:aA}={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:sA}={compareMetadata:({newMetadata:t,curMetadata:n})=>{let r=i=>JSON.stringify(i??{},(o,a)=>a&&typeof a=="object"&&!Array.isArray(a)?Object.keys(a).sort().reduce((s,c)=>(s[c]=a[c],s),{}):a);return r(t)===r(n)}},{freeTrialsAreSame:cA}={freeTrialsAreSame:({ft1:t,ft2:n})=>{if(!t&&!n)return!0;if(!t||!n)return!1;let r={length:{condition:t.length!==n.length,message:`Length different: ${t.length} !== ${n.length}`},unique_fingerprint:{condition:t.unique_fingerprint!==n.unique_fingerprint,message:`Unique fingerprint different: ${t.unique_fingerprint} !== ${n.unique_fingerprint}`},duration:{condition:t.duration!==n.duration,message:`Duration different: ${t.duration} !== ${n.duration}`},card_required:{condition:t.card_required!==n.card_required,message:`Card required different: ${t.card_required} !== ${n.card_required}`},on_end:{condition:(t.on_end??"bill")!==(n.on_end??"bill"),message:`On end different: ${t.on_end??"bill"} !== ${n.on_end??"bill"}`}};return!Object.values(r).some(o=>o.condition)}},{prodOptionsAreSame:uA}={prodOptionsAreSame:({curProduct:t,newProduct:n})=>t.is_default===n.is_default&&t.is_add_on===n.is_add_on},{PurchaseLimitIntervalEnum:lA}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(Ae,OI),{entToItemInterval:Pg}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))(Wr),{billingToItemInterval:Cg}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(En),{isContUseFeature:Eg}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(Wn),{getBillingType:eu}=((e,t,n,r)=>({getBillingType:o=>{if(o.type===e.Fixed&&o.interval===t.OneOff)return n.OneOff;if(o.type===e.Fixed)return n.FixedCycle;let a=o;return a.bill_when===r.InAdvance||a.bill_when===r.StartOfPeriod?n.UsageInAdvance:a.bill_when===r.EndOfPeriod&&a.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(Qr,En,Zr,Yi),{isAllocatedPrice:Tg}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(eu,Zr),{priceToEnt:tu}=(e=>{function t({price:n,entitlements:r,errorOnNotFound:i}){let o=r.filter(s=>s.id===n.entitlement_id),a=o.find(s=>s.internal_product_id===n.internal_product_id)??o[0];if(!a&&i)throw new e({message:`Entitlement not found for price ${n.id}`});return a}return{priceToEnt:t}})(EI),{isBooleanFeatureItem:Rg}=((e,t)=>({isBooleanFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)&&t(r.interval)&&t(r.included_usage)}))(Xr,Jr),{constructBooleanFeature:dA}=((e,t,n)=>({constructBooleanFeature:({featureId:i,orgId:o,env:a,name:s})=>({internal_id:e("fe"),org_id:o,env:a,created_at:Date.now(),id:i,name:s||t(i),type:n.Boolean,config:null,archived:!1,event_names:[],model_markups:null})}))(Hr,cg,Pt),{constructMeteredFeature:pA}=((e,t,n,r)=>({constructMeteredFeature:({featureId:o,name:a,orgId:s,env:c,usageType:u,eventNames:l=[]})=>({internal_id:e("fe"),org_id:s,env:c,created_at:Date.now(),id:o,name:a||t(o),type:n.Metered,config:{filters:[{property:"event_name",operator:"eq",value:[]}],aggregate:{type:r.Sum,property:"value"},usage_type:u},archived:!1,event_names:l,model_markups:null})}))(Hr,cg,Pt,RI),{ApiFeatureV0Schema:mA}=((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,jI),{CURRENCY_CODES:fA}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(ug,NI,DI),{RolloverConfigSchema:gA}=((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,zc),{EntitlementExpirySchema:hA}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(Ae,FI),{CreditDimensionNameSchema:bA}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ae,UI,MI),{CreditDimensionBaseSchema:_A}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(Ae,pg),{graduatedCreditRateShape:kg}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(Ae,LI),{ProviderMarkupsSchema:yA}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ae,fg),{isAnyCreditSystem:SA}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(Pt,Wc),{findCreditTierViolations:xA}=(e=>({findCreditTierViolations:n=>{let r=[],i=(a,s)=>r.push({index:a,reason:s,message:e[s]}),o=0;for(let[a,s]of n.entries()){let c=a===n.length-1;if(s==="inf"){c||i(a,"non_final_infinity");continue}(!Number.isFinite(s)||s<=o)&&i(a,"not_increasing"),o=s,c&&i(a,"final_not_infinity")}return r}}))(VI),{findAmbiguousCreditDimensions:vA}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),o=[];for(let[a,[s,c]]of i.entries())for(let[u,l]of i.slice(a+1))e(c,l)&&t(c.match,l.match)&&o.push({names:[s,u],example:{...c.match,...l.match}});return o}}))($I,gg),{validateMultipliersKeepRatesNonNegative:IA}=((e,t)=>({validateMultipliersKeepRatesNonNegative:({schemaItem:r,invalidCreditSystem:i})=>{let o=Object.values(r.multipliers??{}),a=[r,...Object.values(r.dimensions??{})],s=Math.min(...a.map(e));t({multipliers:o,cheapestRate:s}).lt(0)&&i(`Multipliers on ${r.metered_feature_id} can take a rate below zero.`)}}))(zI,HI),{buildFixedPriceCurrencies:AA}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:o}of n)r[e(i)]={amount:o};return r}}))(hg),{PriceCurrencyConfigSchema:jg}=((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,Zc),{baseCurrenciesAreCompatible:wA}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:o})=>(n??null)===(r??null)||e(i)!==e(o)}))(JI),{tiersAreSame:Ng}=(e=>({tiersAreSame:(n,r)=>{if(n.length!==r.length)return!1;let i=e(n),o=e(r);return i.every((a,s)=>{let c=o[s];return a.amount===c?.amount&&a.flat_amount===c.flat_amount&&a.to===c.to})}}))(XI),{UsagePriceConfigSchema:OA}=((e,t,n,r,i,o)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(o).optional()})}))(Ae,Yi,Zc,En,jg,Qn),{toFeature:PA}=((e,t,n,r,i,o,a)=>({toFeature:({item:c,orgId:u,internalFeatureId:l,internalProductId:d,isCustom:p,newVersion:g,feature:f,curEnt:h})=>{let v=f?.type===e.Boolean,I=t({item:c,feature:f}),S={id:c.entitlement_id||h?.id||n("ent"),org_id:u,created_at:c.created_at||Date.now(),is_custom:p,internal_product_id:d||null,internal_feature_id:l,feature_id:c.feature_id,allowance:c.included_usage===r?null:c.included_usage,allowance_type:v?null:c.included_usage===r?i.Unlimited:i.Fixed,interval:v?null:o({item:c}),interval_count:a({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(p||g)&&(S={...S,id:n("ent"),created_at:Date.now()}),{price:null,ent:S}}}))(Pt,bg,Hr,Zi,Ia,Oa,Pa),{creditDimensionRulesEqual:CA}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(Yc),{markupRecordsAreSame:EA}=(e=>({markupRecordsAreSame:(n,r)=>[...new Set([...Object.keys(n??{}),...Object.keys(r??{})])].every(i=>e.every(o=>(n?.[i]?.[o]??null)===(r?.[i]?.[o]??null)))}))(o1),{itemToUsageType:TA}=((e,t,n)=>({itemToUsageType:({item:i,features:o})=>{let a=e({item:i,features:o});return!a||!a.config?null:a.type===t.Boolean?n.Static:a.type===t.CreditSystem?n.SingleUse:a.config.usage_type}}))(yg,Pt,Tn),{itemToUsageType:RA}=((e,t,n)=>({itemToUsageType:({item:i,features:o})=>{let a=e({item:i,features:o});return a?a.type==t.Boolean?n.Static:a.type==t.CreditSystem?n.SingleUse:a.config.usage_type:null}}))(u1,Pt,Tn),{isPreviewStripeId:kA}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(m1,f1),{findPairedEntitlement:jA}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(tu),{isConsumablePrice:NA}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(eu,Zr),{validateLicenseLink:EM}=((e,t,n)=>({validateLicenseLink:({parentProduct:i,licenseProduct:o,prepaidOnly:a,licensePlanId:s})=>{if(a!==void 0&&e({prepaidOnly:a}),s&&o.archived)throw new t({message:`License plan ${s} is archived and cannot be linked.`,code:n.InvalidRequest,statusCode:400});if(o.base_internal_product_id)throw new t({message:`A variant cannot be used as a plan license (${s??o.id}).`,code:n.InvalidRequest});if(i&&o.id===i.id)throw new t({message:`A plan cannot be linked as a license to itself (${s??o.id}).`,code:n.InvalidRequest,statusCode:400})}}))(S1,Ft,$t),{evaluateCatalogItemIdentity:DA}=(e=>({evaluateCatalogItemIdentity:({item:n,recipe:r=e})=>{let i=[];for(let o of r.components){let a;for(let c of o.paths){a=n;for(let u of c.split("."))a=a!==null&&typeof a=="object"?a[u]:void 0;if(a!=null)break}let s=o.defaultWhen&&i[o.defaultWhen.component]?o.defaultWhen.value:o.default;if(a!=null&&typeof a!="string"&&typeof a!="number")throw new Error("Catalog identity components must be strings or numbers");i.push(a??s)}return i}}))(v1),{removeItems:FA}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(o=>e({item:i,filter:o})))}))(A1),{toApiPlanItem:UA}=((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)})}))(O1,P1),{applyLicenses:MA}=(e=>({applyLicenses:({base:n,diff:r})=>{if(r.upsert_licenses===void 0&&r.remove_licenses===void 0)return;let i=new Set((r.remove_licenses??[]).map(s=>s.license_plan_id)),o=new Map((r.upsert_licenses??[]).map(s=>[s.license_plan_id,s])),a=[];for(let s of n.licenses??[]){if(i.has(s.license_plan_id))continue;let c=o.get(s.license_plan_id);if(c){a.push(e({existing:s,upsert:c})),o.delete(s.license_plan_id);continue}a.push(s)}for(let s of r.upsert_licenses??[])o.has(s.license_plan_id)&&a.push(e({upsert:s}));return a}}))(E1),{pricesEqual:Dg}=(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)}))(Jc),{itemPricesEqual:LA}=((e,t,n)=>({itemPricesEqual:(i,o)=>{if(i==null&&o==null)return!0;if(i==null||o==null)return!1;let a=i.tiers?.length?i.tier_behavior??e.Graduated:null,s=o.tiers?.length?o.tier_behavior??e.Graduated:null;return(i.amount??null)===(o.amount??null)&&t(i.additional_currencies,o.additional_currencies)&&n(i.tiers,o.tiers)&&a===s&&i.interval===o.interval&&(i.interval_count??1)===(o.interval_count??1)&&(i.billing_units??1)===(o.billing_units??1)&&i.billing_method===o.billing_method&&(i.max_purchase??null)===(o.max_purchase??null)}}))(Aa,Jc,R1),{featureOverridesEqual:BA}=((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??{})}))(N1,Yc),{freeTrialsEqual:qA}=(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")}))(U1),{planItemFiltersEqual:VA}=(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)}))(L1),{toUpsertLicense:$A}=(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}:{}})}))(xg),{getVariantSettingsPatch:TM}=((e,t)=>({getVariantSettingsPatch:({from:r,to:i})=>{let o={};for(let a of e)t(r[a],i[a])||(o[a]=i[a]);return o}}))(q1,V1),{isOneOffProductV2:RM}=((e,t,n,r)=>({isOneOffProductV2:({items:o})=>{let a=o.filter(s=>e(s)||t(s));return a.length>0&&a.every(s=>n({item:s})===r.OneOff)}}))(Ea,ni,Zn,En),{canonicalizeBillingControls:GA}=(e=>({canonicalizeBillingControls:n=>{let r=n??{},i={};for(let o of Object.keys(r)){let a=r[o];Array.isArray(a)&&a.length===0||(i[o]=Array.isArray(a)?[...a].sort((s,c)=>String(s?.feature_id??"").localeCompare(String(c?.feature_id??""))):a)}return JSON.stringify(e(i))}}))(vg),{ProductConfigSchema:KA}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(Ae,K1),{shouldApplyVariantUpdates:kM}=(e=>({shouldApplyVariantUpdates:({oldBase:n,latestBase:r,propagateToVariants:i,variantUpdates:o,updates:a})=>i.length>0||o.length>0||n.internal_id!==r.internal_id?!0:e.some(s=>a[s]!==void 0)}))(z1),{resolveLicenseParentTargets:jM}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:o,childPlanId:a})=>{let s=new Map(i.map(l=>[e({planId:l.parent.id,version:l.parent.version}),l])),c=new Set,u=[];for(let l of o){let d=e({planId:l.plan_id,version:l.version});if(c.has(d))throw new t({message:`Parent plan target ${d} was selected more than once.`,code:n.InvalidPropagationTarget,statusCode:400});let p=s.get(d);if(!p)throw new t({message:`Plan ${l.plan_id} v${l.version} does not offer ${a} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),u.push(p)}return u}}))(H1,Ft,$t),{stripeMinorUnitFactor:Ta}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(Ig,W1),{entIntervalsSame:zA}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),o=e(r.interval,r.intervalCount);return i.eq(o)}}))(Q1),{intervalsDifferent:HA}=((e,t)=>({intervalsDifferent:({intervalA:r,intervalB:i})=>{if(e(r)&&e(i))return!1;if(e(r)||e(i))return!0;let o=t(r.interval,r.intervalCount),a=t(i.interval,i.intervalCount);return o!==a}}))(Xt,Z1),{allocatedBillingBehaviorAreSame:WA}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),o=e(r);return i===o}}))(J1),{tiersAreSame:QA}=(e=>({tiersAreSame:(n,r)=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every((i,o)=>i.amount===r[o].amount&&i.to===r[o].to&&(i.flat_amount??null)===(r[o].flat_amount??null)&&e(i.additional_currencies,r[o].additional_currencies))}))(Xc),{itemToPriceOrTiers:ZA}=(e=>({itemToPriceOrTiers:({item:n,proration:r,now:i})=>{if(i=i||Date.now(),n.price)return{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.price}):n.price,tiers:void 0};if(n.tiers)return n.tiers.length>1?{price:void 0,tiers:n.tiers.map(o=>({...o,amount:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:o.amount}):o.amount}))}:{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.tiers[0].amount}):n.tiers[0].amount,tiers:void 0}}}))(tA),{normalizeBillingControls:YA}=((e,t,n)=>({normalizeBillingControls:i=>{let o=e(i);return JSON.stringify(t.flatMap(a=>{let s=o?.[a];return s?.length?[[a,n(s)]]:[]}))}}))(oA,va,aA),{AutoTopupPurchaseLimitSchema:JA}=((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,lA),{toFeatureItem:XA}=((e,t,n,r)=>({toFeatureItem:({ent:o})=>{if(o.feature.type===e.Boolean)return{feature_id:o.feature.id,entity_feature_id:o.entity_feature_id,entitlement_id:o.id};let a=o.rollover||o.feature_override?{rollover:o.rollover??void 0,feature_override:o.feature_override??void 0}:void 0;return{feature_id:o.feature.id,included_usage:o.allowance_type===t.Unlimited?n:o.allowance,interval:r({entInterval:o.interval}),interval_count:o.interval_count??1,entity_feature_id:o.entity_feature_id,pooled:o.pooled??!1,reset_usage_when_enabled:!o.carry_from_previous,config:a,entitlement_id:o.id,created_at:o.created_at}}}))(Pt,Ia,Zi,Pg),{toPriceItem:ew}=((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,PI),{isPayPerUsePrice:Fg}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(eu,Zr),{createFeaturesFromItems:tw}=((e,t,n,r,i,o,a,s,c,u)=>({createFeaturesFromItems:({items:d,curFeatures:p,orgId:g,env:f})=>{let h=[];for(let v of d){if(!v.feature_id)continue;let I=p.find(S=>S.id===v.feature_id);if(I){if(e(v.feature_type))continue;if(v.feature_type===t.Static){if(v.feature_type===t.Static&&I.type!==n.Boolean)throw new r({message:`Feature ${v.feature_id} already exists but is not a static feature`,code:i.InvalidRequest,statusCode:400})}else if(v.feature_type!==I.config?.usage_type)throw new r({message:`Feature ${v.feature_id} already exists but is not a ${v.feature_type} feature`,code:i.InvalidRequest,statusCode:400});continue}if(o(v.feature_id),a(v)){let S=s({featureId:v.feature_id,orgId:g,env:f});h.push(S)}else{if(!v.feature_type)throw new r({message:`Feature type is required for ${v.feature_id}. Either 'continuous_use' or 'single_use'`,code:i.InvalidRequest,statusCode:400});let S=c({featureId:v.feature_id,orgId:g,env:f,usageType:v.feature_type===t.ContinuousUse?u.Continuous:u.Single});h.push(S)}}return{allFeatures:[...p,...h],newFeatures:h}}}))(Jr,Tn,Pt,Ft,$t,TI,Rg,dA,pA,Wn),{SUPPORTED_SET:nw}=(e=>({SUPPORTED_SET:new Set(e)}))(fA),{CreditDimensionSchema:rw}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(Ae,_A,mg,kg),{FeatureMarkupsOverrideSchema:iw}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(Ae,yA,qI),{validateCreditRate:Ug}=(e=>({validateCreditRate:({rate:n,invalidCreditSystem:r})=>{if(n.tier_behavior==="graduated"){(!Array.isArray(n.tiers)||n.tiers.length===0)&&r("Graduated credit schemas require at least one tier.");let o=n.tiers??[];for(let s of o){let c=Number(s.credit_amount);(!Number.isFinite(c)||c<0)&&r("Tier credit costs must be zero or greater."),s.credit_amount=c,s.to!=="inf"&&(s.to=Number(s.to))}let[a]=e(o.map(s=>s.to));a&&r(a.message);return}let i=Number(n.credit_amount);(!Number.isFinite(i)||i<0)&&r("Credit cost must be zero or greater."),n.credit_amount=i}}))(xA),{validateDimensionsAreSeparable:ow}=((e,t)=>({validateDimensionsAreSeparable:({dimensions:r,invalidCreditSystem:i})=>{let[o]=e(r);if(!o)return;let[a,s]=o.names;i(`Dimensions "${a}" and "${s}" can both match the same event (${t(o.example)}). Give one more match keys or a priority.`)}}))(vA,GI),{validateCreditMultipliers:aw}=((e,t)=>({validateCreditMultipliers:({schemaItem:r,invalidCreditSystem:i})=>{for(let[o,a]of Object.entries(r.multipliers??{}))e({name:o,multiplier:a,invalidCreditSystem:i});t({schemaItem:r,invalidCreditSystem:i})}}))(KI,IA),{FixedPriceConfigSchema:sw}=((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,En,jg,Zc,YI),{currenciesAreCompatible:cw}=(e=>({currenciesAreCompatible:(n,r)=>{let i=n??{},o=r??{};for(let a of Object.keys(i)){let s=o[a];if(!s)continue;let c=i[a];if((c?.amount??null)!==(s.amount??null)||!e(c?.usage_tiers??[],s.usage_tiers??[]))return!1}return!0}}))(Ng),{creditSchemaItemsAreSame:uw}=(e=>({creditSchemaItemsAreSame:({left:n,right:r})=>(n.feature_amount??1)==(r.feature_amount??1)&&e({left:n,right:r})&&n.credit_amount==r.credit_amount&&(n.tier_behavior??null)===(r.tier_behavior??null)&&(n.tiers??[]).length===(r.tiers??[]).length&&(n.tiers??[]).every((i,o)=>i.to===r.tiers?.[o]?.to&&i.credit_amount==r.tiers?.[o]?.credit_amount)}))(CA),{markupOverridesAreSame:lw}=(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)}))(EA),{resolveAllocatedBillingBehavior:dw}=((e,t,n,r)=>({resolveAllocatedBillingBehavior:({item:o,curPrice:a})=>{if(e(o.config?.allocated_billing_behavior))return o.config.allocated_billing_behavior;if(e(o.config?.on_increase)||e(o.config?.on_decrease))return t.Prorated;if(a&&n({price:a})){let c=a.config;return e(c.allocated_billing_behavior)?c.allocated_billing_behavior:r(a)?t.Prorated:t.Arrear}return t.Arrear}}))(_r,Qn,Fg,Tg),{itemCanBeProrated:pw}=((e,t,n)=>({itemCanBeProrated:({item:i,features:o})=>{let a=e({item:i,features:o});return a===t.SingleUse&&i.usage_model===n.Prepaid?!0:a===t.ContinuousUse}}))(RA,Tn,Yr),{priceHasPreviewStripeId:mw}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(o=>t({stripeId:i[o]}))}}))(p1,kA),{buildPlanItemKey:fw}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let o=t({item:r});return i===e.FeatureCadence&&o.splice(1,1),o.join("|")}}))(x1,DA),{itemsEqual:Mg}=((e,t,n,r)=>({itemsEqual:(o,a)=>o.feature_id===a.feature_id&&(o.entity_feature_id??null)===(a.entity_feature_id??null)&&(o.pooled??!1)===(a.pooled??!1)&&(o.included??0)===(a.included??0)&&(o.unlimited??!1)===(a.unlimited??!1)&&(o.reset?.interval??null)===(a.reset?.interval??null)&&(o.reset?.interval_count??1)===(a.reset?.interval_count??1)&&e(o.price,a.price)&&t(o.rollover,a.rollover)&&n(o.proration,a.proration)&&r(o.feature_override,a.feature_override)}))(LA,k1,j1,BA),{licenseCustomizesAreSame:gw}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:o,right:a})=>{let s=o??{},c=a??{},u={price:!e(s.price,c.price),addItems:!t({left:s.add_items,right:c.add_items,equals:n}),removeItems:!t({left:s.remove_items,right:c.remove_items,equals:r})};return!Object.values(u).some(Boolean)}}))(Dg,M1,Mg,VA),{normalizeVariantSettingValue:hw}=((e,t,n)=>({normalizeVariantSettingValue:({field:i,value:o})=>{if(i==="group")return o||"";if(i==="description")return o||null;if(i==="billing_controls")return e(o);if(i==="config"){let a=t.safeParse(o??{});return JSON.stringify(n(a.success?a.data:o??{}))}return i==="metadata"?JSON.stringify(n(o??{})):o}}))(GA,KA,vg),{intervalsSame:bw}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(HA),{sanitizeItems:_w}=((e,t,n,r)=>({sanitizeItems:({items:o,features:a})=>o.map(s=>{let c=s.tiers?.length===1&&s.tiers[0].additional_currencies?.length?{price:void 0,tiers:s.tiers}:e({item:s}),u={...s,reset_usage_when_enabled:t({item:s,feature:a.find(l=>l.id===s.feature_id)}),...c};return u.config||(u.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),u})}))(ZA,nA,ei,Ji),{compareBillingControls:yw}=(e=>({compareBillingControls:({newBillingControls:n,curBillingControls:r})=>e(n)===e(r)}))(YA),{AutoTopupSchema:Sw}=((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,JA),{toFeaturePriceItem:xw}=((e,t,n,r,i,o,a,s,c,u,l)=>({toFeaturePriceItem:({ent:p,price:g})=>{let f=g.config,h=e(f.currencies,f.usage_tiers.length),v=f.usage_tiers.map((R,D)=>({amount:R.amount,to:R.to===-1?t:R.to,flat_amount:R.flat_amount,...h?.[D]?.length?{additional_currencies:h[D]}:{}})),I={};return g.proration_config&&(I={...g.proration_config}),n({feature:p.feature})&&r({price:g})&&(I.allocated_billing_behavior=f.allocated_billing_behavior??(i(g)?o.Prorated:o.Arrear)),p.rollover&&(I.rollover=p.rollover),p.expiry_duration&&p.expiry_length!=null&&(I.expiry={duration:p.expiry_duration,length:p.expiry_length}),p.feature_override&&(I.feature_override=p.feature_override),f.threshold_billing&&(I.threshold_billing=f.threshold_billing),{feature_id:p.feature.id,feature_type:p.feature.config?.usage_type||a.SingleUse,included_usage:p.allowance,interval:s({entInterval:p.interval}),interval_count:p.interval_count??1,price_interval:c({billingInterval:f.interval}),price_interval_count:f.interval_count??1,price:null,tiers:v,base_currency:f.base_currency??void 0,billing_units:f.billing_units,tier_behavior:g.tier_behavior??null,entity_feature_id:p.entity_feature_id,pooled:p.pooled??!1,reset_usage_when_enabled:!p.carry_from_previous,usage_model:f.bill_when===u.StartOfPeriod||f.bill_when===u.InAdvance?l.Prepaid:l.PayPerUse,created_at:p.created_at,entitlement_id:p.id,price_id:g.id,price_config:g.config,config:Object.keys(I).length>0?I:void 0,usage_limit:p.usage_limit}}}))(CI,Gc,Eg,Fg,Tg,Qn,Tn,Pg,Cg,Yi,Yr),{isValidCurrencyCode:nu}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(nw),{CreditSchemaItemBaseSchema:Lg}=((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,bA,rw,BI),{GraduatedCreditSchemaItemSchema:vw}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(Lg,kg),{validateCreditDimensionRules:Iw}=((e,t,n)=>({validateCreditDimensionRules:({schemaItem:i,invalidCreditSystem:o})=>{let a=i.dimensions??{};for(let[s,c]of Object.entries(a))c.priority!==void 0&&!Number.isInteger(c.priority)&&o(`Dimension "${s}" priority must be an integer.`),e({rate:c,invalidCreditSystem:o});t({dimensions:a,invalidCreditSystem:o}),n({schemaItem:i,invalidCreditSystem:o})}}))(Ug,ow,aw),{pricesAreSame:Ra}=((e,t,n,r,i,o,a,s)=>({pricesAreSame:(u,l,d=!1)=>{let p=u.config,g=l.config;if(p.type!==g.type)return!1;if(p.type===e.Fixed){let D=t.parse(p),P=t.parse(g),be={amount:D.amount!==P.amount,interval:D.interval!==P.interval,intervalCount:(D.interval_count??1)!==(P.interval_count??1),baseCurrency:!n({base1:D.base_currency,base2:P.base_currency,currencies1:D.currencies,currencies2:P.currencies}),currencies:!r(D.currencies,P.currencies)};return!Object.values(be).some(Boolean)}let f=i.parse(p),h=i.parse(g),v={shouldProrate:(f.should_prorate??!1)!==(h.should_prorate??!1),allocatedBillingBehavior:o(f)!==o(h),billWhen:f.bill_when!==h.bill_when,billingUnits:(f.billing_units??1)!==(h.billing_units??1),thresholdBilling:f.threshold_billing?.threshold!==h.threshold_billing?.threshold,interval:f.interval!==h.interval,intervalCount:(f.interval_count??1)!==(h.interval_count??1),internalFeatureId:f.internal_feature_id!==h.internal_feature_id,featureId:f.feature_id!==h.feature_id,usageTiers:!a(f.usage_tiers,h.usage_tiers),baseCurrency:!n({base1:f.base_currency,base2:h.base_currency,currencies1:f.currencies,currencies2:h.currencies}),currencies:!r(f.currencies,h.currencies)},I=f.usage_tiers.length<=1&&h.usage_tiers.length<=1,S={onIncrease:u.proration_config?.on_increase!=l.proration_config?.on_increase,onDecrease:u.proration_config?.on_decrease!=l.proration_config?.on_decrease,tierBehavior:!I&&(u.tier_behavior??s.Graduated)!==(l.tier_behavior??s.Graduated)},R=Object.values(v).some(Boolean)||Object.values(S).some(Boolean);return R&&d&&console.log("Prices are different",{configDiffs:v,prorationDiffs:S}),!R}}))(Qr,sw,wA,cw,OA,e1,Ng,Aa),{creditSchemasAreSame:Aw}=(e=>({creditSchemasAreSame:({schema1:n,schema2:r})=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every(i=>{let o=r.find(a=>a.metered_feature_id===i.metered_feature_id);return o?e({left:i,right:o}):!1})}))(uw),{itemToAllocatedBillingBehavior:ww}=((e,t,n,r,i,o,a,s,c)=>({itemToAllocatedBillingBehavior:({item:l,features:d,curPrice:p})=>{if(!(e({item:l,features:d})===t.ContinuousUse&&n(l)&&l.usage_model!==r.Prepaid))return null;let h=i({item:l,curPrice:p});if(h===o.Arrear){if(a(l.config?.on_increase)||a(l.config?.on_decrease))throw new s({message:`on_increase / on_decrease are not supported for allocated arrear billing (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400});if(a(l.config?.rollover))throw new s({message:`rollover is not supported for allocated arrear billing because the balance never resets (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400})}return h}}))(TA,Tn,ni,Yr,dw,Qn,_r,Ft,s1),{composeMatchKey:Xi}=(e=>({composeMatchKey:n=>e({item:n})}))(fw),{applyItems:Ow}=((e,t,n,r)=>({applyItems:(o,a)=>{let s=[...o];if(a.remove_items&&(s=e(s,a.remove_items)),a.add_items){let c=new Set;for(let u of s)t(u)&&c.add(n(u));for(let u of a.add_items){let l=n(u);t(u)&&c.has(l)||(s.push(r(u)),t(u)&&c.add(l))}}return s}}))(FA,w1,Xi,UA),{dedupeItemsByMatchKey:Pw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Xi),{planLicensesAreSame:Cw}=(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)}}))(gw),{dedupeItemsByMatchKey:Ew}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let o=e(i);return r.has(o)?!1:(r.add(o),!0)})}}))(Xi),{validateVariantSettingsUpdate:NM}=((e,t,n,r)=>({validateVariantSettingsUpdate:({allowVariantSettingsUpdate:o,fullProduct:a,currentProduct:s,updates:c})=>{if(o||a.base_internal_product_id==null)return;let u=e.find(l=>c[l]===void 0?!1:t({field:l,value:c[l]})!==t({field:l,value:s[l]}));if(u)throw new n({message:`Cannot update ${u} directly on a variant plan.`,code:r.InvalidPropagationTarget,statusCode:400})}}))(G1,hw,Ft,$t),{findSimilarItem:ru}=((e,t,n,r,i,o,a,s,c)=>({findSimilarItem:({item:l,items:d})=>e(l)?d.find(p=>e(p)&&p.feature_id===l.feature_id&&p.entity_feature_id==l.entity_feature_id&&t({intervalA:{interval:n({item:p}),intervalCount:r({item:p})},intervalB:{interval:n({item:l}),intervalCount:r({item:l})}})):i(l)?d.find(p=>i(p)&&p.feature_id===l.feature_id&&p.entity_feature_id==l.entity_feature_id&&o({intervalA:{interval:a({item:p}),intervalCount:s({item:p})},intervalB:{interval:a({item:l}),intervalCount:s({item:l})}})&&l.usage_model==p.usage_model):c(l)?d.find(p=>c(p)&&p.price==l.price&&a({item:p})==a({item:l})&&s({item:p})==s({item:l})):null}))(Ca,zA,Oa,Pa,ni,bw,Zn,ti,Ea),{stripAutoTopupCountsForStorage:Tw}=(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}))}))(Sw),{toProductItem:Bg}=((e,t,n,r)=>({toProductItem:({ent:o,price:a})=>e(a)?t({ent:o}):e(o)?n({price:a}):r({ent:o,price:a})}))(Xt,XA,ew,xw),{CurrencyCodeSchema:qg}=((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,nu),{AdditionalCurrencyPriceSchema:Rw}=((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,qg),{FlatCreditSchemaItemSchema:kw}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(Lg,mg),{validateCreditSystem:jw}=((e,t,n,r,i,o,a,s)=>({validateCreditSystem:(u,l=e.CreditSystem)=>{let d=Array.isArray(u?.schema)?u.schema:[],p=S=>{throw new t({message:S,code:n.InvalidFeature,statusCode:r.BAD_REQUEST})};!i(l)&&d.length===0&&p("At least one metered feature is required for credit system"),i(l)&&d.length>0&&p("AI credit systems are leaf features and cannot define a schema. Model rates live in model_markups.");let g=d.map(S=>S.metered_feature_id),f=Array.from(new Set(g));g.length!==f.length&&p("Credit system contains multiple of the same metered_feature_id");let h={...u,schema:d,usage_type:o.Single},v=h.default_markup;if(v!=null){let S=Number(v);if(Number.isNaN(S)||S<-100)throw new t({message:"Default markup must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});h.default_markup=S}let I=h.provider_markups;if(I!=null)for(let[S,R]of Object.entries(I)){let D=Number(R?.markup);if(!S||Number.isNaN(D)||D<-100)throw new t({message:"Provider markups must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});R.markup=D}for(let S of h.schema){if(S.feature_amount!==void 0){let R=Number(S.feature_amount);(!Number.isFinite(R)||R<=0)&&p("Billing units must be greater than zero."),S.feature_amount=R}a({rate:S,invalidCreditSystem:p}),s({schemaItem:S,invalidCreditSystem:p})}return h}}))(Pt,Ft,$t,Hn,Wc,Wn,Ug,Iw),{stripePriceIdForInitializedPrice:Vg}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:o,newPrice:a})=>{if(!e(i)&&(!o||i!==t({price:o})||n(o,a)))return i}}))(Xt,ZI,Ra),{featureOverridesAreSame:iu}=((e,t)=>({featureOverridesAreSame:({override1:r,override2:i})=>e({schema1:r?.schema,schema2:i?.schema})&&t({markups1:r?.markups,markups2:i?.markups})}))(Aw,lw),{applyDiff:$g}=((e,t,n,r)=>({applyDiff:({base:o,diff:a})=>{let s={price:e(o.price,a.price),items:t(o.items,a),free_trial:n(o.free_trial,a.free_trial)},c=r({base:o,diff:a});return c===void 0?s:{...s,licenses:c}}}))(I1,Ow,C1,MA),{diffPlanLicenses:Nw}=((e,t,n,r)=>({diffPlanLicenses:({from:o,to:a,includeAdds:s=!1,includeRemoves:c=!1})=>{let u=new Map((o??[]).map(g=>[g.license_plan_id,g])),l=new Map((a??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of l.values()){let f=u.get(g.license_plan_id);!f&&!s||f&&e({left:f,right:g})||d.push(t({license:g,clearCustomize:f!=null&&n(f.customize)&&!n(g.customize)}))}let p=c?[...u.keys()].filter(g=>!l.has(g)).map(g=>({license_plan_id:g})):[];return{...d.length>0?{upsert_licenses:d.sort(r)}:{},...p.length>0?{remove_licenses:p.sort(r)}:{}}}}))(Cw,$A,xg,B1),{applyDiffToVariantPlan:DM}=((e,t)=>({applyDiffToVariantPlan:({plan:r,diff:i,settingsPatch:o={}})=>{let a=e({base:r,diff:i});return{...r,...a,...o,items:t(a.items)}}}))($g,Ew),{mapToProductItems:Gg}=((e,t,n,r)=>({mapToProductItems:({prices:o,entitlements:a,features:s})=>{let c=[];o??=[],a??=[];for(let u of a){let l=e({ent:u,prices:o}),d=t({ent:u,price:l});c.push(d)}for(let u of o)n({price:u,entitlements:a})||c.push(t({price:u}));for(let u of c)s.find(d=>d.id===u.feature_id)&&(u.feature_type=r({item:u,features:s}));return c}}))(og,Bg,tu,ag),{featureItemsAreSame:Dw}=((e,t,n)=>({featureItemsAreSame:({item1:i,item2:o,logDifferences:a=!1})=>{let s={feature_id:{condition:i.feature_id===o.feature_id,message:`Feature ID different: ${i.feature_id} != ${o.feature_id}`},included_usage:{condition:e(i.included_usage)==e(o.included_usage),message:`Included usage different: ${i.included_usage} != ${o.included_usage}`},interval:{condition:i.interval==o.interval,message:`Interval different: ${i.interval} != ${o.interval}`},interval_count:{condition:(i.interval_count||1)==(o.interval_count||1),message:`Interval count different: ${i.interval_count} != ${o.interval_count}`},entity_feature_id:{condition:i.entity_feature_id==o.entity_feature_id,message:`Entity feature ID different: ${i.entity_feature_id} != ${o.entity_feature_id}`},pooled:{condition:(i.pooled??!1)===(o.pooled??!1),message:`Pooled different: ${i.pooled} != ${o.pooled}`},reset_usage_when_enabled:{condition:(i.reset_usage_when_enabled??!1)===(o.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${i.reset_usage_when_enabled} !== ${o.reset_usage_when_enabled}`},rollover_config:{condition:t({rollover1:i.config?.rollover||void 0,rollover2:o.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(i.config?.rollover)} !== ${JSON.stringify(o.config?.rollover)}`},feature_override:{condition:n({override1:i.config?.feature_override,override2:o.config?.feature_override}),message:`Feature override different: ${JSON.stringify(i.config?.feature_override)} !== ${JSON.stringify(o.config?.feature_override)}`},threshold_billing:{condition:(i.config?.threshold_billing?.threshold??null)===(o.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(i.config?.threshold_billing)} !== ${JSON.stringify(o.config?.threshold_billing)}`}},c=Object.values(s).every(u=>u.condition);return!c&&a&&console.log("Feature items different:",Object.values(s).filter(u=>!u.condition).map(u=>u.message)),c}}))(wg,Og,iu),{featurePriceItemsAreSame:Fw}=((e,t,n,r,i,o,a,s,c,u)=>({featurePriceItemsAreSame:({item1:d,item2:p,logDifferences:g=!1})=>{let f={included_usage:{condition:e(d.included_usage)==e(p.included_usage),message:`Included usage different: ${d.included_usage} != ${p.included_usage}`},usage_limit:{condition:d.usage_limit==p.usage_limit,message:`Usage limit different: ${d.usage_limit} !== ${p.usage_limit}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`},proration_config:{condition:t({config1:d.config||void 0,config2:p.config||void 0}),message:`Proration config different: ${JSON.stringify(d.config)} !== ${JSON.stringify(p.config)}`},allocated_billing_behavior:{condition:n({item1:d,item2:p}),message:`Allocated billing behavior different: ${d.config?.allocated_billing_behavior} !== ${p.config?.allocated_billing_behavior}`},rollover_config:{condition:r({rollover1:d.config?.rollover||void 0,rollover2:p.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(d.config?.rollover)} !== ${JSON.stringify(p.config?.rollover)}`},feature_override:{condition:i({override1:d.config?.feature_override,override2:p.config?.feature_override}),message:`Feature override different: ${JSON.stringify(d.config?.feature_override)} !== ${JSON.stringify(p.config?.feature_override)}`},threshold_billing:{condition:(d.config?.threshold_billing?.threshold??null)===(p.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(d.config?.threshold_billing)} !== ${JSON.stringify(p.config?.threshold_billing)}`},entity_feature_id:{condition:d.entity_feature_id==p.entity_feature_id,message:`Entity feature ID different: ${d.entity_feature_id} != ${p.entity_feature_id}`},pooled:{condition:(d.pooled??!1)===(p.pooled??!1),message:`Pooled different: ${d.pooled} != ${p.pooled}`}},h={feature_id:{condition:d.feature_id===p.feature_id,message:`Feature ID different: ${d.feature_id} != ${p.feature_id}`},interval:{condition:o({item:d})==o({item:p}),message:`Billing interval different: ${o({item:d})} != ${o({item:p})}`},interval_count:{condition:a({item:d})==a({item:p}),message:`Billing interval count different: ${a({item:d})} != ${a({item:p})}`},usage_model:{condition:d.usage_model===p.usage_model,message:`Usage model different: ${d.usage_model} != ${p.usage_model}`},pricing:{condition:s(c(d),c(p)),message:`Pricing different: ${JSON.stringify(c(d))} != ${JSON.stringify(c(p))}`},additional_currencies:{condition:u(d.additional_currencies,p.additional_currencies),message:"Additional currencies different"},tier_behavior:{condition:(c(d)?.length??0)<=1&&(c(p)?.length??0)<=1?!0:d.tier_behavior==p.tier_behavior,message:`Tiers type different: ${d.tier_behavior} != ${p.tier_behavior}`},billing_units:{condition:d.billing_units==p.billing_units,message:`Billing units different: ${d.billing_units} !== ${p.billing_units}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`}},v=Object.values(h).every(S=>S.condition)&&Object.values(f).every(S=>S.condition),I=Object.values(h).some(S=>!S.condition);return!v&&g&&console.log("Feature price items different:",Object.values(f).filter(S=>!S.condition).map(S=>S.message),Object.values(h).filter(S=>!S.condition).map(S=>S.message)),{same:v,pricesChanged:I}}}))(wg,Y1,WA,Og,iu,Zn,ti,QA,X1,Xc),{pickBillingControlColumns:Uw}=((e,t)=>({pickBillingControlColumns:r=>{if(!r)return{};let i=Object.fromEntries(e.flatMap(o=>r[o]===void 0?[]:[[o,r[o]]]));return i.auto_topups!==void 0&&(i.auto_topups=t(i.auto_topups)),i}}))(va,Tw),{mapToProductV2:FM}=((e,t,n,r,i)=>({mapToProductV2:({product:a,features:s})=>{let c=[];for(let l of a.entitlements){let d=e({ent:l,prices:a.prices});c.push(t({ent:l,price:d}))}for(let l of a.prices)n({price:l,entitlements:a.entitlements})||c.push(t({price:l}));s||(s=a.entitlements.map(l=>l.feature));for(let l of c)l.feature_type=r({item:l,features:s});return{internal_id:a.internal_id,id:a.id,name:a.name,description:a.description??null,is_add_on:a.is_add_on,is_default:a.is_default,version:a.version,version_slug:a.version_slug??null,active:a.active??!1,group:a.group||null,free_trial:a.free_trial,created_at:a.created_at,env:a.env,items:c,stripe_id:a.processor?.id||null,archived:a.archived||!1,config:a.config??void 0,billing_controls:i(a),metadata:a.metadata??{}}}}))(og,Bg,tu,ag,sg),{AdditionalCurrencyTierSchema:Mw}=((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,qg),{AdditionalCurrencyPriceArraySchema:Lw}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ae,Rw,lg,dg),{CreditSchemaItemSchema:Bw}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(Ae,kw,vw),{validateItemFeatureOverride:qw}=((e,t,n,r,i,o,a,s,c)=>({validateItemFeatureOverride:({item:l,feature:d,features:p})=>{let g=l.config?.feature_override;if(!g)return;let f=v=>{throw new e({message:`${v} (feature: ${l.feature_id})`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})};if(!(d&&r(d.type))){f("feature_override is only supported on credit system items");return}if(g.schema&&d.type!==i.CreditSystem&&f("feature_override.credit_schema is not supported on AI credit system items"),g.markups&&!o(d.type)&&f("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let h={schema:g.schema,usage_type:a.Single};s(h,d.type),c({config:h,allFeatures:p});for(let v of g.schema)if(!p.find(S=>S.id===v.metered_feature_id))throw new e({message:`feature_override on ${d.id} references unknown feature ${v.metered_feature_id}`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})}}))(Ft,$t,Hn,SA,Pt,Wc,Wn,jw,WI),{toPrice:Vw}=((e,t,n,r,i,o,a)=>({toPrice:({item:c,orgId:u,internalProductId:l,isCustom:d,newVersion:p,curPrice:g})=>{let f={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&&(f.currencies=h);let v=c.base_currency??(h?g?.config?.base_currency:void 0);v&&(f.base_currency=v);let I={id:c.price_id||g?.id||o("pr"),created_at:c.created_at||Date.now(),org_id:u,internal_product_id:l,is_custom:d,config:f,proration_config:null};return(d||p)&&(I={...I,id:o("pr"),created_at:Date.now()}),f.stripe_price_id=a({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:I}),{price:I,ent:null}}}))(Qr,Xr,Zn,ti,AA,Hr,Vg),{entsAreSame:ou}=((e,t,n,r,i,o,a)=>({entsAreSame:(c,u)=>{if(c.internal_feature_id!==u.internal_feature_id||e(c)!==e(u))return!1;let l=e(c),d={interval:t(c)!==t(u),intervalCount:n(c)!==n(u),allowance:!l&&c.allowance!=u.allowance,carryFromPrevious:(c.carry_from_previous??!1)!==(u.carry_from_previous??!1),entityFeatureId:r(c.entity_feature_id)!==r(u.entity_feature_id),pooled:(c.pooled??!1)!==(u.pooled??!1),usageLimit:c.usage_limit!=u.usage_limit,rollover:!i({rollover1:c.rollover,rollover2:u.rollover}),featureOverride:!o({override1:c.feature_override,override2:u.feature_override}),expiry:!a(c,u)};return!Object.values(d).some(Boolean)}}))(t1,_g,n1,r1,i1,iu,a1),{toFeatureAndPrice:$w}=((e,t,n,r,i,o,a,s,c,u,l,d,p,g,f,h,v,I,S,R,D,P,be,nt,Qe,je,ue,$)=>({toFeatureAndPrice:({item:Q,orgId:pt,internalFeatureId:me,internalProductId:ce,isCustom:Gt,curPrice:Ze,curEnt:Kt,newVersion:Rn,features:en})=>{let Hg=e({item:Q,feature:en.find(Tt=>Tt.id===Q.feature_id)}),ka=t({item:Q,features:en,curPrice:Ze}),uu=ka===n.Arrear,yr={id:Q.entitlement_id||Kt?.id||r("ent"),org_id:pt,created_at:Q.created_at||Date.now(),is_custom:Gt,internal_product_id:ce,internal_feature_id:me,feature_id:Q.feature_id,allowance:Q.included_usage||0,allowance_type:i.Fixed,interval:o({item:Q}),interval_count:a({item:Q}),carry_from_previous:!Hg,entity_feature_id:Q.entity_feature_id,pooled:Q.pooled??!1,usage_limit:Q.usage_limit||null,rollover:Q.config?.rollover,expiry_duration:Q.config?.expiry?.duration,expiry_length:Q.config?.expiry?.length,feature_override:Q.config?.feature_override};(!Kt||Gt&&!s(Kt,yr)||Rn)&&(yr={...yr,id:r("ent"),created_at:Date.now()});let Wg=o({item:Q}),ri={type:c.Usage,bill_when:Q.usage_model===u.Prepaid?l.StartOfPeriod:l.EndOfPeriod,billing_units:Q.billing_units||1,...Q.config?.threshold_billing?{threshold_billing:Q.config.threshold_billing}:{},should_prorate:Wg===d.Lifetime&&!uu,...ka?{allocated_billing_behavior:ka}:{},internal_feature_id:me,feature_id:Q.feature_id,usage_tiers:p(Q.price)?[{amount:Q.price,to:g}]:Q.tiers?.map(Tt=>({to:Tt.to,amount:Tt.amount??0,...Tt.flat_amount!=null?{flat_amount:Tt.flat_amount}:{}})),interval:f({item:Q}),interval_count:h({item:Q}),stripe_price_id:void 0},lu=v({baseTiers:ri.usage_tiers,itemTiers:Q.tiers,flatCurrencies:Q.additional_currencies});lu&&(ri.currencies=lu,ri.base_currency=Q.base_currency??Ze?.config?.base_currency??void 0);let Qg=I({item:Q,features:en})&&!uu,du=null;if(Qg){let Tt=Q.config?.on_increase||S.ProrateImmediately,Yn=Q.config?.on_decrease||R.Prorate;(D(Yn)||Yn===R.Prorate)&&(Yn=Tt===S.ProrateImmediately||Tt===S.BillImmediately?R.ProrateImmediately:R.ProrateNextCycle),du={on_increase:Tt,on_decrease:Yn}}let vn={id:Q.price_id||Ze?.id||r("pr"),created_at:Q.created_at||Date.now(),org_id:pt,internal_product_id:ce,is_custom:Gt,config:ri,entitlement_id:yr.id,proration_config:du,tier_behavior:Q.tier_behavior??null},pu=P(vn.config);if((pu===be.UsageInArrear||pu===be.InArrearProrated)&&vn.config.interval===nt.OneOff)throw new Qe({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${Q.feature_id})`,code:je.InvalidPrice,statusCode:400});let Zg=Ze&&!ue(Ze,vn,!0)||Kt&&!s(Kt,yr);if(Ze&&(Zg||Rn)){let Tt=vn.config,Yn=Ze.config;Tt.stripe_meter_id=Yn.stripe_meter_id,Tt.stripe_product_id=Yn.stripe_product_id,vn.config=Tt}return(Gt||Rn)&&(vn={...vn,id:r("pr"),created_at:Date.now()}),ri.stripe_price_id=$({requestedStripePriceId:Q.stripe_price_id,currentPrice:Ze,newPrice:vn}),{price:vn,ent:yr}}}))(bg,ww,Qn,Hr,Ia,Oa,Pa,ou,Qr,Yr,Yi,Wr,Xr,Gc,Zn,ti,c1,pw,ei,Ji,l1,d1,Zr,En,Ft,$t,Ra,Vg),{getPriceStripeReuseLevel:Gw}=((e,t,n,r,i,o)=>({getPriceStripeReuseLevel:({newPrice:s,candidatePrice:c,newEntitlements:u,candidateEntitlements:l})=>{if(e({price:c})||s.config?.type!==c.config?.type)return"none";if(t(c,s,!1)){if(s.config?.type!==n.Usage)return"full";let h=r({price:s,entitlements:u}),v=r({price:c,entitlements:l});if(!h&&!v)return"full";if(!h||!v)return"none";if(i(v,h))return"full"}if(s.config?.type!==n.Usage)return"none";let d=s.config,p=c.config;if(d.feature_id!==p.feature_id)return"none";let g=r({price:s,entitlements:u}),f=r({price:c,entitlements:l});return!g&&!f?"stripeProductOnly":!g||!f||o(g.entity_feature_id)!==o(f.entity_feature_id)?"none":"stripeProductOnly"}}))(mw,Ra,Qr,jA,ou,g1),{applyLicenseCustomizeToBasePlan:UM}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:o})=>{let a=new Set((o.add_items??[]).map(u=>e(u))),s={...i,items:i.items.filter(u=>!a.has(e(u)))},c=t({base:s,diff:o});return{...s,...c,items:n(c.items)}}}))(Xi,$g,Pw),{diffPlanV1:Kw}=((e,t,n,r,i,o,a,s,c)=>({diffPlanV1:({from:l,to:d,includeAdds:p=!1,includeRemoves:g=!1,filterPrecision:f=e.Identity})=>{let h={};t(l.price,d.price)||(h.price=d.price===null?null:n(d.price));let v=new Map(l.items.map(D=>[r(D),D])),I=new Map(d.items.map(D=>[r(D),D])),S=[];for(let D of d.items){let P=v.get(r(D));(!P||!i(P,D))&&S.push(o(D))}S.length>0&&(h.add_items=S);let R=[];for(let D of l.items){let P=I.get(r(D));(!P||!i(D,P))&&R.push(a({item:D,filterPrecision:f}))}if(R.length>0&&(h.remove_items=R),!s(l.free_trial,d.free_trial))if(d.free_trial==null)h.free_trial=null;else{let{on_end:D,...P}=d.free_trial;h.free_trial=D==null?P:{...P,on_end:D}}return Object.assign(h,c({from:l.licenses,to:d.licenses,includeAdds:p,includeRemoves:g})),h}}))(Sg,Dg,T1,Xi,Mg,D1,F1,qA,Nw),{currentItemsOf:Kg}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))(Gg),{itemsAreSame:zg}=((e,t,n,r,i,o,a,s)=>({itemsAreSame:({item1:u,item2:l,features:d,logDifferences:p=!1})=>{let g=!1,f=!1;if(e(u)){if(!e(l))return{same:!1,pricesChanged:!0};g=t({item1:u,item2:l,logDifferences:p}),f=!1}if(n(u)){if(!n(l))return{same:!1,pricesChanged:!0};let{same:h,pricesChanged:v}=r({item1:u,item2:l,logDifferences:p});g=h,i({item:u,features:d||[]})?.config?.usage_type===o.Continuous?f=!0:f=v}return a(u)&&(g=s({item1:u,item2:l,logDifferences:p}),g||(f=!0)),{same:g,pricesChanged:!g&&f}}}))(Ca,Dw,ni,Fw,yg,Wn,Ea,eA),{productsAreSame:MM}=((e,t,n,r,i,o,a,s,c,u,l,d,p)=>({productsAreSame:({newProductV1:f,newProductV2:h,curProductV1:v,curProductV2:I,features:S})=>{if(!f&&!h)throw new Error("productsAreSame error: product1 not provided");if(!v&&!I)throw new Error("productsAreSame error: product2 not provided");let R=h?.items||e({prices:f?.prices||[],entitlements:f?.entitlements||[],features:S}),D=I?.items||e({prices:v?.prices||[],entitlements:v?.entitlements||[],features:S});R=t({items:R,features:S}),D=t({items:D,features:S});let P=!0,be=!1,nt=!0,Qe=!0,je=!0,ue=[],$=[];nt=n({newProductV2:h,curProductV2:I}),Qe=r({newConfig:h?.config,curConfig:I?.config}),je=i({newBillingControls:h?.billing_controls??(f?o(f):void 0),curBillingControls:I?.billing_controls??(v?o(v):void 0)});let De=a({newMetadata:h?.metadata,curMetadata:I?.metadata});R.length!==D.length&&(P=!1),R.length!==D.length&&(P=!1);for(let Ze of R){let Kt=s({item:Ze,items:D});if(!Kt){(c(Ze)||u(Ze))&&(be=!0),P=!1,ue.push(Ze);continue}let{same:Rn,pricesChanged:en}=l({item1:Ze,item2:Kt,features:S,logDifferences:!1});Rn||(P=!1,ue.push(Ze)),en&&(be=!0)}for(let Ze of D)s({item:Ze,items:R})||(P=!1,(c(Ze)||u(Ze))&&(be=!0),$.push(Ze));let Q=v?.free_trial||I?.free_trial,pt=f?.free_trial||h?.free_trial,me=d({ft1:Q,ft2:pt}),ce=p({curProduct:I||v,newProduct:h||f});return{itemsSame:P,freeTrialsSame:me,onlyEntsChanged:!be,newItems:ue,removedItems:$,detailsSame:nt,optionsSame:ce,configSame:Qe,billingControlsSame:je,metadataSame:De,same:P&&nt&&me&&Qe&&De&&je}}}))(Gg,_w,rA,iA,yw,sg,sA,ru,ni,Ea,zg,cA,uA),{constructProduct:LM}=((e,t)=>({constructProduct:({productData:r,version:i=1,orgId:o,env:a,processor:s,baseInternalProductId:c})=>({id:r.id,name:r.name,description:r.description??null,is_add_on:r.is_add_on,is_default:r.is_default,version:i,version_slug:`v${i}`,active:!0,group:r.group||"",env:a,internal_id:e("prod"),org_id:o,created_at:Date.now(),processor:s,base_variant_id:null,base_internal_product_id:c??r.base_internal_product_id??null,archived:r.archived??!1,deleted_at:null,previous_version_slug:null,config:{...r.config,ignore_past_due:r.config?.ignore_past_due??!1},...t(r.billing_controls),metadata:r.metadata??{}})}))(Hr,Uw),{AdditionalCurrencyTierArraySchema:zw}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ae,Mw,lg,dg),{FeatureConfigOverrideSchema:Hw}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(Ae,Bw,iw),{itemToPriceAndEnt:Ww}=((e,t,n,r,i,o,a,s,c,u)=>({itemToPriceAndEnt:({item:d,orgId:p,internalProductId:g,feature:f,curPrice:h,curEnt:v,isCustom:I,newVersion:S,features:R})=>{let D=null,P=null,be=null,nt=null,Qe=null,je=null;if(e(d)){let{price:ue}=t({item:d,orgId:p,internalProductId:g,isCustom:I,newVersion:S,curPrice:h});!h||S?D=ue:n(h,ue,!0)?Qe=h:be=ue}else if(r(d)){if(!f)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let ue=f?.type===a.Boolean,{ent:$}=s({item:d,orgId:p,internalFeatureId:f.internal_id,internalProductId:g,isCustom:I,newVersion:S,feature:f,curEnt:v});!v||S?P=$:c(v,$)?je=v:nt=$}else{if(!f)throw new i({message:`Feature ${d.feature_id} not found`,code:o.InvalidRequest});let{price:ue,ent:$}=u({item:d,orgId:p,internalFeatureId:f.internal_id,internalProductId:g,isCustom:I,curPrice:h,curEnt:v,newVersion:S,features:R}),De=v&&c(v,$);!h||S?D=ue:!De||!n(h,ue,!1)?be=ue:Qe=h,!v||S?P=$:De?je=v:nt=$}return{newPrice:D,newEnt:P,updatedPrice:be,updatedEnt:nt,samePrice:Qe,sameEnt:je}}}))(Qc,Vw,Ra,wa,Ft,$t,Pt,PA,ou,$w),{copyStripeResourcesToMatchingPrice:Qw}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:a,candidatePrices:s,targetEntitlements:c,candidateEntitlements:u})=>{let l=s.map(I=>({candidatePrice:I,level:e({newPrice:a,candidatePrice:I,newEntitlements:c,candidateEntitlements:u})})),d=l.find(I=>I.level==="full"),g=(d??l.find(I=>I.level==="stripeProductOnly"))?.candidatePrice,f=d?.candidatePrice,h=a.config,v=[];if(g){let I=g.config;for(let S of t)S==="stripe_meter_id"&&(!n(a)||!n(g))||r({fromConfig:I,toConfig:h,field:S})&&v.push(S)}if(f){let I=f.config;for(let S of i)t.includes(S)||r({fromConfig:I,toConfig:h,field:S})&&v.push(S)}return{copiedFields:v}}}))(Gw,h1,NA,b1,_1),{getApiPlanDiff:BM}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(Kw),{backfillExistingItemIds:Zw}=((e,t)=>({backfillExistingItemIds:({items:r,currentFullProduct:i,features:o})=>{let a=e({currentFullProduct:i,features:o});return r.map(s=>{if(s.entitlement_id||s.price_id)return s;let c=t({item:s,items:a});return c?{...s,...c.entitlement_id?{entitlement_id:c.entitlement_id}:{},...c.price_id?{price_id:c.price_id}:{}}:s})}}))(Kg,ru),{PriceTierSchema:Yw}=((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,Gc,zw),{ProductItemConfigSchema:Jw}=((e,t,n,r,i,o,a)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:o.nullish(),feature_override:a.nullish()})}))(Ae,Qn,ei,Ji,gA,hA,Hw),{carryForwardStripeResources:Xw}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:o})=>{for(let a of n)e({targetPrice:a,candidatePrices:i,targetEntitlements:r,candidateEntitlements:o})}}))(Qw),{resolveInPlaceEdit:qM}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:o,items:a,currentFullProduct:s,features:c})=>{let u=e({items:a,currentFullProduct:s,features:c}),l=t({currentFullProduct:s,features:c}),d=[],p=[];for(let h of l){let v=n({item:h,items:u}),I=!v,S=v&&!r({item1:v,item2:h,features:c}).same;(I||S)&&(h.entitlement_id&&d.push(h.entitlement_id),h.price_id&&p.push(h.price_id))}let g=new Set([...d,...p]),f=u.map(h=>{let v=h.entitlement_id&&g.has(h.entitlement_id),I=h.price_id&&g.has(h.price_id);return v||I?{...h,entitlement_id:void 0,price_id:void 0}:h});return{retiredEntitlementIds:d,retiredPriceIds:p,items:f,curPrices:s.prices.filter(h=>!g.has(h.id)),curEnts:s.entitlements.filter(h=>!g.has(h.id))}}}))(Zw,Kg,ru,zg),{ProductItemSchema:eO}=((e,t,n,r,i,o,a,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},e.enum(o).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(a).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(o).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(Ae,kI,Tn,mA,Zi,Kc,Yr,Yw,Lw,Aa,Jw),{validateProductItem:tO}=((e,t,n,r,i,o,a,s,c,u,l,d,p,g,f,h,v,I,S,R)=>({validateProductItem:({item:P,features:be,multiCurrencyEnabled:nt,validateRollover:Qe})=>{P=e.parse(P);let je=be.find(me=>me.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===o.Boolean,$=a(P)||s(P.included_usage)&&P.included_usage!==0||s(P.interval)||s(P.config?.rollover);if(ue&&$)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:be}),a(P)&&P.included_usage===u)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(P.pooled&&a(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(me=>(me.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(a(P)||p(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(a(P)||d(P)){let me=g({item:P});if(String(me)===f.Day||String(me)===f.Minute||String(me)===f.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(a(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(a(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===v.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===o.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 Q=P.config.rollover;if(Q.duration===S.Forever&&(Q.length=0),!Qe)return;if(P.included_usage===u)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let pt=R({rollover:Q});if(pt)throw new n({message:pt,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(Q.duration===S.Month&&(typeof Q.length!="number"||Q.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})}}))(eO,Xt,Ft,$t,Hn,Pt,Hc,_r,qw,Zi,Yr,Qc,wa,Zn,Kc,Aa,ei,Eg,zc,QI),{validateProductItems:nO}=((e,t,n,r,i,o,a,s,c,u,l,d,p,g,f)=>({validateProductItems:({newItems:v,features:I,orgId:S,env:R,multiCurrencyEnabled:D,validateRollover:P=!0})=>{let{allFeatures:be,newFeatures:nt}=e({items:v,curFeatures:I,orgId:S,env:R});I=be;for(let ue=0;ue<v.length;ue++){t({item:v[ue],features:I,multiCurrencyEnabled:D,validateRollover:P});let $=I.find(De=>De.id===v[ue].feature_id);$&&$.type===n.Metered&&(v[ue].feature_type=$.config?.usage_type)}for(let ue=0;ue<v.length;ue++){let $=v[ue],De=r({item:$}),Q=i({item:$});if(o($)&&v.find((ce,Gt)=>ce.feature_id===$.feature_id&&Gt!==ue&&$.entity_feature_id===ce.entity_feature_id))throw new a({message:`Feature ${$.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let pt=v.find((me,ce)=>me.feature_id===$.feature_id&&ce!==ue&&r({item:me})===De&&i({item:me})===Q&&me.entity_feature_id===$.entity_feature_id);if(pt){if(u(pt)&&u($))throw new a({message:`You're trying to create two items for the same feature (${$.feature_id}) with the same interval. Please make them into one item.`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if($.usage_model&&$.usage_model===pt?.usage_model)throw new a({message:`You're trying to add the same feature (${$.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.find((ce,Gt)=>d({item:ce})===d({item:$})&&p({item:ce})===p({item:$})&&Gt!==ue))throw new a({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let Qe=v.some(ue=>(l(ue)||g(ue))&&String(d({item:ue}))===f.Week),je=v.some(ue=>(l(ue)||g(ue))&&String(d({item:ue}))===f.Month);if(Qe&&je)throw new a({message:"Can't have both weekly and monthly price items in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(v.filter(l).length>1)throw new a({message:"Can't have more than one price item in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});return{allFeatures:be,newFeatures:nt}}}))(tw,tO,Pt,Oa,Pa,Rg,Ft,$t,Hn,wa,Qc,Zn,ti,Hc,Kc),{handleNewProductItems:VM}=((e,t,n,r,i)=>({handleNewProductItems:async({db:a,curPrices:s,curEnts:c,newItems:u,features:l,product:d,logger:p,isCustom:g,newVersion:f,saveToDb:h=!0,multiCurrencyEnabled:v})=>{if(!u)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:l};let{allFeatures:I,newFeatures:S}=e({newItems:u,features:l,orgId:d.org_id,env:d.env,multiCurrencyEnabled:v,validateRollover:!g});l=I;let R=[],D=[],P=[],be=[],nt=s.filter($=>{let De=u.find(Q=>Q.price_id===$.id);return De?t(De):!0}),Qe=c.filter($=>!u.some(De=>De.entitlement_id===$.id)),je=[],ue=[];for(let $ of u){let De=l.find(en=>en.id===$.feature_id),Q=c.find(en=>en.id===$.entitlement_id),pt=s.find(en=>en.id===$.price_id),{newPrice:me,newEnt:ce,updatedPrice:Gt,updatedEnt:Ze,samePrice:Kt,sameEnt:Rn}=n({item:$,orgId:d.org_id,internalProductId:d.internal_id,feature:De,curPrice:pt,curEnt:Q,isCustom:g,newVersion:f,features:l});me&&R.push(me),ce&&D.push(ce),Gt&&P.push(Gt),Ze&&be.push(Ze),Kt&&je.push(Kt),Rn&&ue.push(Rn)}return r({targetPrices:[...R,...P],targetEntitlements:[...D,...be,...ue],candidatePrices:s,candidateEntitlements:c}),(g||f)&&h?{...i({newPrices:R,newEnts:D,updatedPrices:P,updatedEnts:be,samePrices:je,sameEnts:ue,features:l}),samePrices:je,sameEnts:ue,newFeatures:S,retiredPriceIds:nt.map($=>$.id),retiredEntitlementIds:Qe.map($=>$.id)}:{prices:[...R,...P],entitlements:[...D,...be].map($=>({...$,feature:l.find(De=>De.id===$.feature_id)})),customPrices:[],customEnts:[],features:l,samePrices:je,sameEnts:ue,newFeatures:S,retiredPriceIds:nt.map($=>$.id),retiredEntitlementIds:Qe.map($=>$.id)}}}))(nO,Ca,Ww,Xw,y1);var rO=pn.clone({precision:40});function au(e){if(!nu(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function su(e){let t=new rO(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function zM(e,t){let n=au(t),i=su(e).toDecimalPlaces(Ag(n),pn.ROUND_HALF_CEIL).mul(Ta(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 HM(e,t){let n=au(t),r=su(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(Ta(n)).toString()}function WM(e,t){let n=su(e).mul(Ta(au(t)));if(n.isNegative())throw new Error("Usage unit price must be nonnegative");if(n.decimalPlaces()>12||n.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Usage unit amount cannot be represented exactly by the provider");return n.toFixed()}import{z as qe}from"zod";var iO=qe.strictObject({selector:qe.string().min(1).max(2048),action:qe.enum(["set","append","remove"]),attribute:qe.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:qe.string().max(5e4).optional(),parentSelector:qe.string().max(2048).optional(),insertBeforeSelector:qe.string().max(2048).optional()}),oO=qe.strictObject({variation:qe.string().min(1).max(128),description:qe.string().max(2e3).default(""),css:qe.string().max(1e5).default(""),js:qe.string().max(1e5).default(""),domMutations:qe.array(iO).max(200).default([])}),cu=oO.omit({variation:!0,description:!0}),aO=Lr.omit({variations:!0,active:!0}).extend({changeId:qe.string().regex(/^[a-f0-9]{64}$/),variations:qe.tuple([cu,cu]).rest(cu).refine(e=>e.length<=20)}),JM=qe.strictObject({environmentId:qe.uuid(),trackExposures:qe.boolean(),generation:qe.string().regex(/^[a-f0-9]{64}$/),experiments:qe.array(aO).max(100),savedGroups:Ui}),XM="__indiana_visual_editor",e4=qe.object({selector:qe.string().max(2048),tag:qe.string().max(64),text:qe.string().max(1e3),href:qe.string().max(2048),src:qe.string().max(2048),matches:qe.number().int().nonnegative()});export{Wb as a,ll as b,es as c,ml as d,fo as e,Yb as f,ts as g,Jb as h,fl as i,ns as j,OO as k,Xb as l,gl as m,PO as n,hl as o,CO as p,ui as q,is as r,go as s,jn as t,W as u,Jn as v,jO as w,NO as x,_l as y,MO as z,yl as A,n_ as B,r_ as C,LO as D,os as E,ut as F,Y as G,ho as H,tn as I,Xe as J,Al as K,o_ as L,a_ as M,s_ as N,zO as O,ss as P,cs as Q,us as R,c_ as S,u_ as T,wl as U,l_ as V,XO as W,ds as X,Fe as Y,fn as Z,uP as _,Ol as $,lP as aa,Pl as ba,d_ as ca,Cl as da,dP as ea,pP as fa,p_ as ga,El as ha,ps as ia,mP as ja,fP as ka,_e as la,Ut as ma,xt as na,bo as oa,li as pa,f_ as qa,h_ as ra,b_ as sa,Rl as ta,__ as ua,Ir as va,xP as wa,kl as xa,vP as ya,y_ as za,S_ as Aa,x_ as Ba,IP as Ca,AP as Da,nn as Ea,Xn as Fa,_o as Ga,A_ as Ha,PP as Ia,RP as Ja,w_ as Ka,O_ as La,Fl as Ma,UP as Na,Ar as Oa,rn as Pa,Ul as Qa,P_ as Ra,Ml as Sa,MP as Ta,LP as Ua,BP as Va,qP as Wa,VP as Xa,$P as Ya,di as Za,yo as _a,$l as $a,pi as ab,wr as bb,E_ as cb,T_ as db,R_ as eb,k_ as fb,Nn as gb,Gl as hb,Kl as ib,zl as jb,Hl as kb,So as lb,Wl as mb,Ql as nb,Zl as ob,Yl as pb,N_ as qb,Jl as rb,D_ as sb,F_ as tb,U_ as ub,Xl as vb,_s as wb,M_ as xb,fi as yb,ed as zb,td as Ab,nd as Bb,L_ as Cb,rd as Db,id as Eb,hi as Fb,bi as Gb,tr as Hb,xo as Ib,Ss as Jb,B_ as Kb,ad as Lb,sd as Mb,_i as Nb,vo as Ob,cd as Pb,cC as Qb,uC as Rb,lC as Sb,dC as Tb,q_ as Ub,pC as Vb,mC as Wb,vs as Xb,bC as Yb,_C as Zb,yi as _b,xC as $b,vC as ac,V_ as bc,$_ as cc,ud as dc,IC as ec,G_ as fc,AC as gc,K_ as hc,ld as ic,z_ as jc,wC as kc,OC as lc,PC as mc,pd as nc,H_ as oc,EC as pc,dd as qc,W_ as rc,fd as sc,As as tc,Z_ as uc,TC as vc,nr as wc,RC as xc,kC as yc,Y_ as zc,J_ as Ac,X_ as Bc,ey as Cc,FC as Dc,UC as Ec,gd as Fc,ws as Gc,KC as Hc,zC as Ic,ty as Jc,ZC as Kc,YC as Lc,Io as Mc,Ii as Nc,Os as Oc,ir as Pc,yd as Qc,Ao as Rc,Sd as Sc,Ai as Tc,ny as Uc,Id as Vc,Ps as Wc,Ad as Xc,wd as Yc,Od as Zc,ry as _c,Pd as $c,Cs as ad,Cd as bd,mE as cd,Ed as dd,fE as ed,gE as fd,wo as gd,Td as hd,wi as id,Ye as jd,Rd as kd,kd as ld,Oo as md,jd as nd,cy as od,Nd as pd,Fd as qd,Ud as rd,Rs as sd,uy as td,Md as ud,EE as vd,Ld as wd,Bd as xd,kE as yd,jE as zd,ly as Ad,dy as Bd,Un as Cd,qd as Dd,py as Ed,my as Fd,ks as Gd,Gd as Hd,sr as Id,gy as Jd,hy as Kd,zd as Ld,Ci as Md,Cr as Nd,Co as Od,Hd as Pd,Wd as Qd,js as Rd,by as Sd,_y as Td,yy as Ud,Qd as Vd,Ns as Wd,Zd as Xd,Yd,Jd as Zd,Eo as _d,ZE as $d,YE as ae,Xd as be,To as ce,Sy as de,Ti as ee,Ro as fe,ep as ge,vy as he,Fs as ie,rT as je,np as ke,rp as le,Iy as me,Us as ne,op as oe,ap as pe,jo as qe,No as re,Ay as se,wy as te,Oy as ue,sp as ve,cp as we,up as xe,lp as ye,dp as ze,pp as Ae,mp as Be,fp as Ce,Er as De,Mn as Ee,gp as Fe,Cy as Ge,Ls as He,cr as Ie,AT as Je,Vs as Ke,Ey as Le,Ty as Me,Ri as Ne,Ry as Oe,jy as Pe,Ny as Qe,ki as Re,PT as Se,Do as Te,qs as Ue,Dy as Ve,bp as We,_p as Xe,Fy as Ye,CT as Ze,ET as _e,yp as $e,Uy as af,TT as bf,My as cf,Tr as df,Uo as ef,Mo as ff,xp as gf,LT as hf,vp as if,kr as jf,Ip as kf,Ly as lf,$s as mf,Ap as nf,Lo as of,Bo as pf,qo as qf,KT as rf,zT as sf,By as tf,wp as uf,Op as vf,Vy as wf,Cp as xf,ZT as yf,Ep as zf,Gs as Af,Tp as Bf,XT as Cf,$y as Df,cn as Ef,Ni as Ff,Me as Gf,Gy as Hf,Ky as If,zs as Jf,Rp as Kf,Di as Lf,kp as Mf,zy as Nf,Hy as Of,Np as Pf,Wy as Qf,Qy as Rf,Zy as Sf,Yy as Tf,Jy as Uf,ur as Vf,Xy as Wf,eS as Xf,tS as Yf,nS as Zf,rS as _f,iS as $f,oS as ag,aS as bg,sS as cg,cS as dg,uS as eg,lS as fg,Dp as gg,dS as hg,mS as ig,fS as jg,Hs as kg,cR as lg,gS as mg,uR as ng,Ct as og,lR as pg,Rt as qg,hn as rg,Ws as sg,bS as tg,jr as ug,dR as vg,pR as wg,SS as xg,Qs as yg,mR as zg,xS as Ag,Fi as Bg,fR as Cg,gR as Dg,Up as Eg,On as Fg,IS as Gg,Vo as Hg,$o as Ig,OS as Jg,PS as Kg,Mp as Lg,OR as Mg,PR as Ng,CR as Og,ER as Pg,Lp as Qg,Go as Rg,qp as Sg,Zs as Tg,Vp as Ug,$p as Vg,Gp as Wg,zp as Xg,Kp as Yg,Ys as Zg,CS as _g,zR as $g,ES as ah,Hp as bh,TS as ch,mr as dh,Wp as eh,Zp as fh,Yp as gh,Jp as hh,Xp as ih,em as jh,RS as kh,tm as lh,kS as mh,jS as nh,NS as oh,DS as ph,im as qh,ec as rh,am as sh,FS as th,US as uh,ak as vh,sk as wh,ck as xh,cm as yh,um as zh,lm as Ah,dm as Bh,pm as Ch,mm as Dh,uk as Eh,lk as Fh,LS as Gh,BS as Hh,dk as Ih,pk as Jh,tc as Kh,Dr as Lh,Ho as Mh,gm as Nh,Fr as Oh,Ur as Ph,fr as Qh,gr as Rh,Mr as Sh,hm as Th,qS as Uh,VS as Vh,nc as Wh,bm as Xh,_m as Yh,ym as Zh,rc as _h,_k as $h,yk as ai,Lr as bi,oc as ci,zS as di,HS as ei,Ui as fi,bn as gi,xm as hi,vm as ii,WS as ji,Im as ki,Am as li,wm as mi,QS as ni,lj as oi,M as pi,ZS as qi,YS as ri,JS as si,dj as ti,U as ui,pj as vi,sc as wi,Em as xi,Tm as yi,bj as zi,_j as Ai,yj as Bi,tt as Ci,xj as Di,km as Ei,Rm as Fi,Zo as Gi,Ij as Hi,jm as Ii,Ej as Ji,r0 as Ki,i0 as Li,Tj as Mi,Rj as Ni,Nm as Oi,o0 as Pi,Nj as Qi,a0 as Ri,Dm as Si,Fm as Ti,s0 as Ui,Dj as Vi,Fj as Wi,Uj as Xi,Mj as Yi,c0 as Zi,qj as _i,Vj as $i,Kj as aj,zj as bj,Mm as cj,Zj as dj,Yj as ej,Vi as fj,Lm as gj,uc as hj,$i as ij,Jo as jj,Gi as kj,un as lj,i2 as mj,dc as nj,o2 as oj,Bn as pj,Xo as qj,ea as rj,pc as sj,qm as tj,na as uj,mc as vj,m0 as wj,$m as xj,Gm as yj,g2 as zj,h2 as Aj,b2 as Bj,_2 as Cj,y2 as Dj,S2 as Ej,f0 as Fj,x2 as Gj,fc as Hj,g0 as Ij,gc as Jj,P2 as Kj,C2 as Lj,E2 as Mj,Km as Nj,N2 as Oj,h0 as Pj,b0 as Qj,hc as Rj,M2 as Sj,_0 as Tj,y0 as Uj,Hm as Vj,G2 as Wj,_c as Xj,yc as Yj,I0 as Zj,Sc as _j,xc as $j,qr as ak,A0 as bk,w0 as ck,iN as dk,Wm as ek,mN as fk,Ic as gk,Ac as hk,fN as ik,gN as jk,hN as kk,bN as lk,O0 as mk,Qm as nk,qt as ok,Jm as pk,Xm as qk,Zm as rk,P0 as sk,C0 as tk,Ki as uk,E0 as vk,Cc as wk,R0 as xk,qN as yk,VN as zk,$N as Ak,Ec as Bk,k0 as Ck,j0 as Dk,Tc as Ek,nf as Fk,sD as Gk,rf as Hk,gD as Ik,hD as Jk,sf as Kk,F0 as Lk,U0 as Mk,OD as Nk,uf as Ok,M0 as Pk,Rc as Qk,kc as Rk,jc as Sk,L0 as Tk,B0 as Uk,LD as Vk,BD as Wk,qD as Xk,VD as Yk,KD as Zk,WD as _k,df as $k,JD as al,XD as bl,q0 as cl,V0 as dl,$0 as el,G0 as fl,K0 as gl,z0 as hl,rF as il,H0 as jl,iF as kl,oF as ll,uF as ml,W0 as nl,Q0 as ol,aa as pl,Z0 as ql,Y0 as rl,pF as sl,bF as tl,_F as ul,yF as vl,J0 as wl,SF as xl,AF as yl,wF as zl,mx as Al,fx as Bl,gx as Cl,MF as Dl,Af as El,hx as Fl,qF as Gl,wf as Hl,zF as Il,HF as Jl,JF as Kl,XF as Ll,bx as Ml,rU as Nl,iU as Ol,Of as Pl,Pf as Ql,dU as Rl,pU as Sl,yx as Tl,xU as Ul,Sx as Vl,vU as Wl,xx as Xl,AU as Yl,Ef as Zl,wU as _l,OU as $l,Tf as am,Rf as bm,RU as cm,kU as dm,vx as em,MU as fm,Ix as gm,LU as hm,BU as im,Nf as jm,Df as km,zU as lm,HU as mm,WU as nm,QU as om,jf as pm,ZU as qm,Ax as rm,XU as sm,nM as tm,Ox as um,Uf as vm,rM as wm,oM as xm,aM as ym,zM as zm,HM as Am,WM as Bm,iO as Cm,oO as Dm,cu as Em,aO as Fm,JM as Gm,XM as Hm,e4 as Im};