@tinkerlandai/indiana-sdk 0.1.0 → 0.2.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.
- package/CHANGELOG.md +7 -0
- package/README.md +10 -6
- package/dist/{ai-usage-DX99gvfl.d.ts → ai-usage-CO0lDavO.d.ts} +210 -62
- package/dist/{chunk-2HEB2TPD.js → chunk-EZFAY4ZL.js} +1 -1
- package/dist/chunk-ULRVTA45.js +1 -0
- package/dist/chunk-YOH6DIUN.js +27 -0
- package/dist/funnel-runtime-host-OJJSHKUD.js +1 -0
- package/dist/{funnel-runtime-start-CcuXliU_.d.ts → funnel-runtime-start-DvrWekm0.d.ts} +1631 -135
- package/dist/index.d.ts +624 -40
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/paywall-HCADUT22.js +1 -0
- package/dist/popup.js +3 -3
- package/dist/server.d.ts +2 -2
- package/dist/server.js +1 -1
- package/dist/src-3GT6E6XD.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-FMAMDKAV.js +0 -27
- package/dist/chunk-Y7LNDG3O.js +0 -1
- package/dist/funnel-runtime-host-QIYKF5KH.js +0 -1
- package/dist/paywall-6HHA4OJV.js +0 -1
- package/dist/src-G7U7DUQR.js +0 -1
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import{z as en}from"zod";import{z as A}from"zod/v4";import{z as Yg}from"zod/v4";var hu=Yg.registry();var{AppEnv:Xi}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:bu}={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:ri}=(()=>{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:ah}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:_u}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:No}=(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:_r}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(A),{findDuplicate:oh}={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:Do}=(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:ii}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(hu),{COMMON:yu}={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)}))(yu),{hasNoDuplicateCurrencies:Su}={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:xu}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:Fo}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(A),{Infinite:ea}={Infinite:"inf"},{TierBehavior:ai}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:ta}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:vu}=(()=>{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:na}=(()=>{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:ra}=(()=>{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:Uo}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:Iu}=(()=>{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:Mo}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(A),{ApiCreditTierSchema:Au}=(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:mh}={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:wu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(A),{ModelMarkupsSchema:Bo}=((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,wu),{additionalCurrencyPlanItemIssues:Cu}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let n=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&n.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let r=t.tiers;if(r&&r.length>0){let i=o=>(o.additional_currencies??[]).map(s=>s.currency.toLowerCase()),a=new Set(r.flatMap(i));a.size>0&&(r.every(s=>{let c=new Set(i(s));return c.size===a.size&&[...a].every(l=>c.has(l))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:Lo}=((e,t,n,r,i)=>({PlanItemFilterSchema:e.object({feature_id:e.string().optional().meta({description:"Match items linked to this feature."}),billing_method:e.enum(t).optional().meta({description:"Match items with this billing method (prepaid or usage_based)."}),interval:e.union([e.enum(n),e.enum(r)]).optional().meta({description:"Match items with this interval. Accepts either a BillingInterval (price-side) or a ResetInterval (reset-side, includes day/hour/minute) so price-less items keyed by reset.interval can be disambiguated."}),interval_count:e.number().int().positive().optional().meta({description:"Match items with this interval_count. Disambiguates between items that share an interval but differ in count."}),included:i.optional().meta({description:"Match items whose grant equals this included usage. Omitted is a wildcard."})}).refine(o=>o.feature_id!==void 0||o.billing_method!==void 0||o.interval!==void 0||o.interval_count!==void 0,{message:"PlanItemFilter must have at least one field set."}).meta({title:"PlanItemFilter",description:"Filter for matching plan items. All provided fields must match (AND)."})}))(A,ta,kn,ri,Fo),{UpdatePlanItemParamsV1Schema:ph}=((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,Lo,ri),{FreeTrialDuration:oi}=(()=>{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})}))(ii,A),{findDuplicateInControls:gh}={findDuplicateInControls:({controlKey:t,controls:n,rule:r})=>{let i=new Set;for(let[a,o]of n.entries()){let s=r.identityOf(o);if(s!==void 0){if(i.has(s))return{code:"custom",message:r.message,input:o[r.field],path:[t,a,r.field]};i.add(s)}}}},{featureIdIdentity:hh}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:Pu}={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("|")}))(_u,Pu),{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:ia}={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:Ch}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(A),{UsageWindowScopeSchema:Ph}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(A),{EntInterval:Ou}=(()=>{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:Oh}=(()=>{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:kh}=((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,oi,ia),{BillingType:Th}=(()=>{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:qo}=((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,ea),{IgnoredFixedPriceMetadataSchema:Rh}=(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:Eu}=(()=>{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,na,ra),{AllowanceType:Dh}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:ku}=((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,Uo),{CreditDimensionBaseSchema:Fh}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(A,Mo),{flatCreditRateShape:Tu}=(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,Mo),{idRegex:aa}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Ru}={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:Bh}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:Lh}=(()=>{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:ju}=((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,oi,ia),{ProductConfigParamsSchema:Vo}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(A,ii,bu),{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,oi,ia),{CreateProductSchema:uC}=(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:Hh}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:Nu}=(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:Du}=(()=>{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:Fu}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:Uu}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(A,Fu),{RewardTriggerEvent:Wh}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:zh}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:oa}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(A,bu),{PurchaseLimitIntervalEnum:Qh}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(A,Jg),{DbSpendLimitSchema:$o}=((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]}))(ri),{UsageLimitAnchorSchema:Mu}=((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"]}))(ah),{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"]}]}}))(oh),{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,Do),{CURRENCY_CODES:tb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(yu,sh,ch),{AllocatedBillingFieldSchema:Bu}=((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,vu),{EntitlementExpirySchema:sa}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(A,Iu),{CreditDimensionNameSchema:Lu}=((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:qu}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Mo),{findCreditTierViolations:nb}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(mh),{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,qu),{ProviderMarkupsSchema:Vu}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(A,wu),{planItemParamsIssues:ib}=((e,t,n,r,i)=>({planItemParamsIssues:o=>{let s=[],c=o.reset?.interval,l=o.price?.interval,u=o.reset?.interval_count??1,d=o.price?.interval_count??1;if(c&&l&&(String(c)!==String(l)||u!==d)&&o.price?.billing_method!==e.Prepaid&&s.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:o}),o.threshold_billing&&(!o.price||o.unlimited)&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing}),o.expiry&&(o.price?.billing_method===e.Prepaid&&String(o.price.interval)===String(t.OneOff)||s.push({message:"expiry is only supported on one-off prepaid items. Recurring items are already bounded by their reset cadence.",input:o.expiry}),o.entity_feature_id&&s.push({message:"expiry is not supported on entity-scoped items; each entity's balance would have to expire on its own clock.",input:o.expiry}),o.pooled&&s.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:o.expiry}),o.expiry.length<=0&&s.push({message:"expiry.length must be greater than 0",input:o.expiry})),o.price){o.threshold_billing&&o.price.billing_method!==e.UsageBased&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing});let{amount:g,tiers:f}=o.price;o.threshold_billing&&f?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:o.threshold_billing});let h=o.price.billing_method===e.UsageBased&&o.price.allocated_billing===n.ProratedLegacy;o.proration&&o.price.billing_method!==e.Prepaid&&!h&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:o.proration});let x=typeof g=="number",I=Array.isArray(f)&&f.length>0;x||I?x&&I&&s.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:o.price}):s.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:o.price})}if(o.price?.tiers){let g=o.price.tiers.some(f=>f.flat_amount&&f.flat_amount>0);g&&o.price.tier_behavior!==r.VolumeBased&&s.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:o.price}),g&&o.price.tiers.length<=1&&s.push({message:"flat_amount is not supported on single-tier pricing.",input:o.price}),o.price.tiers.some(f=>f.flat_amount!=null&&f.flat_amount<0)&&s.push({message:"flat_amount must be 0 or greater.",input:o.price}),o.price?.tier_behavior===r.VolumeBased&&o.price?.billing_method!==e.Prepaid&&s.push({message:"volume-based pricing is only supported for prepaid features.",input:o.price}),o.price?.tiers.length===0?s.push({message:"tiers cannot be empty.",input:o.price}):o.included&&typeof o.price?.tiers[0].to=="number"&&o.price?.tiers[0].to<=o.included&&s.push({message:"tiers[0].to must be greater than included.",input:o.price})}for(let g of i(o.price))s.push({message:g,input:o.price});return s}}))(ta,kn,vu,ai,Cu),{FreeTrialParamsV1Schema:Go}=((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,oi,ii),{duplicateCheck:ab}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(gh),{usageLimitIdentity:Ko}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(Pu),{ApiPriceProcessorsSchema:$u}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(A,yh),{ApiFeatureV0Schema:Gu}=((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:ob}=((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,oi,ia),{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:lC}=((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,Ch,Ph,Ou,Mu),{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,Xi,Oh,Bo,Eh),{PriceCurrencyConfigSchema:Ku}=((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,qo),{UsagePriceConfigSchema:lb}=((e,t,n,r,i,a)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(a).optional()})}))(A,jh,qo,kn,Ku,Eu),{graduatedCreditRateShape:Hu}=((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,Vu,Bo),{usageAlertTargetLimitIdentity:mb}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(Ko),{DiscountConfigSchema:Wu}=((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,Fu),{RewardEntitlementSchema:zu}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(A,sa),{UpdateRewardSchema:dC}=((e,t,n,r,i,a)=>({UpdateRewardSchema:e.object({name:e.string().nullish(),promo_codes:e.array(t).optional(),id:e.string().optional(),type:e.nativeEnum(n).optional(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(a).nullish()})}))(A,Nu,Du,Wu,Uu,zu),{CreateRewardProgram:mC}=((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,Wh,zh),{AutoTopupPurchaseLimitSchema:Qu}=((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:Zu}=((e,t,n,r)=>({UsageLimitFilterSchema:e.object({properties:e.record(e.string().min(1).max(t),n).meta({description:"Event property equality conditions. A usage event counts toward this cap only when every listed property matches (AND)."}).check(a=>{let o=Object.keys(a.value).length;(o<1||o>r)&&a.issues.push({code:"custom",message:`filter.properties must have between 1 and ${r} keys`,input:a.value})})})}))(A,th,Yh,rh),{UsageAlertBasisSchema:pb}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(A,Jh),{refineCustomizePlanV1Schema:Yu}=(e=>({refineCustomizePlanV1Schema:(n,{includeItems:r=!0,includeFreeTrial:i=!0,includeUpdateItems:a=!0,includeLicenses:o=!0}={})=>{let s=["price",r&&"items","add_items","remove_items",a&&"update_items",i&&"free_trial","billing_controls",o&&"upsert_licenses",o&&"remove_licenses"].filter(Boolean),c=l=>l==="update_items"?"deprecated update_items":l;return n.refine(l=>s.some(u=>l[u]!==void 0),{message:`When using customize, at least one of ${s.map(c).join(", ")} must be provided`}).superRefine((l,u)=>{if(o)for(let d of e({upsertLicenses:l.upsert_licenses}))u.addIssue({code:"custom",...d})}).refine(l=>!(l.items!==void 0&&(l.add_items!==void 0||l.remove_items!==void 0||a&&l.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",a?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(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,qu),{refineGraduatedTiers:Ju}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(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,Vu,Bo),{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."})})}))(Qu,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"})]}))(ab,hh,Ko,bh),{ApiPlanProcessorsSchema:yb}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(A,xh,ob),{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,Ku,qo,Rh),{CreditDimensionSchema:xb}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(A,Fh,Tu,Hu),{filterUnresolvableUsageLimitAlerts:vb}=((e,t,n)=>({filterUnresolvableUsageLimitAlerts:({usageAlerts:i,usageLimitLists:a})=>{let o=new Set(a.flatMap(s=>(s??[]).map(e)));return i.flatMap((s,c)=>t(s)&&!o.has(n(s))?[{index:c,usageAlert:s}]:[])}}))(Ko,Hh,mb),{CreateRewardSchema:pC}=((e,t,n,r,i,a)=>({CreateRewardSchema:e.object({name:e.string(),promo_codes:e.array(t),id:e.string(),type:e.nativeEnum(n).nullish(),discount_config:r.nullish(),free_product_config:i.nullish(),free_product_id:e.string().nullish(),entitlements:e.array(a).nullish()}).refine(s=>s.type!==n.FeatureGrant?!0:s.entitlements&&s.entitlements.length>0,{message:"Feature grant rewards require at least one entitlement"}).refine(s=>s.type!==n.FeatureGrant?!0:s.promo_codes.some(c=>c.code.length>0),{message:"Feature grant rewards require at least one promo code"})}))(A,Nu,Du,Wu,Uu,zu),{AutoTopupSchema:Ho}=((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,Qu),{DbUsageLimitSchema:Wo}=((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,Mu,Zu),{DbUsageAlertSchema:zo}=((e,t,n,r,i)=>({DbUsageAlertSchema:e.object({feature_id:e.string().optional().meta({description:"The feature ID this alert applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage alert is enabled."}),threshold:e.number().min(0).meta({description:"The threshold value that triggers the alert. For usage or remaining, this is an absolute count. For usage_percentage or remaining_percentage, this is a percentage (0-100)."}),threshold_type:t.meta({description:"Whether the threshold is an absolute count or a percentage of the usage allowance or remaining balance."}),basis:n.default(r).meta({description:"What 100% means. balance: every grant on the feature. included: the plan allowance only. recurring: grants that reset. usage_limit: the cap of the usage limit with the same feature and filter."}),filter:i.optional().meta({description:"Only valid with basis usage_limit. Points the alert at the usage limit carrying the same filter."}),name:e.string().optional().meta({description:"Optional user-defined label to distinguish multiple alerts on the same feature."})}).check(o=>{let{feature_id:s,threshold_type:c,threshold:l,basis:u,filter:d}=o.value;c==="remaining_percentage"&&l>100&&o.issues.push({code:"custom",input:l,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),u==="usage_limit"&&!s&&o.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&u!=="usage_limit"&&o.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(A,ih,pb,_u,Zu),{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,Au,Ju),{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."})})}))(Ho,bb),{findDuplicateBillingControlIssue:Cb}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(_b),{CustomerBillingControlsSchema:Qo}=((e,t,n,r,i,a)=>({CustomerBillingControlsSchema:e.object({auto_topups:e.array(t).optional().meta({description:"List of auto top-up configurations per feature."}),spend_limits:e.array(n).optional().meta({description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:e.array(r).optional().meta({description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:e.array(i).optional().meta({description:"List of usage alert configurations per feature."}),overage_allowed:e.array(a).optional().meta({description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})})}))(A,Ho,$o,Wo,zo,No),{PriceSchema:Pb}=((e,t,n,r,i,a)=>({PriceSchema:e.object({id:e.string(),internal_product_id:e.string().nullable(),org_id:e.string().optional(),created_at:e.number().optional(),billing_type:e.nativeEnum(t).nullish(),tier_behavior:e.nativeEnum(n).nullish(),is_custom:e.boolean().optional(),config:r.or(i),entitlement_id:e.string().nullish(),proration_config:a.nullable()})}))(A,Th,ai,Sb,lb,Nh),{CreditSchemaItemBaseSchema:Xu}=((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,Lu,xb,Mh),{GraduatedCreditSchemaItemSchema:Ob}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(Xu,Hu),{UpdateProductSchema:fC}=((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,oa,Qo),{DbBillingControlsSchema:Eb}=((e,t,n,r,i,a)=>({DbBillingControlsSchema:e.object({auto_topups:e.array(t).nullish(),spend_limits:e.array(n).nullish(),usage_limits:e.array(r).nullish(),usage_alerts:e.array(i).nullish(),overage_allowed:e.array(a).nullish()})}))(A,Ho,$o,Wo,zo,No),{CurrencyCodeSchema:el}=((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:kb}=((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,el),{ApiCreditSchemaItemBaseSchema:tl}=((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,Lu,Ab,rb),{ApiFlatCreditSchemaItemSchema:Tb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(tl,A),{rejectDuplicateBillingControls:Rb}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(Cb),{FlatCreditSchemaItemSchema:jb}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(Xu,Tu),{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,Xi,oa,Eb,_r),{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,el),{AdditionalCurrencyTierArraySchema:nl}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(A,kb,Su,xu),{ApiGraduatedCreditSchemaItemSchema:Fb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(tl,A,Au,Ju),{CustomerBillingControlsParamsSchema:ca}=((e,t,n,r,i,a,o,s)=>({CustomerBillingControlsParamsSchema:e.object({auto_topups:t({schema:n,description:"List of auto top-up configurations per feature."}),spend_limits:t({schema:r,description:"List of overage spend limits per feature (caps overage spend)."}),usage_limits:t({schema:i,description:"List of hard usage caps per feature (max units per interval)."}),usage_alerts:t({schema:a,description:"List of usage alert configurations per feature."}),overage_allowed:t({schema:o,description:"List of overage allowed controls per feature. When enabled, usage can exceed balance."})}).check(s)}))(A,fh,wb,$o,Wo,zo,No,Rb),{CreditSchemaItemSchema:Ub}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(A,jb,Ob),{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,nl),{PlanBillingControlsParamsSchema:Bb}=((e,t)=>({PlanBillingControlsParamsSchema:e.check(r=>{let i=t({usageAlerts:r.value.usage_alerts??[],usageLimitLists:[r.value.usage_limits??[]]});for(let{index:a,usageAlert:o}of i)r.issues.push({code:"custom",message:`No usage limit on this plan matches the usage_limit alert for feature ${o.feature_id}`,input:o,path:["usage_alerts",a,"basis"]})})}))(ca,vb),{AdditionalCurrencyPriceArraySchema:si}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(A,Db,Su,xu),{ApiUsageTierWithCurrenciesSchema:rl}=((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,ea,nl),{ApiCreditSchemaItemSchema:Lb}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(A,Fb,Tb),{FeatureConfigOverrideSchema:il}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(A,Ub,db),{ProductItemConfigSchema:qb}=((e,t,n,r,i,a,o)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:a.nullish(),feature_override:o.nullish()})}))(A,Eu,na,ra,ku,sa,il),{BasePriceParamsSchema:ua}=((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,ii,A,si),{PlanItemPriceParamsSchema:Vb}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(A,si,rl,ai,kn,ta,Bu),{ApiFeatureOverrideSchema:al}=((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,Lb,hb),{ApiPlanItemV1Schema:$b}=((e,t,n,r,i,a,o,s,c,l,u,d,m,g,f,h,x)=>({ApiPlanItemV1Schema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature this item configures."}),feature:t.optional().meta({description:"The full feature object if expanded."}),included:e.number().meta({description:"Number of free units included. For consumable features, balance resets to this number each interval."}),unlimited:e.boolean().meta({description:"Whether the customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"The interval at which the feature balance resets (e.g. 'month', 'year'). For consumable features, usage resets to 0 and included units are restored."}),interval_count:e.number().optional().meta({description:"Number of intervals between resets. Defaults to 1."})}).nullable().meta({description:"Reset configuration for consumable features. Null for non-consumable features like seats where usage persists across billing cycles."}),price:e.object({amount:e.number().optional().meta({description:"Price per billing_units after included usage is consumed. Mutually exclusive with tiers."}),additional_currencies:r.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers' (tiered prices carry per-currency amounts on each tier)."}),tiers:e.array(i).optional().meta({description:"Tiered pricing configuration. Each tier's 'to' INCLUDES the included amount. Either 'tiers' or 'amount' is required."}),tier_behavior:e.enum(a).optional(),interval:e.enum(o).meta({description:"Billing interval for this price. For consumable features, should match reset.interval."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().meta({description:"Number of units per price increment. Usage is rounded UP to the nearest billing_units when billed (e.g. billing_units=100 means 101 usage rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:c,max_purchase:e.number().nullable().meta({description:"Maximum units a customer can purchase beyond included. E.g. if included=100 and max_purchase=300, customer can use up to 400 total before usage is capped. Null for no limit."}),processors:l.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:u.optional().meta({description:"Display text for showing this item in pricing pages."}),rollover:e.object({max:e.number().nullable().meta({description:"Maximum rollover units. Null for unlimited rollover."}),max_percentage:e.number().nullable().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(d).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover configuration for unused units. If set, unused included units roll over to the next period."}),proration:e.object({on_increase:e.enum(m).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(g).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry: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 T=S.value.reset?.interval,D=S.value.price?.interval,P=S.value.reset?.interval_count??1,be=S.value.price?.interval_count??1;if(T&&D&&(String(T)!==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 We of x(S.value.price))S.issues.push({code:"custom",message:We,input:S.value.price})}})}))(A,Gu,ri,si,rl,ai,kn,ta,Bu,$u,Do,Uo,na,ra,sa,al,Cu),{EntitlementSchema:Gb}=((e,t,n,r,i,a)=>({EntitlementSchema:e.object({id:e.string(),created_at:e.number(),internal_feature_id:e.string(),internal_product_id:e.string().nullable(),internal_reward_id:e.string().nullish(),is_custom:e.boolean().default(!1),allowance_type:e.nativeEnum(t).optional().nullable(),allowance:e.number().nullish(),interval:e.nativeEnum(n).optional().nullable(),interval_count:e.number().default(1),carry_from_previous:e.boolean().default(!1).optional(),entity_feature_id:e.string().nullish(),pooled:e.boolean().default(!1).optional(),org_id:e.string().optional(),feature_id:e.string().optional(),usage_limit:e.number().nullable().optional().default(null),expiry_duration:e.nativeEnum(r).nullish(),expiry_length:e.number().nullish(),rollover:i.nullish(),feature_override:a.nullish()})}))(A,Dh,Ou,Iu,ku,il),{ProductItemSchema:ol}=((e,t,n,r,i,a,o,s,c,l,u)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(l).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:u.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(A,Bh,Lh,Gu,ea,qh,Vh,Mb,si,ai,qb),{ProductV2Schema:sl}=((e,t,n,r,i,a,o)=>({ProductV2Schema:e.object({internal_id:e.string().nullish(),id:e.string(),name:e.string(),description:e.string().nullish(),is_add_on:e.boolean(),is_default:e.boolean(),version:e.number().default(1),version_slug:e.string().nullable().optional(),active:e.boolean().optional(),group:e.string().nullable(),env:e.nativeEnum(t),free_trial:n.nullish(),items:e.array(r),created_at:e.number(),stripe_id:e.string().nullish(),archived:e.boolean().default(!1).nullish(),base_internal_product_id:e.string().nullish(),base_id:e.string().nullish(),config:i.partial().optional(),billing_controls:a.optional(),metadata:o.optional()})}))(A,Xi,Kh,ol,oa,Qo,_r),{PlanItemParamsObjectSchema:Kb}=((e,t,n,r,i,a,o,s,c,l,u)=>({PlanItemParamsObjectSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature to configure."}),included:t.optional().meta({description:"Number of free units included. Balance resets to this each interval for consumable features."}),unlimited:e.boolean().optional().meta({description:"If true, customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:r({schema:e.number().optional(),defaultValue:1,description:"Number of intervals between resets. Defaults to 1."})}).optional().meta({description:"Reset configuration for consumable features. Omit for non-consumable features like seats."}),price:i.optional().meta({description:a}),proration:e.object({on_increase:e.enum(o).meta({description:"Billing behavior when quantity increases mid-cycle."}),on_decrease:e.enum(s).meta({description:"Credit behavior when quantity decreases mid-cycle."})}).optional().meta({description:"Proration settings for prepaid features. Controls mid-cycle quantity change billing."}),rollover:e.object({max:e.number().optional().meta({description:"Max rollover units. Omit for unlimited rollover."}),max_percentage:e.number().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(c).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover config for unused units. If set, unused included units carry over."}),expiry:l.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:u.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,Fo,ri,ii,Vb,uh,na,ra,Uo,sa,al),{FullProductWithoutLicensesSchema:gC}=((e,t,n,r,i,a)=>({FullProductWithoutLicensesSchema:e.extend({description:t.string().nullable().optional().default(null),prices:t.array(n),entitlements:t.array(r.extend({feature:i})),free_trial:a.nullish(),free_trials:t.array(a).nullish(),free_trial_ids:t.array(t.string()).nullish()})}))(Nb,A,Pb,Gb,ub,kh),{CreateProductItemParamsSchema:cl}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))(ol,Fo,A,ea),{CreatePlanItemParamsV1Schema:Zo}=((e,t)=>({CreatePlanItemParamsV1Schema:e.check(r=>{for(let{message:i,input:a}of t(r.value))r.issues.push({code:"custom",message:i,input:a})}).meta({title:"PlanItem",description:"Configuration for a feature item in a plan, including usage limits, pricing, and rollover settings."})}))(Kb,ib),{LicenseCustomizeSchema:ul}=((e,t,n,r)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(n).optional(),remove_items:e.array(r).optional()})}))(A,ua,Zo,Lo),{PlanLicenseParamsSchema:Yo}=((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,ul),{UpdateProductV2ParamsSchema:hC}=((e,t,n,r,i,a,o,s,c)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:n.id}),name:e.string().refine(u=>u.length>0,{message:"name must be a non-empty string"}).optional().meta({description:n.name}),is_add_on:e.boolean().optional().meta({description:n.is_add_on}),is_default:e.boolean().optional().meta({description:n.is_default}),base_plan_id:e.string().nonempty().regex(t).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."}),description:e.string().nullish().optional().meta({description:n.description}),group:e.string().nonempty().nullable().optional().meta({description:n.group}),archived:e.boolean().optional().meta({description:n.archived}),items:e.array(r).optional(),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata})})}))(A,aa,Ru,cl,Yo,ju,Vo,ca,_r),{CreatePlanParamsV1Schema:Hb}=((e,t,n,r,i,a,o,s,c)=>({CreatePlanParamsV1Schema:e.object({id:e.string().nonempty().regex(t).meta({description:"Unique identifier for the plan."}),group:e.string().default("").meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),name:e.string().nonempty().meta({description:"Display name of the plan."}),description:e.string().nullable().default(null).meta({description:"Optional description of the plan."}),add_on:e.boolean().default(!1).meta({description:"If true, this plan can be attached alongside other plans. Otherwise, attaching replaces existing plans in the same group."}),auto_enable:e.boolean().default(!1).meta({description:"If true, plan is automatically attached when a customer is created. Use for free tiers."}),price:n.optional().meta({description:"Base recurring price for the plan. Omit for free or usage-only plans."}),items:e.array(r).optional().meta({description:"Feature configurations for this plan. Each item defines included units, pricing, and reset behavior."}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.optional().meta({description:"Free trial configuration. Customers can try this plan before being charged."}),config:o.optional().meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:"Arbitrary key-value metadata defined by you for your own use (e.g. UI copy, feature highlights). Values can be any JSON-serializable value. Shared across all versions of the plan."}),create_in_stripe:e.boolean().default(!0).meta({internal:!0})})}))(A,aa,ua,Zo,Yo,Go,Vo,Bb,_r),{UpdatePlanParamsV1Schema:bC}=((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."})})}))(Hb,A,ua,Go,aa),{CustomizePlanLicenseSchema:Jo}=((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,ul),{CreateProductV2ParamsSchema:_C}=((e,t,n,r,i,a,o,s,c,l)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:n.id}),name:e.string().refine(d=>d.length>0,{message:"name must be a non-empty string"}).meta({description:n.name}),description:e.string().nullish().meta({description:n.description}),is_add_on:e.boolean().default(!1).meta({description:n.is_add_on}),is_default:e.boolean().default(!1).meta({description:n.is_default}),group:e.string().nullable().default("").meta({description:n.group}),items:e.array(r).optional().meta({description:n.items}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().default(null).meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata}),create_in_stripe:e.boolean().optional().meta({internal:!0}),archived:e.boolean().optional().meta({internal:!0}),base_internal_product_id:e.string().nullable().optional().meta({internal:!0})}).meta({examples:[l]})}))(A,aa,Ru,cl,Yo,ju,Vo,ca,_r,Gh),{CustomizePlanV1BaseSchema:ll}=((e,t,n,r,i,a,o,s,c)=>({CustomizePlanV1BaseSchema:e.object({price:t.nullable().optional().meta({description:"Override the base price of the plan. Pass null to remove the base price."}),items:e.array(n).optional().meta({description:"Override the items in the plan (PUT-style \u2014 replaces all existing items). Mutually exclusive with add_items / remove_items / deprecated update_items."}),add_items:e.array(n).optional().meta({description:"Items to add to the plan."}),remove_items:e.array(r).optional().meta({description:"Filters selecting items to remove from the plan."}),update_items:e.array(i).optional().meta({description:"Deprecated. Use remove_items and add_items to replace matched plan items.",internal:!0,deprecated:!0}),free_trial:a.nullable().optional().meta({description:"Override the plan's default free trial. Pass an object to set a custom trial, or null to remove the trial entirely."}),billing_controls:o.optional().meta({description:"Override the plan's billing controls (auto top-ups, spend limits, usage limits, usage alerts, overage allowed) for this customer."}),upsert_licenses:e.array(s).optional().meta({description:"License links to add or override for this customer, keyed by license_plan_id. Omitted fields inherit the plan catalog link (included defaults to 1 when the license is not in the catalog). A bare entry restores the license to pure catalog inheritance."}),remove_licenses:e.array(c).optional().meta({description:"License links to drop, keyed by license_plan_id. Parallel to remove_items."})})}))(A,ua,Zo,Lo,ph,Go,ca,Jo,_h),{VariantCustomizeSchema:Wb}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(Yu,ll),{DiffedCustomizePlanV1Schema:yC}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(Yu,ll),{ApiPlanV1Schema:SC}=((e,t,n,r,i,a,o,s,c,l,u,d,m,g)=>({ApiPlanV1Schema:e.object({id:e.string().meta({description:"Unique identifier for the plan."}),internal_id:e.string().nullable().optional().meta({description:"Stable row id. Survives renames of plan_id and version_slug, so config files address rows by it.",internal:!0}),name:e.string().meta({description:"Display name of the plan."}),description:e.string().nullable().meta({description:"Optional description of the plan."}),group:e.string().nullable().meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),version:e.number().meta({description:"Version number of the plan. Incremented when plan configuration changes."}),version_slug:e.string().nullable().optional().meta({description:"User-facing version identity. Defaults to v{n} when the version is minted."}),active:e.boolean().optional().meta({description:"Whether this is the active version of the plan. At most one version is active."}),add_on:e.boolean().meta({description:"Whether this is an add-on plan that can be attached alongside a main plan."}),auto_enable:e.boolean().meta({description:"If true, this plan is automatically attached when a customer is created. Used for free plans."}),price:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),additional_currencies:t.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),interval:e.enum(n).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0}),display:r.optional().meta({description:"Display text for showing this price in pricing pages."}),processors:i.optional().meta({description:"Payment processors this base price is connected to. Omitted when unset."})}).nullable().meta({description:"Base recurring price for the plan. Null for free plans or usage-only plans."}),items:e.array(a).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:o.optional().meta({description:"Payment processors this plan is connected to. Omitted when unset."}),free_trial:s.optional().meta({description:"Free trial configuration. If set, new customers can try this plan before being charged."}),created_at:e.number().meta({description:"Unix timestamp (ms) when the plan was created."}),env:e.enum(c).meta({description:"Environment this plan belongs to ('sandbox' or 'live')."}),archived:e.boolean().meta({description:"Whether the plan is archived. Archived plans cannot be attached to new customers."}),config:l.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:u.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:m.optional(),base_variant_id:e.string().nullable().meta({description:"Deprecated. Use variant_details.base_plan_id instead. If this is a variant, the ID of the base plan it was created from.",deprecated:!0}),variant_details:e.object({base_plan_id:e.string().meta({description:"The ID of the base plan this variant was derived from."}),customize:g.optional().meta({description:"The customization that transforms the base plan into this variant."})}).optional().meta({description:"Details about how this variant relates to its latest base plan."})})}))(A,si,kn,Do,$u,$b,yb,sb,Xi,oa,Qo,_r,cb,Wb);import{z as O}from"zod";var zb=O.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),pl=O.enum(["single_use","continuous_use"]),Xo=O.record(O.string(),O.union([O.string(),O.number(),O.boolean()]).transform(String).pipe(O.string())),dl=O.string().min(1).max(64).refine(e=>!e.includes("::")),fl={credit_amount:O.number(),tier_behavior:O.never().optional(),tiers:O.never().optional()},gl={credit_amount:O.never().optional(),tier_behavior:O.literal("graduated"),tiers:O.array(O.strictObject({to:O.union([O.number(),O.literal("inf")]),credit_amount:O.number()}))},Qb=O.union([O.strictObject({match:Xo,priority:O.number().int().optional(),...fl}),O.strictObject({match:Xo,priority:O.number().int().optional(),...gl})]),Zb=O.strictObject({match:Xo,factor:O.number().positive().optional(),add:O.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),ml={metered_feature_id:O.string(),feature_amount:O.number().optional(),dimensions:O.record(dl,Qb).optional(),multipliers:O.record(dl,Zb).optional()},es=O.union([O.strictObject({...ml,...fl}),O.strictObject({...ml,...gl})]),da=O.number().min(-100),hl=O.record(O.string(),O.strictObject({markup:da})).nullish(),ma=O.record(O.string().regex(/.+\/.+/),O.strictObject({markup:da.optional(),input_cost:O.number().min(0).optional(),output_cost:O.number().min(0).optional()})).nullish(),Yb=O.strictObject({default_markup:da.optional(),provider_markups:hl,model_markups:ma}),ts=O.strictObject({schema:O.array(es).optional(),markups:Yb.optional()}),Jb=O.strictObject({filters:O.array(O.strictObject({property:O.string(),operator:O.string(),value:O.array(O.string())})),aggregate:O.strictObject({type:O.string(),property:O.string().nullable()}),usage_type:pl}),bl=O.strictObject({schema:O.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:O.boolean().optional(),usage_type:pl.default("single_use").overwrite(()=>"single_use"),default_markup:da.optional(),provider_markups:hl}),ns=bl.safeExtend({schema:O.array(es).length(0)}),la={id:zb,name:O.string().min(1),display:O.strictObject({singular:O.string().optional(),plural:O.string().optional()}).nullish(),event_names:O.array(O.string()).default([]),model_markups:ma,stripe_meter:O.strictObject({id:O.string(),event_name:O.string()}).nullish(),stripe_product_id:O.string().nullish()},rs=e=>O.discriminatedUnion("type",[O.strictObject({...la,...e,type:O.literal("boolean"),config:O.null()}),O.strictObject({...la,...e,type:O.literal("metered"),config:Jb}),O.strictObject({...la,...e,type:O.literal("credit_system"),config:bl}),O.strictObject({...la,...e,type:O.literal("ai_credit_system"),config:ns})]),IC=rs({}),Xb=O.strictObject({id:O.boolean(),type:O.boolean(),usage_type:O.boolean()}),e_={internal_id:O.uuid(),org_id:O.uuid(),created_at:O.number(),env:O.enum(["sandbox","live"]),archived:O.boolean(),project_id:O.uuid(),environment_id:O.uuid(),revision:O.number().int().nonnegative(),update_rules:Xb},_l=rs(e_),AC=O.strictObject({rows:O.array(_l).max(200),nextCursor:O.uuid().nullable()}),yl=O.strictObject({features:O.array(_l).max(500),limited:O.boolean()}),wC=O.union([rs({action:O.literal("save"),internal_id:O.uuid().nullable(),revision:O.number().int().nonnegative()}),O.strictObject({action:O.enum(["archive","restore","delete"]),internal_id:O.uuid(),revision:O.number().int().nonnegative()})]);import{z as yr}from"zod";var Sl=yr.number().int().min(0).max(1e8),ci=yr.strictObject({kind:yr.enum(["graduated","volume"]),tiers:yr.array(yr.strictObject({upTo:yr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Sl,flatAmountMinor:Sl.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?ci.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function pa(e){return is({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as N}from"zod";import{z as G}from"zod";import{z as ln}from"zod";import{z as t_}from"zod";var Tn=["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"],z=t_.enum(Tn);function Zn(e){let t=z.parse(e.toUpperCase());return["JPY","KRW","VND"].includes(t)?0:2}function kC(e,t){let n=Zn(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 TC(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("Expected a nonnegative integer amount");let n=Zn(t),r=String(e).padStart(n+1,"0");return n?`${r.slice(0,-n)}.${r.slice(-n)}`:r}function xl(e,t,n="en",r={}){let i=z.parse(t.toUpperCase());return new Intl.NumberFormat(n,{style:"currency",currency:i,...r}).format(e/10**Zn(i))}import{z as yn}from"zod";var DC={plans:Tn,creditPacks:Tn,paidSeats:Tn,postpaid:Tn},vl=yn.partialRecord(yn.enum(Tn),yn.number().int().min(1).max(1e8)),n_=yn.strictObject({currency:yn.enum(Tn),automaticTax:yn.boolean()}),r_=yn.strictObject({projectId:yn.uuid(),environmentId:yn.uuid()}),FC=r_.extend({settings:n_});var i_=ln.string().regex(/^[a-z][a-z0-9_]{0,63}$/),Il=ln.number().int().min(0).max(1e4),as=ln.object({key:i_,featureId:ln.uuid(),planVersionId:ln.uuid(),includedQuantity:Il,maximumQuantity:Il,unitAmountCents:ln.number().int().min(0).max(1e8),currency:z,currencyOptions:vl.optional(),stripePriceId:ln.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:ln.array(ln.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:ln.boolean()}).strict().refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency),"Additional prices cannot repeat the default currency").refine(e=>e.maximumQuantity>=e.includedQuantity,"\u6700\u5927\u5E2D\u4F4D\u6570\u4E0D\u80FD\u5C0F\u4E8E\u5305\u542B\u5E2D\u4F4D\u6570").refine(e=>new Set(e.pooledResources).size===e.pooledResources.length,"\u5171\u4EAB\u6765\u6E90\u4E0D\u80FD\u91CD\u590D");import{z as Ce}from"zod";import{z as mt}from"zod";import{z as Ke}from"zod";var ct=Ke.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Y=Ke.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),fa=Ke.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}),os=Y.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Al=Ke.string().min(1).max(64),Yt=Ke.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),wl=Ke.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),Ye=Ke.record(Al,Ke.union([Ke.string().max(120),Ke.number().finite(),Ke.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)]))),Cl=Ke.record(Al,Ke.union([Ke.string().max(120),Ke.number().finite(),Ke.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Sr=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},Pl=Ke.array(Ke.object({upTo:os.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||Sr(t.upTo)>Sr(e[n-1].upTo))),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),a_=Ke.object({key:wl,match:Cl,priority:Ke.number().int().default(0),cost:Y.optional(),tiers:Pl.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),o_=Ke.object({key:wl,match:Cl,factor:os.optional(),add:fa.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_=Ke.object({units:os.default("1"),cost:Y,tiers:Pl.optional(),dimensions:Ke.array(a_).max(12).optional(),multipliers:Ke.array(o_).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(o=>o.key)).size!==n.length||new Set(r.map(o=>o.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let o=0;o<n.length;o++)for(let s=o+1;s<n.length;s++){let c=n[o],l=n[s];Object.keys(c.match).length===Object.keys(l.match).length&&c.priority===l.priority&&!Object.keys(c.match).some(u=>l.match[u]!==void 0&&l.match[u]!==c.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"})}let i=[e.cost,...(e.tiers??[]).map(o=>o.cost),...n.flatMap(o=>[...o.cost===void 0?[]:[o.cost],...(o.tiers??[]).map(s=>s.cost)])],a=Sr(e.units);for(let o 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(x=>Object.keys(f.match).some(I=>x.match[I]!==void 0&&x.match[I]!==f.match[I]))))continue;let l=Sr(o),u=BigInt("1"),d=BigInt("0");for(let f=0;f<r.length;f++)s&1<<f&&(l*=Sr(r[f].factor??"1"),u*=BigInt("1000000"),d+=Sr(r[f].add??"0"));let m=(l+d*u)*BigInt("1000000"),g=u*a;(m<BigInt("0")||m%g!==BigInt("0")||m/g>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),$C=s_.safeExtend({featureKey:Yt});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=Ce.object({group:Ce.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:Ce.enum(["main","addon"]).default("main")}).strict(),c_=Ce.enum(["immediate","end_of_cycle"]),u_=Ce.enum(["attach","change","cancel","resume","cancel_change"]),Ol=Ce.object({id:Ce.uuid(),subscriptionId:Ce.uuid().nullable(),targetPlanVersionId:Ce.uuid().nullable(),action:u_,timing:c_,status:Ce.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:Ce.iso.datetime().nullable(),createdAt:Ce.iso.datetime()}),l_=Ce.object({id:Ce.uuid(),planVersionId:Ce.uuid(),planId:Ce.uuid(),basePlanId:Ce.uuid().nullable(),name:Ce.string(),group:Ce.string(),kind:Ce.enum(["main","addon"]),source:Ce.enum(["subscription","assignment","license","apple","google"]),status:Ce.string(),accessEnabled:Ce.boolean(),startsAt:Ce.iso.datetime().nullable(),endsAt:Ce.iso.datetime().nullable(),cancelAtPeriodEnd:Ce.boolean(),scheduledChange:Ol.nullable(),trial:cs.nullable().optional()}),ZC=Ce.object({customerId:Ce.uuid(),evaluatedAt:Ce.iso.datetime(),holdings:Ce.array(l_),changes:Ce.array(Ol),trials:Ce.array(cs).optional()});import{z as ls}from"zod";var ds=ls.enum(["sandbox","live"]),Ue=ls.object({projectId:ls.string().min(1),environment:ds}).strict();var dn=G.string().trim().min(1).max(64).regex(/^[a-z][a-z0-9_]*$/,"ID \u4F7F\u7528\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u4E0B\u5212\u7EBF\uFF0C\u5E76\u4EE5\u5B57\u6BCD\u5F00\u5934"),oP=G.record(G.string().min(1).max(80),G.union([G.string().max(500),G.number().finite(),G.boolean(),G.null()])).refine(e=>Object.keys(e).length<=30,"\u6700\u591A 30 \u4E2A\u5C5E\u6027"),El=G.object({key:dn,name:G.string().trim().min(1).max(80),description:G.string().trim().max(240),type:G.enum(["boolean","metered"]),usageType:G.enum(["consumable","non_consumable"]).optional()}),sP=El.extend({...Ue.shape,id:G.string().min(1),archived:G.boolean(),createdAt:G.iso.datetime()}),kl=G.object({amountCents:G.number().int().min(0).max(1e8),currency:z,interval:G.enum(["free","month","year"]),currencyOptions:G.partialRecord(z,G.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C"),d_=G.object({featureId:G.string().min(1),allowance:G.number().int().min(0).max(1e9).nullable(),pooled:G.boolean().optional()}),Tl=G.object({name:G.string().trim().min(1).max(80),description:G.string().trim().max(240),price:kl,membership:us.optional(),trial:ss.nullable().optional(),licenses:G.array(as).max(20).optional(),items:G.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")}),cP=G.object({key:dn,config:Tl}),uP=Ue.extend({id:G.string().min(1),key:dn,draft:Tl,status:G.enum(["draft","published","archived"]),publishedVersionId:G.string().nullable(),isDefault:G.boolean(),updatedAt:G.iso.datetime()}),m_=El.pick({key:!0,name:!0,type:!0}).extend({featureId:G.string(),allowance:G.number().int().min(0).max(1e9).nullable(),pooled:G.boolean().optional()}).refine(e=>e.type==="boolean"?e.allowance===null:e.allowance!==null,"\u5F00\u5173\u578B\u65E0\u6570\u91CF\uFF0C\u8BA1\u91CF\u578B\u5FC5\u987B\u6307\u5B9A\u989D\u5EA6"),Rl=Ue.extend({id:G.string().min(1),planId:G.string().min(1),variant:G.object({basePlanId:G.uuid(),baseVersionId:G.uuid()}).nullable(),version:G.number().int().positive(),name:G.string(),description:G.string(),price:kl,membership:us.optional(),trial:ss.nullable().optional(),licenses:G.array(as).optional(),items:G.array(m_),publishedAt:G.iso.datetime()}).strict(),ms=G.object({startsAt:G.iso.datetime(),endsAt:G.iso.datetime().nullable()}).refine(e=>e.endsAt===null||Date.parse(e.endsAt)>Date.parse(e.startsAt),"\u5230\u671F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u751F\u6548\u65F6\u95F4"),lP=Ue.extend({id:G.string(),customerId:G.string(),planVersionId:G.string(),assignedAt:G.iso.datetime(),source:G.literal("demo"),validity:ms.nullable().default(null),used:G.record(G.string(),G.number().int().min(0))}),dP=Ue.extend({id:G.string(),customerId:G.string(),at:G.iso.datetime(),message:G.string()});import{z as b}from"zod";import{z as oe}from"zod";import{z as w}from"zod";function ga(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function xr(e,t,n){return n===2?ga(ga(e+t)+"")%1e4/1e4:n===1?ga(t+e)%1e3/1e3:null}function jl(e){return e<=0?[]:new Array(e).fill(1/e)}function ui(e,t){return e>=t[0]&&e<t[1]}function ps(e,t){let n=xr("__"+t[0],e,1);return n===null?!1:n>=t[1]&&n<t[2]}function fs(e,t){for(let n=0;n<t.length;n++)if(ui(e,t[n]))return n;return-1}function gs(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=jl(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,c)=>c+s,0);(i<.99||i>1.01)&&(n=r);let a=0,o=t;return n.map(s=>{let c=a;return a+=s,[c,c+o*s]})}function hs(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let i=r.replace(/#.*/,"").split("&").map(a=>a.split("=",2)).filter(([a])=>a===e).map(([,a])=>parseInt(a));return i.length>0&&i[0]>=0&&i[0]<n?i[0]:null}function bs(e){try{return e()}catch{return!1}}function Yn(e){return typeof e=="string"?e:JSON.stringify(e)}function Et(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function ha(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function _s(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i=0;i<t.length;i++){let a=g_(e,t[i].type,t[i].pattern);if(t[i].include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function p_(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function f_(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,a)=>{r.push([e.searchParams.get(a)||"",i,!1])}),!r.some(i=>!p_(i[0],i[1],i[2]))}catch{return!1}}function g_(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=ha(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return f_(r,n);return!1}catch{return!1}}var Nl=new Map,ys=32,Dl=new WeakMap,Fl=new WeakMap,ba=e=>typeof e=="string"?e.toLowerCase():e;function ql(e){let t=Dl.get(e);return t||(t=new Set(e),Dl.set(e,t)),t}function h_(e){let t=Fl.get(e);return t||(t=new Set(e.map(ba)),Fl.set(e,t)),t}function Vl(e){for(let t of Object.values(e)){let n=Array.isArray(t)?t:t&&t.type==="list"&&Array.isArray(t.values)?t.values:null;n&&n.length>=ys&&ql(n)}return e}function Ft(e,t,n,r){n=n||{},r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Ll(e,a,n,r))return!1;break;case"$nor":if(Ll(e,a,n,r))return!1;break;case"$and":if(!x_(e,a,n,r))return!1;break;case"$not":if(Ft(e,a,n,r))return!1;break;case"$savedGroup":if(!b_(e,a,n,r))return!1;break;default:if(!li(a,$l(e,i),n,!1,r))return!1}return!0}function b_(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:a}=t;if(typeof i!="string"||r.has(i)||a!==void 0&&typeof a!="string")return!1;let o=n[i];if(!o||Array.isArray(o)||typeof o!="object")return!1;let s=new Set(r).add(i);if(o.type==="list"){let c=a??o.attributeKey;return typeof c!="string"||!Array.isArray(o.values)?!1:Jn($l(e,c),o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:Ft(e,o.condition,n,s):!1}function $l(e,t){let n=t.split("."),r=e;for(let i=0;i<n.length;i++)if(r&&typeof r=="object"&&n[i]in r)r=r[n[i]];else return null;return r}function Ul(e,t=!1){let n=`${e}${t?"/i":""}`,r=Nl.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Nl.set(n,r)),r}function li(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!Gl(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!S_(o,t,a[o],n,i))return!1;return!0}function Gl(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function __(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function y_(e,t,n,r){if(!Array.isArray(e))return!1;let i=Gl(t)?a=>li(t,a,n,!1,r):a=>Ft(a,t,n,r);for(let a=0;a<e.length;a++)if((e[a]??null)!==null&&i(e[a]))return!0;return!1}function Jn(e,t,n=!1){if(n){let i;if(t.length>=ys){let a=h_(t);i=o=>{let s=ba(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>ba(a)===ba(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=ys?(i=>a=>i.has(a))(ql(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Ml(e){return e===void 0?[]:Array.isArray(e)?e:e&&typeof e=="object"&&e.type==="list"&&Array.isArray(e.values)?e.values:null}function Bl(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let a=0;a<t.length;a++){let o=!1;for(let s=0;s<e.length;s++)if(li(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function S_(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return Et(t)===Et(n);case"$vne":return Et(t)!==Et(n);case"$vgt":return Et(t)>Et(n);case"$vgte":return Et(t)>=Et(n);case"$vlt":return Et(t)<Et(n);case"$vlte":return Et(t)<=Et(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return a<o;case"$lte":return a<=o;case"$gt":return a>o;case"$gte":return a>=o;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?Jn(t,n):!1;case"$ini":return Array.isArray(n)?Jn(t,n,!0):!1;case"$inGroup":{let s=Ml(r[n]);return s===null?!1:Jn(t,s)}case"$notInGroup":{let s=Ml(r[n]);return s===null?!1:!Jn(t,s)}case"$nin":return Array.isArray(n)?!Jn(t,n):!1;case"$nini":return Array.isArray(n)?!Jn(t,n,!0):!1;case"$not":return!li(n,t,r,!1,i);case"$size":return Array.isArray(t)?li(n,t.length,r,!1,i):!1;case"$elemMatch":return y_(t,n,r,i);case"$all":return Array.isArray(n)?Bl(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?Bl(t,n,r,!0,i):!1;case"$regex":try{return Ul(n).test(t)}catch{return!1}case"$regexi":try{return Ul(n,!0).test(t)}catch{return!1}case"$type":return __(t)===n;default:return!1}}function Ll(e,t,n,r){if(!t.length)return!0;for(let i=0;i<t.length;i++)if(Ft(e,t[i],n,r))return!0;return!1}function x_(e,t,n,r){for(let i=0;i<t.length;i++)if(!Ft(e,t[i],n,r))return!1;return!0}function Ss(e){return{context:e,stack:{evaluatedFeatures:new Set}}}function _a(e){return{...e.attributes,...e.attributeOverrides}}function Sn(e,t,n){let r=t||"id",i="",a=_a(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function we(e,t,n){e.context.log?.(t,n)}function di(e,t){return t=t||0,`${e}__${t}`}function ya(e,t){return`${e}||${t}`}function v_(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Sn(e,t),o=ya(i,Yn(a)),{hashAttribute:s,hashValue:c}=Sn(e,n),l=c?ya(s,Yn(c)):null,u={};return l&&r[l]&&Object.assign(u,r[l].assignments||{}),r[o]&&Object.assign(u,r[o].assignments||{}),u}function xs({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:a,expMeta:o}){n=n||0,a=a||0,r=r||"id",o=o||[];let s=di(t,n),c=v_(e,r,i);if(a>0)for(let d=0;d<a;d++){let m=di(t,d);if(c[m]!==void 0)return{variation:-1,versionIsBlocked:!0}}let l=c[s];if(l===void 0)return{variation:-1};let u=o.findIndex(d=>d.key===l);return u<0?{variation:-1}:{variation:u}}function vs(e,t,n,r){let i=ya(t,n),a=e.stickyBucketAssignmentDocs,o=a&&a[i]?a[i].assignments||{}:{},s={...o,...r},c=JSON.stringify(o)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:c}}function Kl(e,t){let n=Ss(t),r=zl(e,null,n);return t.onExperimentEval?.(e,r),r}function Hl(e,t){return As(e,Ss(t))}function I_(e){return e.forcedVariations||{}}function Wl(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=Yl(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Is(()=>r.onExperimentViewed?.(t,n))}function A_(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}Is(()=>r.onFeatureUsage?.(t,n))}function Is(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function As(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return we(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Rn(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.forcedFeatureValues;if(r&&r.has(e))return we(t,"Global override",{id:e,value:r.get(e)}),Rn(t,e,r.get(e),"override");if(!n.features||!n.features[e])return we(t,"Unknown feature",{id:e}),Rn(t,e,null,"unknownFeature");let i=n.features[e];if(i.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of i.rules){if(o.parentConditions)for(let l of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let u=As(l.id,t);if(u.source==="cyclicPrerequisite")return Rn(t,e,null,"cyclicPrerequisite");let d={value:u.value};if(!Ft(d,l.condition||{},n.savedGroups||{})){if(l.gate)return we(t,"Feature blocked by prerequisite",{id:e,rule:o}),Rn(t,e,null,"prerequisite");we(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Zl(o.filters,t)){we(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Ql(o.condition,t)){we(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!w_(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){we(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return we(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(l=>{Wl(t,l.experiment,l.result)}),Rn(t,e,o.force,"force",o.id)}if(!o.variations){we(t,"Skip invalid rule",{id:e,rule:o});continue}let s={variations:o.variations,key:o.key||e};"coverage"in o&&(s.coverage=o.coverage),o.weights&&(s.weights=o.weights),o.hashAttribute&&(s.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(s.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(s.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(s.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(s.minBucketVersion=o.minBucketVersion),o.namespace&&(s.namespace=o.namespace),o.meta&&(s.meta=o.meta),o.ranges&&(s.ranges=o.ranges),o.name&&(s.name=o.name),o.phase&&(s.phase=o.phase),o.seed&&(s.seed=o.seed),o.hashVersion&&(s.hashVersion=o.hashVersion),o.filters&&(s.filters=o.filters),o.condition&&(s.condition=o.condition);let c=zl(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Rn(t,e,c.value,"experiment",o.id,s,c)}}return we(t,"Use default value",{id:e,value:i.defaultValue}),Rn(t,e,i.defaultValue===void 0?null:i.defaultValue,"defaultValue")}function zl(e,t,n){let{context:r}=n,i=e.key,a=e.variations.length;if(a<2)return we(n,"Invalid experiment",{id:i}),Je(n,e,-1,!1,t);if(r.enabled===!1)return we(n,"Context disabled",{id:i}),Je(n,e,-1,!1,t);if(e=C_(e,r),e.urlPatterns&&!_s(r.url||"",e.urlPatterns))return we(n,"Skip because of url targeting",{id:i}),Je(n,e,-1,!1,t);let o=hs(i,r.url||"",a);if(o!==null)return we(n,"Force via querystring",{id:i,variation:o}),Je(n,e,o,!1,t);let s=I_(r);if(i in s){let h=s[i];return we(n,"Force via dev tools",{id:i,variation:h}),Je(n,e,h,!1,t)}if(e.status==="draft"||e.active===!1)return we(n,"Skip because inactive",{id:i}),Je(n,e,-1,!1,t);let{hashAttribute:c,hashValue:l}=Sn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return we(n,"Skip because missing hashAttribute",{id:i}),Je(n,e,-1,!1,t);let u=-1,d=!1,m=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:h,versionIsBlocked:x}=xs({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta});d=h>=0,u=h,m=!!x}if(!d){if(e.filters){if(Zl(e.filters,n))return we(n,"Skip because of filters",{id:i}),Je(n,e,-1,!1,t)}else if(e.namespace&&!ps(l,e.namespace))return we(n,"Skip because of namespace",{id:i}),Je(n,e,-1,!1,t);if(e.include&&!bs(e.include))return we(n,"Skip because of include function",{id:i}),Je(n,e,-1,!1,t);if(e.condition&&!Ql(e.condition,n))return we(n,"Skip because of condition exp",{id:i}),Je(n,e,-1,!1,t);if(e.parentConditions){let h=new Set(n.stack.evaluatedFeatures);for(let x of e.parentConditions){n.stack.evaluatedFeatures=new Set(h);let I=As(x.id,n);if(I.source==="cyclicPrerequisite")return Je(n,e,-1,!1,t);let S={value:I.value};if(!Ft(S,x.condition||{},r.savedGroups||{}))return we(n,"Skip because prerequisite evaluation fails",{id:i}),Je(n,e,-1,!1,t)}}if(e.groups&&!O_(e.groups,r))return we(n,"Skip because of groups",{id:i}),Je(n,e,-1,!1,t)}if(e.url&&!P_(e.url,r))return we(n,"Skip because of url",{id:i}),Je(n,e,-1,!1,t);let g=xr(e.seed||i,l,e.hashVersion||1);if(g===null)return we(n,"Skip because of invalid hash version",{id:i}),Je(n,e,-1,!1,t);if(!d){let h=e.ranges||gs(a,e.coverage===void 0?1:e.coverage,e.weights);u=fs(g,h)}if(m)return we(n,"Skip because sticky bucket version is blocked",{id:i}),Je(n,e,-1,!1,t,void 0,!0);if(u<0)return we(n,"Skip because of coverage",{id:i}),Je(n,e,-1,!1,t);if("force"in e)return we(n,"Force variation",{id:i,variation:e.force}),Je(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return we(n,"Skip because QA mode",{id:i}),Je(n,e,-1,!1,t);if(e.status==="stopped")return we(n,"Skip because stopped",{id:i}),Je(n,e,-1,!1,t);let f=Je(n,e,u,!0,t,g,d);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:h,key:x,doc:I}=vs(r,c,Yn(l),{[di(e.key,e.bucketVersion)]:f.key});if(h){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[x]=I;let S=r.saveStickyBucketAssignmentDoc;Is(()=>S(I))}}return Wl(n,e,f),we(n,"In experiment",{id:i,variation:f.variationId}),f}function Rn(e,t,n,r,i,a,o){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return a&&(s.experiment=a),o&&(s.experimentResult=o),r!=="override"&&A_(e,t,s),s}function Ql(e,t){return Ft(_a(t.context),e,t.context.savedGroups||{})}function Zl(e,t){return e.some(n=>{let{hashValue:r}=Sn(t.context,n.attribute);if(!r)return!0;let i=xr(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>ui(i,a))})}function w_(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Sn(e.context,n,r);if(!s)return!1;let c=xr(t,s,o||1);return c===null?!1:i?ui(c,i):a!==void 0?c<=a:!0}function Je(e,t,n,r,i,a,o){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:l}=Sn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),u=t.meta?t.meta[n]:{},d={key:u.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:t.variations[n],hashAttribute:c,hashValue:l,stickyBucketUsed:!!o};return u.name&&(d.name=u.name),a!==void 0&&(d.bucket=a),u.passthrough&&(d.passthrough=u.passthrough),d}function C_(e,t){let n=e.key,r=t.overrides;if(r&&r[n]){let i=Object.assign({},e,r[n]);typeof i.url=="string"&&(i.url=ha(i.url)),e=i}return e}function P_(e,t){let n=t.url;if(!n)return!1;let r=n.replace(/^https?:\/\//,"").replace(/^[^/]*\//,"/");return!!(e.test(n)||e.test(r))}function O_(e,t){let n=t.groups||{};for(let r=0;r<e.length;r++)if(n[e[r]])return!0;return!1}function Yl(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
|
|
2
|
+
Copyright (c) 2025 GrowthBook, Inc.
|
|
3
|
+
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
|
|
5
|
+
furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all
|
|
8
|
+
copies or substantial portions of the Software.
|
|
9
|
+
|
|
10
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
11
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
12
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
13
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
14
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
15
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
16
|
+
SOFTWARE.
|
|
17
|
+
*/var Oe=w.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>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(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),Jt=w.record(w.string().min(1).max(128),Oe).superRefine((e,t)=>{(!Oe.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"})}),E_=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"]),yt=Jt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!w.strictObject({id:w.uuid(),attributeKey:w.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!E_.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}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)}),Sa=w.discriminatedUnion("type",[w.strictObject({type:w.literal("condition"),condition:yt}),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 mi(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var k_=w.record(w.uuid(),Sa).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&mi(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Cs=w.tuple([w.number().min(0).max(1),w.number().min(0).max(1)]).refine(([e,t])=>e<=t),Jl=w.strictObject({attribute:w.string().optional(),seed:w.string().min(1),hashVersion:w.literal(2),ranges:w.array(Cs).min(1).max(100)}),T_=w.strictObject({id:w.string().min(1).max(128),condition:yt,gate:w.boolean().optional()}),ws={id:w.string().max(128).optional(),condition:yt.optional(),parentConditions:w.array(T_).max(50).optional(),filters:w.array(Jl).max(20).optional()},R_=w.union([w.strictObject({...ws}),w.strictObject({...ws,force:Oe,coverage:w.number().min(0).max(1).optional(),range:Cs.optional(),seed:w.string().min(1).optional(),hashAttribute:w.string().optional(),hashVersion:w.literal(2).optional()}),w.strictObject({...ws,type:w.literal("experiment-ref"),experimentId:w.uuid(),values:w.record(w.string().min(1),Oe),meta:w.record(w.string().min(1),w.strictObject({passthrough:w.boolean()})).optional()})]),j_=w.strictObject({defaultValue:Oe,rules:w.array(R_).max(100)}),Xl=w.record(w.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),j_).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(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),N_=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:yt,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(Cs).min(1)}).nullable(),seed:w.string().min(1).max(128)}),vr=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(N_).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],a,o)=>r>=i||o.some(([s,c],l)=>l!==a&&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 MP(e,t,n=Date.now()){return Object.fromEntries(Object.entries(e).map(([r,i])=>[r,{defaultValue:i.defaultValue,rules:i.rules.flatMap(a=>{if(!("experimentId"in a))return[{...a,hashVersion:2}];let o=t[a.experimentId];if(!o)throw new Error(`Missing experiment: ${a.experimentId}`);let s=o.phases[o.phases.length-1],c=o.statusSchedule?.startAt?Date.parse(o.statusSchedule.startAt):null,l=ed(o),u=o.status!=="stopped"&&(o.status==="running"||c!==null&&n>=c)&&(c===null||n>=c)&&(l===null||n<l),{type:d,experimentId:m,values:g,meta:f,...h}=a;if(o.variations.some(S=>!Object.hasOwn(g,S.key))||Object.keys(g).length!==o.variations.length||Object.keys(f??{}).some(S=>!o.variations.some(T=>T.key===S)))throw new Error("Every variation needs a Feature value");let x={$and:[s.condition,...h.condition?[h.condition]:[],...s.savedGroups.map(S=>{let T=S.ids.map(D=>({$savedGroup:{id:D}}));return S.match==="all"?{$and:T}:S.match==="none"?{$nor:T}:{$or:T}})]},I=o.variations.find(S=>S.id===o.releasedVariationId);return I&&!o.excludeFromPayload?f?.[I.key]?.passthrough?[{...h,condition:x}]:[{...h,condition:x,force:g[I.key]}]:[{...h,condition:x,key:o.key,variations:o.variations.map(S=>g[S.key]),meta:o.variations.map(S=>({key:S.key,name:S.name,...f?.[S.key]})),weights:s.variationWeights,coverage:u?s.coverage:0,seed:s.seed,hashVersion:2,hashAttribute:o.hashAttribute,fallbackAttribute:o.fallbackAttribute??void 0,disableStickyBucketing:!u||o.disableStickyBucketing,bucketVersion:o.bucketVersion,minBucketVersion:o.minBucketVersion,filters:[...h.filters??[],...o.filters??[]]}]})}]))}function ed(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 BP(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,ed(r)]).filter(r=>r!==null&&r>t);return n.length?new Date(Math.min(...n)).toISOString():null}var D_=vr.safeExtend({filters:w.array(Jl).optional()}),F_=w.strictObject({experiments:w.record(w.uuid(),D_),savedGroups:k_}),U_=w.strictObject({attributeName:w.string(),attributeValue:w.string(),assignments:w.record(w.string(),w.string())}),LP=w.strictObject({snapshot:F_,attributes:Jt,results:Jt,stickyBucketAssignmentDocs:w.record(w.string(),U_)}),qP=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 M_}from"zod";var nd=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,xn=M_.string().max(16).regex(nd,"\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),a=[n,r,i].filter(Boolean).join("-");return nd.test(a)?a:null}catch{return null}}var B_=new Set(["TW","HK","MO"]);function td(e){let[t,n,r]=e.split("-");if(t!=="zh")return`${t}-${new Intl.Locale(e).maximize().script??""}`;let i=n?.length===4?n:void 0,a=n?.length===4?r:n;return i?`zh-${i}`:a&&B_.has(a)?"zh-Hant":"zh-Hans"}function xa(e,t,n){let r=t.map(i=>({code:xn.parse(i),normalized:i}));for(let i of e){let a=Xn(i);if(!a)continue;let o=r.find(l=>l.normalized===a);if(o)return o.code;let s=td(a),c=r.filter(l=>td(l.normalized)===s);if(c.length>0)return(c.find(l=>!l.normalized.includes("-")||l.normalized===s)??c[0]).code}return n}var L_=[{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 GP(e){return L_.find(t=>t.code===e)?.label??e}var Ps={"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"}},zP=["zh-CN","zh-TW","zh-HK","en","ja","ko","es","fr","de","pt-BR","it","ru","vi","th","id","ar"];function Os(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 Ps[r]?{locale:t,copy:Ps[r]}:{locale:"en",copy:Ps.en}}function q_(e,t,n="zh-CN"){let r=Zn(t);return xl(e,t,Os(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function V_(e,t="zh-CN"){let n=Os(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e.percentOff/100):q_(e.amountOffCents,e.currency,n)}var rd={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 id(e,t="zh-CN",n="month"){let r=Os(t),i=V_(e.discount,r.locale),a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",o=r.locale.split("-")[0],s=o==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":o,c=e.duration.type==="repeating"&&n!=="month"?rd[s]??rd.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],l=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return c.replace("{discount}",i).replace("{months}",a).replace("{period}",l)}var eO=oe.enum(["draft","active","paused","archived"]),Ir=oe.discriminatedUnion("type",[oe.object({type:oe.literal("percent"),percentOff:oe.number().int().min(1).max(100)}).strict(),oe.object({type:oe.literal("amount"),amountOffCents:oe.number().int().min(1).max(1e8),currency:z}).strict()]),Xt=oe.discriminatedUnion("type",[oe.object({type:oe.literal("once")}).strict(),oe.object({type:oe.literal("repeating"),months:oe.number().int().min(1).max(36)}).strict(),oe.object({type:oe.literal("forever")}).strict()]),ad=oe.discriminatedUnion("type",[oe.object({type:oe.literal("all")}).strict(),oe.object({type:oe.literal("plans"),planIds:oe.array(oe.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),$_=oe.strictObject({firstPurchaseOnly:oe.boolean(),condition:yt}),od=oe.object({name:oe.string().trim().min(1).max(80),description:oe.string().max(500),discount:Ir,duration:Xt,appliesTo:ad,eligibility:$_,startsAt:oe.iso.datetime().nullable(),endsAt:oe.iso.datetime().nullable(),totalLimit:oe.number().int().min(1).max(1e6).nullable(),perCustomerLimit:oe.number().int().min(1).max(10),grantWindowHours:oe.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"]}),tO=oe.object({code:oe.string().trim().transform(e=>e.toUpperCase()).pipe(oe.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:oe.number().int().min(1).max(1e6).nullable(),expiresAt:oe.iso.datetime().nullable(),firstPurchaseOnly:oe.boolean(),minimumAmountCents:oe.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:z.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function nO(){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 Es=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function rO(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return Es(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),Es(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),Es(t.appliesTo,n.appliesTo)||r.push({field:"appliesTo",reason:"immutable"}),t.startsAt!==n.startsAt&&r.push({field:"startsAt",reason:"immutable"}),t.endsAt!==n.endsAt&&(n.endsAt===null||t.endsAt!==null&&Date.parse(n.endsAt)>Date.parse(t.endsAt))&&r.push({field:"endsAt",reason:"only_earlier"}),t.totalLimit!==n.totalLimit&&(n.totalLimit===null||t.totalLimit!==null&&n.totalLimit>t.totalLimit)&&r.push({field:"totalLimit",reason:"only_reduce"}),n.perCustomerLimit>t.perCustomerLimit&&r.push({field:"perCustomerLimit",reason:"only_reduce"}),r}var G_=e=>`$${(e/100).toFixed(e%100===0?0:2)}`;function iO(e,t="zh-CN"){return id(e,t)}function aO(e){return G_(e)}function oO(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var ks=oe.object({id:oe.uuid(),couponId:oe.uuid(),status:oe.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:oe.iso.datetime(),expiresAt:oe.iso.datetime(),coupon:oe.object({name:oe.string(),discount:Ir,duration:Xt,appliesTo:ad}).strict()}).strict(),va=oe.enum(["inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var dd=b.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),pi=b.string().regex(/^(0|[1-9]\d{0,14})$/),Ar=b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),K_=b.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),fi=K_,vn=Y.refine(e=>/[1-9]/.test(e)),St=b.iso.datetime({offset:!0}),er=e=>{let[t,n=""]=e.split(".");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},H_=b.array(b.object({upTo:vn.nullable(),unitAmountMinor:dd,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"),W_=b.discriminatedUnion("kind",[b.object({kind:b.literal("flat"),units:vn,unitAmountMinor:dd}).strict(),b.object({kind:b.enum(["graduated","volume"]),units:vn,tiers:H_}).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"),z_=b.strictObject({interval:b.enum(["month","year"]),count:b.number().int().min(1).max(12),anchor:b.enum(["membership","calendar"])}),jn=b.object({currency:z,pricing:W_,billingCycle:z_.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function md(e){return e.pricing.kind==="flat"&&er(e.pricing.units)>0n&&er(e.pricing.unitAmountMinor)===er(e.pricing.units)*BigInt(10**Zn(e.currency))}var sd={requestId:b.uuid(),productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:z},pd=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)}),fd=b.discriminatedUnion("kind",[b.object({...sd,kind:b.literal("auto_topup"),threshold:fa,quantity:vn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:pd.optional()}).strict(),b.object({...sd,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:fi,maxOutstandingMinor:fi}).strict()]),cd={productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:z},gd=b.discriminatedUnion("kind",[b.object({...cd,kind:b.literal("auto_topup"),threshold:fa,quantity:vn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:pd.optional(),purchaseAmountMinor:fi,purchaseUnits:vn}).strict(),b.object({...cd,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:fi,maxOutstandingMinor:fi,cashPrice:jn}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Ia=b.object({id:b.uuid(),terms:gd,status:b.enum(["prepared","active","revoked","blocked"]),createdAt:St,acceptedAt:St.nullable(),effectiveAt:St.nullable(),revokedAt:St.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"),hd=b.object({authorizationId:b.uuid(),terms:gd,setupUrl:b.url().nullable()}).strict(),bd=b.object({authorizationId:b.uuid(),accepted:b.literal(!0)}).strict(),_d=b.object({authorizationId:b.uuid(),requestId:b.uuid()}).strict(),yd=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),basis:b.enum(["usage","credits"]),filter:Ye.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(vn).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"),Q_=yd.safeExtend({requestId:b.uuid()}),ud={control:b.literal("overage"),requestId:b.uuid(),internal_feature_id:b.uuid(),entityId:b.uuid().nullable()},Z_=b.discriminatedUnion("action",[b.strictObject({...ud,action:b.literal("set"),allowed:b.boolean().nullable(),overageLimit:Y.nullable(),skipOverageBilling:b.boolean()}),b.strictObject({...ud,action:b.literal("remove")})]),Sd=b.union([Q_,Z_]),Y_=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:St,endsAt:St,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()}),J_=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),basis:b.enum(["usage","credits"]),filter:Ye.optional(),startsAt:St,endsAt:St,used:ct,reserved:ct,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(vn).max(8).optional(),notifiedAbsoluteThresholds:b.array(vn).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"),X_=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:St.nullable(),attemptCount:b.number().int().nonnegative(),failedAttemptCount:b.number().int().nonnegative(),suspendedAt:St.nullable(),nextAttemptAt:St.nullable(),failureReason:b.string().min(1).max(240).nullable()}).strict(),xd=b.object({internal_feature_id:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),Ts=b.object({authorizations:b.array(Ia).max(100),limits:b.array(yd).max(100),overages:b.array(Y_).max(100).optional(),windows:b.array(J_).max(200),autoTopups:b.array(X_).max(100),limited:b.boolean()}).strict(),ey=b.object({id:b.uuid(),internal_feature_id:b.uuid(),productVersionId:b.uuid(),authorizationId:b.uuid(),entityId:b.uuid().nullable(),units:Y,amountMinor:Ar,cashPrice:jn}).strict(),gi=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:z,startsAt:St.nullable(),endsAt:St.nullable(),amountMinor:pi,grossAmountMinor:pi,discountMinor:pi,paidAmountMinor:pi,refundedAmountMinor:pi,createdAt:St,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:St.nullable()}).strict().nullable(),lines:b.array(ey).max(100),linesLimited:b.boolean()}).strict(),vd=b.object({invoiceId:b.uuid(),accepted:b.literal(!0)}).strict(),Id=b.object({after:b.uuid().nullable(),limit:b.number().int().min(1).max(100)}).strict(),Ad=b.object({rows:b.array(gi).max(100),nextCursor:b.uuid().nullable()}).strict(),ld=b.strictObject({id:b.string(),coupon:b.string(),start:b.number().nonnegative(),end:b.number().nullable()}),ty=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(ld).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:ld.optional()})).max(20)})).max(100)}),wd=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")}),Cd=b.strictObject({membershipId:b.uuid(),operationId:b.uuid(),status:b.enum(["pending","effective"]),execution:ty.nullable(),grants:b.array(b.strictObject({id:b.uuid(),couponId:b.uuid(),name:b.string(),discount:Ir,duration:Xt,startedAt:St.nullable()})).max(20)});import{z as hi}from"zod";var bi=hi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),_i=hi.number().int().min(1).max(1e3),tr=hi.object({cap:Y.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:hi.number().positive().max(1e4).nullable(),cycles:hi.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var Rs={key:dn,name:N.string().trim().min(1).max(80),description:N.string().trim().max(240)},Pd=Y.refine(e=>/[1-9]/.test(e)),Aa=N.array(N.object({currency:z,amountMinor:N.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"),js=N.strictObject({units:Pd,prices:N.array(N.strictObject({currency:z,amountMinor:N.number().int().min(0).max(1e8),pricing:ci.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:N.number().int().min(0).max(1e4),maximumQuantity:N.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"),ny=N.discriminatedUnion("kind",[N.object({kind:N.literal("access"),internal_feature_id:N.uuid()}).strict(),N.object({kind:N.literal("metered"),internal_feature_id:N.uuid(),usageUnit:N.enum(["count","micro_usd"]),amount:Y.nullable(),reset:bi,resetCount:_i,pooled:N.boolean(),rollover:tr.nullable().optional(),cashPrice:jn.nullable().optional(),prepaidPrice:js.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 Ds(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),N.object({kind:N.literal("credit"),internal_feature_id:N.uuid(),amount:Y,reset:bi,resetCount:_i,rollover:tr.nullable(),pooled:N.boolean(),feature_override:ts.nullish(),cashPrice:jn.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&md(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")]),Ns=N.array(ny).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),Od=N.object({days:N.number().int().min(1).max(730),cardRequired:N.boolean(),allowances:Ns}).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"),Ed=N.object({key:dn,internal_feature_id:N.uuid(),productVersionId:N.uuid(),includedQuantity:N.number().int().min(0).max(1e4),maximumQuantity:N.number().int().min(0).max(1e4),prices:Aa,pooled_internal_feature_ids:N.array(N.uuid()).max(100),requireAssignment:N.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"),yi=N.discriminatedUnion("kind",[N.object({...Rs,kind:N.literal("membership"),groupId:N.uuid(),membershipType:N.enum(["main","addon"]),interval:N.enum(["free","week","month","year","one_time"]),intervalCount:N.number().int().min(1).max(156).optional(),prices:Aa,allowances:Ns,trial:Od.nullable(),licenses:N.array(Ed).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"),N.object({...Rs,kind:N.literal("topup"),interval:N.literal("one_time"),prices:Aa,internal_feature_id:N.uuid(),amount:Pd,expiresDays:N.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),wa=N.object({interval:N.enum(["free","week","month","year","one_time"]).optional(),intervalCount:N.number().int().min(1).max(156).nullable().optional(),prices:Aa.optional(),allowances:N.object({upsert:Ns,remove:N.array(N.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:Od.nullable().optional(),licenses:N.array(Ed).max(20).optional()}).strict(),kd=N.object({...Rs,kind:N.literal("variant"),baseProductVersionId:N.uuid(),overrides:wa}).strict(),wO=N.union([yi,kd]);function CO(e,t){let n=kd.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...a}=n.overrides,o=new Map(e.allowances.map(c=>[c.internal_feature_id,c]));for(let c of r?.remove??[])if(!o.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])o.delete(c.internal_feature_id);for(let c of r?.upsert??[])o.set(c.internal_feature_id,c);let s={...structuredClone(e),...structuredClone(a),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...o.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),yi.parse(s)}function PO(e,t){if(e.kind!=="membership"||t.kind!=="membership"||e.groupId!==t.groupId||e.membershipType!==t.membershipType)throw new Error("Variant group and membership type must match the base");let n={};for(let s of["interval","intervalCount","prices","trial","licenses"])(s==="intervalCount"&&["week","month","year"].includes(t.interval)?(e.intervalCount??1)===(t.intervalCount??1):JSON.stringify(e[s])===JSON.stringify(t[s]))||Object.assign(n,{[s]:s==="intervalCount"&&t[s]===void 0?null:structuredClone(t[s])});let r=new Map(e.allowances.map(s=>[s.internal_feature_id,s])),i=new Set(t.allowances.map(s=>s.internal_feature_id)),a=t.allowances.filter(s=>JSON.stringify(r.get(s.internal_feature_id))!==JSON.stringify(s)),o=e.allowances.filter(s=>!i.has(s.internal_feature_id)).map(s=>s.internal_feature_id);return(a.length||o.length)&&(n.allowances={upsert:a,remove:o}),wa.parse(n)}var OO=N.object({products:N.array(N.object({id:N.uuid(),productId:N.string().min(1),name:N.string(),kind:N.enum(["membership","topup"]),version:N.number().int().positive()}).strict()).max(500),limited:N.boolean()}).strict(),ry=sl.and(N.object({internal_id:N.uuid(),revision:N.number().int().nonnegative(),licenses:N.array(Jo)})),EO=N.strictObject({rows:N.array(ry).max(200),nextCursor:N.uuid().nullable()}),kO=N.object({groups:N.array(N.object({id:N.uuid(),name:N.string(),defaultProductVersionId:N.uuid().nullable()}).strict()).max(500),features:yl.shape.features,products:N.array(N.object({id:N.uuid(),productId:N.uuid(),version:N.number().int().positive(),configuration:yi,baseProductVersionId:N.uuid().nullable()}).strict()).max(500),limited:N.boolean()}).strict();function Ds(e,t,n){let r=o=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(o))throw new Error("Invalid quantity");let[s,c=""]=o.split(".");return BigInt(s)*1000000n+BigInt(c.padEnd(6,"0"))};if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let i=r(e)+r(t)*BigInt(n);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let a=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(a?"."+a:"")}var NO=en.object({requestId:en.uuid(),baseProductVersionId:en.uuid(),name:en.string().trim().min(1).max(80),description:en.string().trim().max(240),overrides:wa}).strict(),DO=en.object({productId:en.uuid(),productVersionId:en.uuid(),bindingStatus:en.enum(["ready","requires_binding"]),missingCurrencies:en.array(en.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();import{z as Re}from"zod";var iy=Re.object({minAccountAgeDays:Re.number().int().min(0).max(3650),paymentStatus:Re.enum(["all","unpaid","paid"])}),ay=Re.object({percentOff:Re.number().int().min(1).max(100),redemptionWindowHours:Re.number().int().min(1).max(2160)}),oy=Re.object({title:Re.string().trim().min(1).max(80),description:Re.string().trim().min(1).max(240),buttonLabel:Re.string().trim().min(1).max(30)}),sy=Re.object({name:Re.string().trim().min(1).max(80),audience:iy,offer:ay,popup:oy}),BO=sy.extend({id:Re.string().min(1),projectId:Re.string().min(1),environment:ds,status:Re.enum(["draft","active","paused"]),updatedAt:Re.iso.datetime()}),LO=Ue.extend({id:Re.string().min(1),externalUserId:Re.string().min(1),name:Re.string().min(1),email:Re.union([Re.email(),Re.literal("")]),createdAt:Re.iso.datetime(),paymentStatus:Re.enum(["unpaid","paid"]),stripeCustomerId:Re.string().nullable()}),qO=Re.object({error:Re.object({code:Re.string(),message:Re.string()})});import{z as Nn}from"zod";var Td=Nn.strictObject({itemKey:Nn.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:Nn.uuid(),includedAmount:Nn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Nn.number().int().min(0).max(1e4),terms:js,pricing:ci.optional(),unitAmountMinor:Nn.number().int().min(0).max(1e8),productId:Nn.string().min(1).max(255).nullable(),priceId:Nn.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{Ds(e.includedAmount,e.terms.units,e.quantity),pa(e)}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as K}from"zod";var Fs=K.object({id:K.uuid(),productVersionId:K.uuid(),connectionId:K.uuid(),currency:K.string().regex(/^[A-Z]{3}$/),productId:K.string().min(1).max(255),priceId:K.string().min(1).max(255),enabled:K.boolean()}).strict(),QO=K.object({productId:K.uuid(),name:K.string(),environment:K.enum(["sandbox","live"]),versions:K.array(K.object({id:K.uuid(),version:K.number().int().positive(),configuration:yi}).strict()),connections:K.array(K.object({id:K.uuid(),accountId:K.string()}).strict()),bindings:K.array(Fs),seatBindings:K.array(Fs.extend({key:K.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:K.array(Fs.extend({internal_feature_id:K.uuid()}).strict()),limited:K.boolean()}).strict(),ZO=K.discriminatedUnion("action",[K.strictObject({action:K.literal("bind_feature"),requestId:K.uuid(),productId:K.uuid(),productVersionId:K.uuid(),connectionId:K.uuid(),currency:K.string().regex(/^[A-Z]{3}$/),internal_feature_id:K.uuid(),priceId:K.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}),K.strictObject({action:K.literal("disable_feature"),productId:K.uuid(),bindingId:K.uuid()}),K.object({action:K.literal("bind_seat"),requestId:K.uuid(),productId:K.uuid(),productVersionId:K.uuid(),connectionId:K.uuid(),currency:K.string().regex(/^[A-Z]{3}$/),key:K.string().regex(/^[a-z][a-z0-9_]{0,63}$/),priceId:K.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),K.object({action:K.literal("disable_seat"),productId:K.uuid(),bindingId:K.uuid()}).strict(),K.object({action:K.literal("bind"),requestId:K.uuid(),productId:K.uuid(),productVersionId:K.uuid(),connectionId:K.uuid(),currency:K.string().regex(/^[A-Z]{3}$/),priceId:K.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),K.object({action:K.literal("disable"),productId:K.uuid(),bindingId:K.uuid()}).strict()]);import{z as he}from"zod";var Rd=he.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),jd=he.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Si=he.enum(["apple","google"]),cy=he.strictObject({id:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:Si,provider:Si,namespace:he.string().min(1).max(255),currency:z,productId:Rd,basePlanId:jd.nullable(),enabled:he.boolean()}),eE=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:z,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(cy).max(500),limited:he.boolean()}),tE=he.discriminatedUnion("action",[he.strictObject({action:he.literal("bind"),requestId:he.uuid(),productId:he.uuid(),productVersionId:he.uuid(),priceId:he.uuid(),connectionId:Si,storeProductId:Rd,basePlanId:jd.nullable()}),he.strictObject({action:he.literal("disable"),productId:he.uuid(),bindingId:he.uuid()})]);import{z as $}from"zod";var nr=Y.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),xi=$.string().min(1).max(120),Ca=$.enum(["cap","overflow"]),Ut=(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=$.discriminatedUnion("operation",[$.object({operation:$.literal("quote"),overageBehavior:Ca.optional(),internal_feature_id:$.uuid(),entityId:$.uuid().optional(),quantity:nr,properties:Ye}).strict(),$.object({operation:$.literal("consume"),overageBehavior:Ca.optional(),occurredAt:$.iso.datetime({offset:!0}).optional(),internal_feature_id:$.uuid(),entityId:$.uuid().optional(),quantity:Y,properties:Ye,idempotencyKey:xi}).strict(),$.object({operation:$.literal("reserve"),occurredAt:$.iso.datetime({offset:!0}).optional(),internal_feature_id:$.uuid(),entityId:$.uuid().optional(),quantity:nr,properties:Ye,idempotencyKey:xi,expiresInSeconds:$.number().int().min(1).max(86400)}).strict(),$.object({operation:$.literal("confirm"),operationId:$.uuid(),quantity:nr,properties:Ye.optional(),idempotencyKey:xi}).strict(),$.object({operation:$.literal("refund"),operationId:$.uuid(),quantity:nr,idempotencyKey:xi}).strict(),$.object({operation:$.literal("release"),operationId:$.uuid(),idempotencyKey:xi}).strict()]),Us=$.object({internal_credit_feature_id:$.uuid().nullable(),internal_metered_feature_id:$.uuid(),dimension:$.string().min(1).max(64),counterKey:$.string().min(1).max(240),cycleStart:$.iso.datetime({offset:!0}),unitCost:Y,units:nr,amount:ct,tier:$.number().int().min(1).max(12).nullable()}).strict(),rr=$.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Nd(e,t){let n=e.reduce((r,i)=>r+Ut(i.units,12),0n)-Ut(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var Dd=$.discriminatedUnion("funding",[$.strictObject({funding:$.literal("balance"),sourceId:$.uuid(),rolloverId:$.uuid().nullable(),units:rr.refine(e=>/[1-9]/.test(e)),amount:ct}),$.strictObject({funding:$.literal("unbilled"),units:rr.refine(e=>/[1-9]/.test(e))}),$.object({funding:$.literal("prepaid"),sourceId:$.uuid(),units:nr,amount:ct,pricing:$.array(Us).min(1).max(12)}).strict().refine(e=>vi(()=>e.pricing.reduce((t,n)=>t+Ut(n.units,6),0n)===Ut(e.units,6)&&e.pricing.reduce((t,n)=>t+Ut(n.amount,12),0n)===Ut(e.amount,12)&&e.pricing.every(t=>Ut(t.unitCost,6)*Ut(t.units,6)===Ut(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),$.object({funding:$.literal("postpaid"),invoiceLineId:$.uuid().nullable(),units:nr,authorizationId:$.uuid()}).strict()]),Pa=$.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Fd=$.object({allowed:$.boolean(),internal_feature_id:$.uuid(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:Ca.optional(),reason:Pa.nullable(),allocations:$.array(Dd).max(500)}).strict().refine(e=>vi(()=>e.allowed?e.reason===null&&Nd(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&&Ut(e.requestedQuantity,6)>=Ut(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Ai=$.object({id:$.uuid(),internal_feature_id:$.uuid(),kind:$.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:$.uuid().nullable(),quantity:Y,requestedQuantity:Y.optional(),overageBehavior:Ca.optional(),accepted:$.boolean(),reason:$.enum([...Pa.options,"expired"]).nullable(),createdAt:$.iso.datetime({offset:!0}),reservationStatus:$.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:$.iso.datetime({offset:!0}).nullable(),allocations:$.array(Dd).max(500)}).strict().refine(e=>vi(()=>e.accepted?e.reason===null&&Nd(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&&Ut(e.requestedQuantity,6)>=Ut(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as ye}from"zod";var ir=ye.iso.datetime({offset:!0}),Ud=Y.refine(e=>/[1-9]/.test(e)),Md=ye.strictObject({interval:bi.exclude(["lifetime"]),count:_i}),uy=ye.strictObject({action:ye.literal("create"),requestId:ye.uuid(),internal_feature_id:ye.uuid(),entityId:ye.uuid().nullable(),amount:Ud.nullable(),expiresAt:ir.nullable(),reset:Md.nullable(),rollover:tr.nullable(),nextResetAt:ir.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"),Bd=ye.discriminatedUnion("action",[uy,ye.strictObject({action:ye.literal("update"),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative(),amount:Ud.nullable(),expiresAt:ir.nullable(),rollover:tr.nullable(),nextResetAt:ir.nullable()}),ye.strictObject({action:ye.enum(["add","subtract","set_remaining"]),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative(),amount:Y}),ye.strictObject({action:ye.literal("revoke"),requestId:ye.uuid(),grantId:ye.uuid(),revision:ye.number().int().nonnegative()})]),Ms=ye.strictObject({id:ye.uuid(),internal_feature_id:ye.uuid(),entityId:ye.uuid().nullable(),amount:Y.nullable(),reset:Md.nullable(),rollover:tr.nullable(),nextResetAt:ir.nullable(),startsAt:ir,expiresAt:ir.nullable(),revision:ye.number().int().nonnegative(),revoked:ye.boolean(),available:ct,held:ct,spent:ct}),Ld=ye.strictObject({customerId:ye.uuid(),after:ye.uuid().nullable(),limit:ye.number().int().min(1).max(100)}),qd=ye.strictObject({rows:ye.array(Ms).max(100),nextCursor:ye.uuid().nullable()});import{z as W}from"zod";var mn=W.iso.datetime({offset:!0}),Vd=W.strictObject({invoiceId:W.uuid(),after:W.string().min(1).max(180).nullable(),limit:W.number().int().min(1).max(100)}),ly=W.strictObject({kind:W.literal("product"),key:W.string(),productVersionId:W.uuid(),productName:W.string(),itemKey:W.string(),entityId:W.uuid().nullable(),quantity:W.number().int().positive(),subtotalMinor:W.string().regex(/^-?\d+$/),discountMinor:W.string().regex(/^\d+$/),taxMinor:W.string().regex(/^-?\d+$/).nullable(),totalMinor:W.string().regex(/^-?\d+$/),startsAt:mn.nullable(),endsAt:mn.nullable(),providerLineId:W.string().nullable(),providerItemId:W.string()}),$d=W.strictObject({invoice:gi,items:W.array(W.discriminatedUnion("kind",[ly,W.strictObject({kind:W.literal("invoice_credit"),key:W.string(),internal_feature_id:W.uuid(),internal_credit_feature_id:W.uuid(),name:W.string(),units:Y,reserved:Y,amountMinor:Ar,grossAmountMinor:Ar,creditsAppliedMinor:Ar,properties:Ye,cashPrice:jn,providerItemId:W.string().nullable(),creditProviderItemId:W.string().nullable()}),W.strictObject({kind:W.literal("usage"),key:W.string(),internal_feature_id:W.uuid(),name:W.string(),units:Y,reserved:Y,amountMinor:Ar,cashPrice:jn})])).max(100),nextCursor:W.string().min(1).max(180).nullable()}),dy=W.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Bs=W.strictObject({from:mn,to:mn,entityId:W.uuid().optional(),snapshotAt:mn.nullable(),after:W.strictObject({at:mn,id:W.uuid(),position:W.number().int().nonnegative()}).nullable(),limit:W.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),Gd=W.strictObject({customerId:W.uuid(),entityId:W.uuid().nullable(),from:mn,to:mn,snapshotAt:mn,totals:W.array(W.strictObject({internal_credit_feature_id:W.uuid(),name:W.string(),consumed:ct,refunded:ct,net:dy})).max(1e3),rows:W.array(W.strictObject({operationId:W.uuid(),position:W.number().int().nonnegative(),kind:W.enum(["consume","confirm","refund"]),originalId:W.uuid().nullable(),occurredAt:mn,internal_feature_id:W.uuid(),entitlementName:W.string(),sourceId:W.uuid(),internal_credit_feature_id:W.uuid(),creditName:W.string(),units:rr,amount:ct,pricing:W.array(Us).max(12),properties:Ye})).max(100),nextCursor:Bs.shape.after});import{z as Mt}from"zod";var bE=Mt.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"]),Kd=Mt.object({operationId:Mt.uuid(),windowId:Mt.uuid(),customerId:Mt.uuid(),entityId:Mt.uuid().nullable(),internal_feature_id:Mt.uuid(),entitlementKey:Yt,basis:Mt.enum(["usage","credits"]),interval:Mt.enum(["day","week","month","year"]),filter:Ye,startsAt:Mt.iso.datetime({offset:!0}),endsAt:Mt.iso.datetime({offset:!0}),limit:Y.refine(e=>/[1-9]/.test(e)),used:ct,reserved:ct,threshold:Mt.number().positive().max(1)}).strict(),_E=Kd.omit({threshold:!0,limit:!0}).extend({alertThreshold:Y.refine(e=>/[1-9]/.test(e)),limit:Y.nullable()}),yE=Kd.omit({limit:!0}).extend({includedAllowance:Mt.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z as C}from"zod";import{z as tn}from"zod";var my=tn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),py=tn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Oa=tn.strictObject({internal_feature_id:tn.uuid(),entityId:tn.uuid().nullable()}),Hd=Oa.extend({quantity:Y,expectedRevision:tn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:tn.string().min(1).max(120),properties:Ye.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),wi=Oa.extend({operationId:tn.uuid().nullable(),usage:Y,capacity:my.nullable(),remaining:py.nullable(),withinLimit:tn.boolean(),revision:tn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:tn.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Qe=C.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),nn=C.iso.datetime({offset:!0}),fy=C.enum(["access","metered","credit"]),Ci={internal_feature_id:C.uuid(),key:Yt,name:C.string().min(1).max(120),kind:fy},Wd=C.object({customerId:C.uuid(),snapshotAt:nn,memberships:C.array(C.object({id:C.uuid(),productId:C.string().min(1).max(255),productVersionId:C.uuid(),billingProductVersionId:C.uuid(),version:C.number().int().positive(),key:C.string().min(1).max(64),name:C.string().min(1).max(120),groupId:C.string().max(255).nullable(),membershipType:C.enum(["main","addon"]),status:C.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:C.boolean(),accessEnabled:C.boolean(),renewalChange:C.object({productVersionId:C.uuid(),name:C.string().min(1).max(120),version:C.number().int().positive(),effectiveAt:nn,benefitsAppliedAt:nn.nullable(),timing:C.enum(["immediate","renewal"]),changeKind:C.enum(["plan","seats","quantity"]),feature:C.strictObject({internal_feature_id:C.uuid(),name:C.string().min(1).max(80),fromQuantity:C.number().int().min(0).max(1e4),toQuantity:C.number().int().min(0).max(1e4)}).optional(),seat:C.object({key:C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:C.number().int().min(0).max(1e4),toQuantity:C.number().int().min(0).max(1e4)}).strict().nullable(),status:C.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:C.object({phase:C.enum(["paid","trial"]),startsAt:nn,endsAt:nn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:C.boolean(),balances:C.array(C.object({...Ci,usageType:C.enum(["consumable","non_consumable"]).nullable(),accessible:C.boolean(),unlimited:C.boolean(),available:Qe,held:Qe,debt:Qe,nextExpiresAt:nn.nullable(),usage:wi.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:C.boolean()}).strict(),zd=C.enum(["source","usage","transaction","invoice","debt","settlement"]),Ea=C.object({at:nn,id:C.uuid(),type:zd}).strict(),Qd=C.object({type:zd.nullable(),resourceKey:Yt.optional(),kind:C.enum(["purchase","refund"]).optional(),topup:C.boolean().optional(),from:C.iso.date().nullable(),to:C.iso.date().nullable(),after:Ea.nullable(),limit:C.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),wr={id:C.uuid(),occurredAt:nn},gy=C.discriminatedUnion("type",[C.strictObject({...wr,type:C.literal("invoice"),status:C.string().min(1).max(80),paid:Qe,refunded:Qe,currency:z,externalId:C.string().nullable()}),C.object({...wr,...Ci,type:C.literal("source"),reason:C.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Qe,unlimited:C.boolean(),status:C.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:nn,expiresAt:nn.nullable(),orderId:C.uuid().nullable(),parentSourceId:C.uuid().nullable()}).strict(),C.object({...wr,type:C.literal("usage"),internal_feature_id:C.uuid(),name:C.string().min(1).max(120),kind:C.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:C.uuid().nullable(),quantity:Y,accepted:C.boolean(),reason:C.enum([...Pa.options,"expired"]).nullable(),properties:Ye,reservationStatus:C.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:nn.nullable(),charges:C.array(C.discriminatedUnion("funding",[C.strictObject({funding:C.literal("balance"),sourceId:C.uuid(),rolloverId:C.uuid().nullable(),units:rr,amount:Qe}),C.strictObject({funding:C.literal("unbilled"),units:rr}),C.object({...Ci,funding:C.literal("prepaid"),amount:Qe}).strict(),C.object({funding:C.literal("postpaid"),invoiceId:C.uuid(),invoiceLineId:C.uuid(),authorizationId:C.uuid(),units:Y,currency:z}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),C.object({...wr,type:C.literal("transaction"),purpose:C.enum(["product","invoice"]),productVersionId:C.uuid().nullable(),productName:C.string().min(1).max(120).nullable(),productVersion:C.number().int().positive().nullable(),invoiceId:C.uuid().nullable(),orderId:C.uuid(),originalId:C.uuid().nullable(),kind:C.enum(["purchase","refund"]),amountMinor:C.number().int().nonnegative().max(2e8).nullable(),currency:z.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),C.object({...wr,...Ci,type:C.literal("debt"),sourceId:C.uuid(),transactionId:C.uuid(),amount:Qe}).strict(),C.object({...wr,...Ci,type:C.literal("settlement"),sourceId:C.uuid(),debtId:C.uuid(),kind:C.enum(["payment","usage_refund","payment_return"]),amount:Qe}).strict()]),Zd=C.object({customerId:C.uuid(),rows:C.array(gy).max(50),nextCursor:Ea.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as ee}from"zod";var Jd=ee.object({customerId:ee.uuid()}).strict(),Xd=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(),Ls=ee.iso.datetime({offset:!0}),qs=ee.strictObject({internalId:ee.uuid(),id:ee.string(),name:ee.string().nullable(),version:ee.number().int().positive()}),Yd=ee.enum(["active","past_due"]),Vs=ee.strictObject({customerId:ee.uuid(),licenses:ee.array(ee.strictObject({id:ee.uuid(),linkId:ee.uuid(),parent:ee.strictObject({customerProductId:ee.uuid(),status:Yd,product:qs}),product:qs,planLicense:ee.strictObject({id:ee.uuid(),prepaidOnly:ee.boolean(),isCustom:ee.boolean()}).nullable(),granted:Pi,included:Pi,paidQuantity:Pi,usage:Pi,remaining:Pi,createdAt:Ls}).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:Yd,product:qs,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:Ls.nullable(),endedAt:Ls.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:ee.boolean()});import{z as Dn}from"zod";var hy=Dn.object({name:Dn.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:Dn.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")}),em=Dn.object({description:Dn.string().trim().max(240)}),jE=Dn.object({project:hy.extend({id:Dn.string().min(1)}),environments:Dn.object({sandbox:em,live:em})});import{z as qe}from"zod";import{z as Pe}from"zod";import{z as Cr}from"zod";var tm=Cr.enum(["stripe","apple","google"]),nm=Cr.enum(["membership","credit_pack","lifetime"]),FE=Cr.enum(["active","grace","suspended","inactive","revoked"]),UE=Cr.strictObject({currency:Cr.string().regex(/^[A-Z]{3}$/),micros:Cr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});import{z as De}from"zod";var by=De.discriminatedUnion("action",[De.strictObject({action:De.literal("create"),couponId:De.uuid(),productBindingId:De.uuid(),storeOfferId:De.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:De.enum(["introductory","promotional"])}),De.strictObject({action:De.literal("set_enabled"),id:De.uuid(),revision:De.number().int().nonnegative(),enabled:De.boolean()})]),_y=De.array(De.strictObject({id:De.uuid(),couponId:De.uuid(),productBindingId:De.uuid(),storeOfferId:De.string().min(1).max(255).nullable(),storeOfferType:De.enum(["introductory","promotional"]),enabled:De.boolean(),revision:De.number().int().nonnegative()})).max(500),Fn=De.strictObject({offerKind:De.enum(["none","introductory","promotional"]),offerId:De.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:De.number().int().min(0).max(1e8),trialDays:De.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"})}),rm=De.record(De.uuid(),Fn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function yy(e,t){if(e.nativeOffers!==void 0)return rm.parse(e.nativeOffers)[t]}function Sy(e,t,n,r){return Fn.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 $s=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:nm,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:z,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 p}from"zod";var om=p.strictObject({requestId:p.uuid(),entityId:p.uuid().optional(),billingSubscriptionId:p.uuid().optional(),newBillingSubscription:p.literal(!0).optional(),offerId:p.uuid().optional(),nativeOffer:Fn.optional(),plans:p.array(p.strictObject({productVersionId:p.uuid(),seatQuantities:p.record(dn,p.number().int().min(0).max(1e4)).optional(),featureQuantities:p.record(p.uuid(),p.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:p.enum(["stripe","apple","google"]),currency:z}).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"),or=p.strictObject({operationId:p.uuid()}),ut=p.number().int().min(0).max(1e8),xy=p.strictObject({lineId:p.uuid(),productVersionId:p.uuid(),productName:p.string().min(1).max(80),interval:p.enum(["free","week","month","year","one_time"]),intervalCount:p.number().int().min(1).max(156).optional(),baseAmountMinor:ut,seats:p.array(p.strictObject({key:dn,quantity:p.number().int().min(0).max(1e4),includedQuantity:p.number().int().min(0).max(1e4),maximumQuantity:p.number().int().min(0).max(1e4),unitAmountMinor:ut})).max(20),prepaid:p.array(Td).max(100).optional(),catalogAmountMinor:ut,trial:p.strictObject({days:p.number().int().min(1).max(730),cardRequired:p.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+pa(n),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),sm=p.string().regex(/^[A-Za-z0-9_-]{1,200}$/),vy=p.strictObject({id:sm,name:p.string().min(1).max(40),percent_off:p.number().gt(0).max(100).optional(),amount_off:p.number().int().positive().optional(),currency:p.string().regex(/^[a-z]{3}$/).optional(),duration:p.enum(["once","repeating","forever"]),duration_in_months:p.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"),Iy=p.strictObject({subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.array(p.strictObject({id:p.string(),price_id:p.string(),quantity:p.number().int().nonnegative(),discounts:p.array(p.strictObject({id:p.string(),coupon:p.string(),start:p.number(),end:p.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.number().int().nonnegative(),amountMinor:p.number().int().positive(),periodStartMs:p.number(),periodEndMs:p.number()}),cm=p.strictObject({append:Iy.optional(),provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.enum(["payment","subscription"]),lineItems:p.array(p.strictObject({price:p.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.number().int().min(1).max(1e4),priceId:p.uuid(),productName:p.string().min(1).max(80),amountMinor:p.number().int().min(0).max(1e8),currency:p.string().regex(/^[a-z]{3}$/),interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),slot:p.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.number().int().min(0).max(1e8),flatAmountMinor:p.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.array(p.strictObject({coupon:sm,terms:vy})).max(1),trialPeriodDays:p.number().int().min(1).max(730).nullable(),metadata:p.strictObject({grooveCheckoutId:p.uuid(),grooveCustomerId:p.uuid()}),expiresAt:p.iso.datetime({offset:!0})}),Oi=p.strictObject({operationId:p.uuid(),entityId:p.uuid().nullable(),billingSubscriptionId:p.uuid().nullable(),discount:p.strictObject({offerId:p.uuid(),couponId:p.uuid(),discount:Ir,duration:Xt,amountMinor:ut,allocations:p.array(p.strictObject({productVersionId:p.uuid(),amountMinor:ut})).min(1).max(20),expiresAt:p.iso.datetime({offset:!0})}).nullable(),charge:p.strictObject({effectiveAt:p.iso.datetime({offset:!0}),periodEndsAt:p.iso.datetime({offset:!0}),debitMinor:ut,discountMinor:ut,taxMinor:ut,totalMinor:ut}).nullable(),expiresAt:p.iso.datetime({offset:!0}),provider:p.enum(["stripe","apple","google"]),nativeOffer:Fn.optional(),currency:z,lines:p.array(xy).min(1).max(20),catalogAmountMinor:ut,automaticTax:p.boolean(),execution:cm.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"),Pr=p.strictObject({operationId:p.uuid(),orderId:p.uuid(),append:p.boolean().optional(),status:p.enum(["pending","complete","cancelled","failed"]),executor:p.enum(["indiana","merchant"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:cm.nullable(),currency:z,catalogAmountMinor:ut,taxMinor:ut,totalMinor:p.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.boolean(),nativePurchase:$s.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"),ka=p.strictObject({enabled:p.literal(!0),featureIds:p.array(p.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),um=p.strictObject({requestId:p.uuid(),membershipId:p.uuid(),carryOverBalances:ka.optional(),carryOverUsages:ka.optional(),membershipIds:p.array(p.uuid()).min(1).max(20).optional(),timing:p.enum(["immediate","renewal","store"]),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:dn,quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.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"),Gs=p.string().regex(/^price_[A-Za-z0-9]+$/),im=p.strictObject({grooveUpdateId:p.uuid(),grooveCustomerId:p.uuid()}),am=p.strictObject({price:Gs.nullable(),priceId:p.uuid().optional(),quantity:p.number().int().min(0).max(1e4)}),lm=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.enum(["update","cancel","schedule","release"]),update:p.strictObject({items:p.array(am).max(20),remove:p.array(Gs).max(20),prorationBehavior:p.enum(["always_invoice","create_prorations"]).optional(),prorationDate:p.number().int().positive().optional(),paymentBehavior:p.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.boolean().optional(),clearCancelAt:p.literal(!0).optional(),metadata:im}).nullable(),cancel:p.strictObject({prorate:p.literal(!1),invoiceNow:p.literal(!1)}).nullable(),schedule:p.strictObject({currentItems:p.array(p.strictObject({price:Gs,quantity:p.number().int().min(0).max(1e4)})).max(20),nextItems:p.array(am).min(1).max(20),switchAt:p.number().int().positive(),interval:p.enum(["week","month","year"]),intervalCount:p.number().int().min(1).max(52),metadata:im}).nullable(),release:p.strictObject({schedule:p.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),Ks=p.strictObject({carryOverBalances:ka.optional(),carryOverUsages:ka.optional(),operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),expiresAt:p.iso.datetime({offset:!0}),currency:z,creditMinor:ut,debitMinor:ut,discountMinor:ut,taxMinor:ut,totalMinor:ut,retainedProductVersionIds:p.array(p.uuid()).max(19),execution:lm}),Ay=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.enum(["indiana","merchant"]),execution:lm.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),wy=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.literal("store"),effectiveAt:p.null(),expiresAt:p.iso.datetime({offset:!0}),currency:z,creditMinor:p.null(),debitMinor:p.null(),discountMinor:p.null(),taxMinor:p.null(),totalMinor:p.null(),retainedProductVersionIds:p.array(p.uuid()).max(19),store:p.strictObject({provider:p.enum(["apple","google"]),productId:p.string().min(1).max(255),catalogAmountMinor:ut,policy:p.enum(["apple_store","google_full_price"])})}),Cy=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.literal("store"),effectiveAt:p.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.null(),nativePurchase:$s.nullable()}),dm=p.union([Ks,wy]),Hs=p.union([Ay,Cy]),Ei=p.number().int().positive().max(2e8),ar=p.number().int().min(0).max(2e8),mm=p.strictObject({requestId:p.uuid(),invoiceId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:Ei.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),pm=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Ei,currency:p.string().regex(/^[a-z]{3}$/),metadata:p.strictObject({indianaRefundId:p.uuid()}),idempotencyKey:p.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),fm=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().regex(/^in_[A-Za-z0-9]+$/),currency:z,paidMinor:ar,refundedMinor:ar,pendingMinor:ar,amountMinor:Ei,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),revokes:p.strictObject({customerProductIds:p.array(p.uuid()).max(100),subscriptionIds:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:pm,expiresAt:p.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"),Ta=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().regex(/^in_[A-Za-z0-9]+$/),status:p.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.enum(["indiana","merchant"]),currency:z,amountMinor:Ei,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),refundId:p.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:pm.nullable(),failureReason:p.string().min(1).max(200).nullable(),createdAt:p.iso.datetime({offset:!0}),completedAt:p.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"),ek=p.strictObject({invoiceId:p.uuid(),currency:z,paidMinor:ar,refundedMinor:ar,pendingMinor:ar,refundableMinor:ar,executor:p.enum(["indiana","merchant"]).nullable(),canRefund:p.boolean(),operations:p.array(Ta).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),tk=p.strictObject({requestId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:Ei.optional(),entitlementAction:p.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 gm=qe.strictObject({requestId:qe.uuid(),targets:qe.array(qe.strictObject({membershipId:qe.uuid(),action:qe.enum(["cancel","uncancel"]),timing:qe.enum(["immediate","renewal"])}).refine(e=>e.action!=="uncancel"||e.timing==="immediate","Restoration is immediate")).min(1).max(100)}).refine(e=>new Set(e.targets.map(t=>t.membershipId)).size===e.targets.length,"Duplicate batch target"),Ra=qe.strictObject({batchId:qe.uuid()}),Py=qe.strictObject({operationId:qe.uuid(),membershipIds:qe.array(qe.uuid()).min(1).max(20),provider:qe.enum(["stripe","apple","google"]),action:qe.enum(["cancel","uncancel"]),timing:qe.enum(["immediate","renewal"]),status:qe.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:Ks.nullable(),managementUrl:qe.url().nullable(),failureCode:qe.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),ki=qe.strictObject({batchId:qe.uuid(),ready:qe.boolean(),status:qe.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:qe.iso.datetime({offset:!0}),acceptedAt:qe.iso.datetime({offset:!0}).nullable(),groups:qe.array(Py).min(1).max(100)});import{z as _e}from"zod";var Oy=_e.string().trim().min(1).max(240),Ws={requestId:_e.uuid(),reason:Oy},ja=_e.discriminatedUnion("action",[_e.strictObject({...Ws,action:_e.literal("start"),productVersionId:_e.uuid(),entityId:_e.uuid().optional(),days:_e.number().int().min(1).max(730).optional()}),_e.strictObject({...Ws,action:_e.literal("extend"),membershipId:_e.uuid(),days:_e.number().int().min(1).max(730)}),_e.strictObject({...Ws,action:_e.literal("end"),membershipId:_e.uuid()})]),hm=_e.strictObject({operationId:_e.uuid()}),bm=_e.iso.datetime({offset:!0}),Ey=_e.strictObject({provider:_e.literal("stripe"),executor:_e.enum(["indiana","merchant"]),accountId:_e.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:_e.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:_e.union([_e.literal("now"),bm]),prorationBehavior:_e.literal("none")}),zs=_e.strictObject({operationId:_e.uuid(),action:_e.enum(["start","extend","end"]),status:_e.enum(["pending","effective"]),managedBy:_e.enum(["indiana","stripe"]),membershipIds:_e.array(_e.uuid()).min(1).max(20),endsAt:bm.nullable(),execution:Ey.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"),sk=_e.strictObject({groupId:_e.uuid(),productVersionId:_e.uuid(),enabled:_e.boolean()});import{z as je}from"zod";var _m=je.strictObject({requestId:je.uuid(),currency:z,makeDefault:je.boolean()}),ym=je.strictObject({setupId:je.uuid()}),ky=je.strictObject({provider:je.literal("stripe"),executor:je.literal("merchant"),accountId:je.string().regex(/^acct_[A-Za-z0-9]+$/),mode:je.literal("setup"),currency:je.string().regex(/^[a-z]{3}$/),customer:je.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:je.uuid(),metadata:je.strictObject({grooveProjectId:je.uuid(),grooveEnvironmentId:je.uuid(),grooveCustomerId:je.uuid(),groovePaymentSetupId:je.uuid()}),setDefaultPaymentMethod:je.boolean(),expiresAt:je.iso.datetime({offset:!0})}),Qs=je.strictObject({id:je.uuid(),provider:je.literal("stripe"),status:je.enum(["prepared","complete","expired"]),currency:z,makeDefault:je.boolean(),url:je.url().nullable(),createdAt:je.iso.datetime({offset:!0}),expiresAt:je.iso.datetime({offset:!0}),completedAt:je.iso.datetime({offset:!0}).nullable(),execution:ky.nullable()});import{z as lt}from"zod";var Sm=lt.union([lt.string(),lt.number(),lt.boolean(),lt.null()]),xm=lt.strictObject({customerId:lt.uuid()}),vm=lt.strictObject({customerId:lt.uuid(),provider:lt.literal("stripe"),checkedAt:lt.iso.datetime({offset:!0}),status:lt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:lt.number().int().nonnegative(),differences:lt.array(lt.strictObject({subscriptionId:lt.string().startsWith("sub_"),itemId:lt.string().nullable(),field:lt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Sm,actual:Sm})).max(1e4)});import{z as le}from"zod";var Na=le.iso.datetime({offset:!0}),Da=le.strictObject({createdAt:Na,id:le.uuid()}),Fa=le.strictObject({customerId:le.uuid().optional(),entityId:le.uuid().optional(),productId:le.string().min(1).max(256).optional(),provider:le.enum(["stripe","apple","google","free"]).optional(),status:le.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Da.optional(),limit:le.number().int().min(1).max(100).optional()}),Zs={id:le.uuid(),customerId:le.uuid(),entityId:le.uuid().nullable(),productId:le.string().min(1).max(256),productVersionId:le.uuid(),name:le.string().min(1).max(120),provider:le.enum(["stripe","apple","google","free"]),createdAt:Na},Ty=le.strictObject({...Zs,status:le.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:le.boolean(),billingSubscriptionId:le.uuid().nullable()}),Ry=le.strictObject({...Zs,status:le.enum(["active","ended","refunded"]),orderId:le.uuid().nullable(),transactionId:le.uuid().nullable(),currency:z.nullable(),amountMinor:le.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),jy=le.strictObject({...Zs,status:le.enum(["blocked","resolved"]),conflict:le.strictObject({detectedAt:Na,blockingMembershipIds:le.array(le.uuid()).min(1).max(100),transactionId:le.uuid()}),resolvedAt:Na.nullable()}),Im=Fa.extend({status:le.enum(["blocked","resolved"]).optional()}),Am=le.strictObject({customerId:le.uuid(),orderId:le.uuid()}),wm=le.strictObject({orderId:le.uuid(),status:le.enum(["blocked","resolved"])}),Cm=le.strictObject({items:le.array(Ty).max(100),nextCursor:Da.nullable()}),Pm=le.strictObject({items:le.array(Ry).max(100),nextCursor:Da.nullable()}),Om=le.strictObject({items:le.array(jy).max(100),nextCursor:Da.nullable()});import{z as Me}from"zod";var Em=Me.union([Me.strictObject({intent:Me.literal("read"),requestId:Me.uuid(),purchaseIntentId:Me.uuid()}),Me.strictObject({requestId:Me.uuid(),provider:Me.literal("apple"),purchaseIntentId:Me.uuid(),productId:Me.string().min(1).max(255).optional(),signedTransaction:Me.string().min(1).max(131072)}),Me.strictObject({requestId:Me.uuid(),provider:Me.literal("google"),purchaseIntentId:Me.uuid(),productId:Me.string().min(1).max(255).optional(),purchaseToken:Me.string().min(1).max(16384)})]),km=Me.strictObject({requestId:Me.uuid(),orderId:Me.uuid(),purchaseIntentId:Me.uuid(),status:Me.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:z,refunded:Me.boolean(),completion:Me.strictObject({transactionIds:Me.array(Me.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Me.boolean()}).nullable()});import{z as Ge}from"zod";import{z as Ny}from"zod";var Or=Ny.object({provider:tm,currency:z}).strict();var Un=Ge.strictObject({internal_feature_id:Ge.uuid(),quantity:Y.refine(e=>/[1-9]/.test(e)),properties:Ye,entityId:Ge.uuid().optional()}),Tm=Ge.strictObject({requirement:Un,commerce:Or.optional(),paywallId:Ge.uuid().optional()}),Dy=Ge.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Ys=Ge.strictObject({productId:Ge.string().min(1),productVersionId:Ge.string().min(1),name:Ge.string().min(1).max(120),action:Ge.enum(["purchase","upgrade","addon","topup"]),membershipId:Ge.string().min(1).nullable(),currency:z,amountMinor:Ge.string().regex(/^(0|[1-9]\d{0,8})$/),interval:Ge.enum(["free","week","month","year","one_time"]),intervalCount:Ge.number().int().min(1).max(156)}),sr=Ge.strictObject({internal_feature_id:Ge.string().min(1),name:Ge.string().min(1).max(120),kind:Ge.enum(["access","metered","credit"]),quantity:Y,allowed:Ge.boolean(),reason:Dy.nullable(),preview:Ge.strictObject({scenario:Ge.enum(["feature_flag","usage_limit"]),candidates:Ge.array(Ys).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"})}),Ok=Ge.strictObject({paywallId:Ge.uuid(),requirement:Un});import{z as j}from"zod";var ec=j.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),Fy=j.record(j.string(),j.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Uy=3,Ti=20,My=Uy*Ti,Js=j.strictObject({type:j.literal("product"),productId:ec}),Rm={type:j.literal("group"),key:j.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:j.string().trim().min(1).max(80)},By=j.discriminatedUnion("type",[Js,j.strictObject({...Rm,items:j.array(Js).max(Ti)})]),Ly=j.discriminatedUnion("type",[Js,j.strictObject({...Rm,items:j.array(By).max(Ti)})]),qy=j.array(Ly).max(Ti).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,l=s.type==="product"?s.productId:s.key;c.has(l)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(l),s.type==="group"&&a(s.items)}}a(e),(n.size>Ti||i>My)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ri(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ri(t))}function Tk(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 Ua=j.strictObject({lookupKey:j.string().trim().min(1).max(200),displayName:j.string().trim().min(1).max(1500),items:qy,metadata:Fy}),Xs=Ua.extend({paywallId:j.uuid().nullable()}),Vy=j.strictObject({product:j.record(j.string(),j.json()),prices:j.array(j.record(j.string(),j.json())),entitlements:j.array(j.record(j.string(),j.json())),freeTrials:j.array(j.record(j.string(),j.json())),licenses:j.array(j.record(j.string(),j.json()))}),jm=Xs.extend({id:j.uuid(),projectId:j.uuid(),environmentId:j.uuid(),state:j.enum(["active","archived"]),isCurrent:j.boolean(),revision:j.number().int().nonnegative(),publishedVersionId:j.uuid().nullable(),createdAt:j.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"})}),Nm=j.strictObject({id:j.uuid(),offeringId:j.uuid(),projectId:j.uuid(),environmentId:j.uuid(),version:j.number().int().positive(),document:Ua,productEvidence:j.record(ec,Vy),createdAt:j.number().nonnegative().nullable()}).superRefine((e,t)=>{let n=Ri(e.document);(!n.length||Ky(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"})}),$y=j.strictObject({rows:j.array(jm).max(200),versions:j.array(Nm).max(500)}),Rk=j.discriminatedUnion("action",[j.strictObject({action:j.literal("create"),document:Xs}),j.strictObject({action:j.literal("save"),id:j.uuid(),revision:j.number().int().nonnegative(),document:Xs}),j.strictObject({action:j.enum(["publish","set_current","archive","restore"]),id:j.uuid(),revision:j.number().int().nonnegative()})]),jk=j.strictObject({record:jm,version:Nm.nullable()}),Dm=j.discriminatedUnion("type",[j.strictObject({type:j.literal("current")}),j.strictObject({type:j.literal("id"),id:j.uuid()}),j.strictObject({type:j.literal("lookup_key"),lookupKey:j.string().min(1).max(200)}),j.strictObject({type:j.literal("version"),versionId:j.uuid()})]),Gy=j.strictObject({internalId:ec,id:j.string(),name:j.string().nullable(),version:j.number().int().positive(),archived:j.boolean()}),Nk=$y.extend({products:j.array(Gy).max(500),paywalls:j.array(j.strictObject({id:j.uuid(),name:j.string()})).max(200)});function Ky(e){let t=[];Ri(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 Ma}from"zod";var Er=Ma.strictObject({id:Ma.uuid(),offeringId:Ma.uuid(),version:Ma.number().int().positive(),document:Ua});import{z as Tt}from"zod";import{z as ie}from"zod";import{z as kr}from"zod";import{z as In}from"zod";var Fm=In.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ba=In.strictObject({tiers:In.array(In.strictObject({id:Fm,name:In.string().trim().min(1).max(80)})).min(1).max(8),assignments:In.array(In.strictObject({productVersionId:In.string().min(1).max(200),tierId:Fm,period:In.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 La(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var Um=kr.strictObject({items:kr.array(kr.strictObject({productVersionId:kr.string().min(1).max(200),label:kr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:kr.string().min(1).max(200).nullable(),grouping:Ba.optional()});function $k(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 Mm(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Tr(e){let t={};function n(r){if(Mm(r)){let i=t[r.interaction.pickerId]??={ids:[],defaultId:null};for(let o of r.children){let s=o.type==="stack"?o.bind?.plan:void 0;s&&!i.ids.includes(s)&&i.ids.push(s)}let a=r.children[r.interaction.defaultIndex];!i.defaultId&&a?.type==="stack"&&(i.defaultId=a.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}function Bm(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 l=c.children.filter(d=>!d.hidden),u=c.interaction;if(Mm(c)){let d=r[c.interaction.pickerId]??={ids:[],defaults:[],remembered:[]},m=n.pickers[c.interaction.pickerId]?.options??[];for(let f of l){let h=f.type==="stack"?f.bind?.plan:void 0;h&&m.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(u?.type==="tabs"){let d=l.find(m=>m.id===t[c.id])??c.children[u.defaultIndex];d&&i(d)}else if(u?.type==="toggle"){let d=typeof t[c.id]=="boolean"?t[c.id]:u.defaultEnabled,m=c.children[d?0:1];m&&i(m)}else l.forEach(i)}let a=typeof t.__page=="string"?t.__page:e.initialPageId??e.pages[0]?.id,o=e.pages.find(c=>c.id===a);o&&i(o.root);let s={};for(let[c,l]of Object.entries(r)){let u=t[c],d=l.remembered[0]??(l.ids.includes(n.pickers[c]?.selected??"")?n.pickers[c]?.selected:l.defaults[0]);s[c]=typeof u=="string"?l.ids.includes(u)?u:"":d&&l.ids.includes(d)?d:""}for(let c of Object.keys(Tr(e)))s[c]??="";return s}import{z as re}from"zod";var Hy=["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"],tc=re.object({plan:re.string().min(1).max(200).optional(),coupon:re.uuid().optional(),promotionCode:re.uuid().optional(),picker:re.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Lm=re.object({text:re.string().optional(),label:re.string().optional(),alt:re.string().optional(),html:re.string().max(32768).optional(),price:re.object({current:re.string(),original:re.string().nullable(),period:re.string()}).optional(),code:re.string().optional(),countdownAt:re.iso.datetime().optional(),planId:re.string().min(1).max(200).optional(),planVersionId:re.string().min(1).max(200).optional(),currency:z.optional(),couponId:re.uuid().optional(),offerId:re.uuid().optional(),unavailable:re.boolean().optional(),unavailableReason:re.string().optional(),missing:re.array(re.string()).optional()}).strict(),qa=re.object({paywall:sr.optional(),nodes:re.record(re.string(),re.object({base:Lm,picker:re.string().optional(),byPlan:re.record(re.string(),Lm).optional()}).strict()),plans:re.record(re.string(),re.object({id:re.string().min(1).max(200),versionId:re.string().min(1).max(200),available:re.boolean(),name:re.string(),price:re.string(),period:re.string(),currency:z.optional()}).strict()),pickers:re.record(re.string(),re.object({options:re.array(re.string().min(1).max(200)).max(20),selected:re.string().min(1).max(200).nullable()}).strict()),diagnostics:re.array(re.object({nodeId:re.string(),message:re.string()}).strict())}).strict();function Va(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].map(t=>t[1].trim())}function $a(e){let t=Va(e).filter(r=>!Hy.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 Qk(e,t,n,r=!1){let i=Va(e).filter(a=>!/^(input|params)\.[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(a)&&t[a]===void 0);return i.length&&!r?{value:n,missing:i}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(a,o)=>t[o.trim()]??a),missing:i}}function Zk(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 Wy=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],qm=Z.enum(Wy),Vm=Z.object({source:qm,layout:Z.enum(["full","compact"]),resourceKey:Yt.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),$m=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(),zy=Z.object({key:Yt,name:at,spendable:at,reserved:at,available:at,expiry:at.nullable(),sources:Z.array($m).max(50),sourceCount:Z.number().int().nonnegative(),sourcePage:Z.number().int().positive(),hasNextSources:Z.boolean(),hasPreviousSources:Z.boolean()}).strict(),Qy=Z.object({source:qm,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(zy).max(500),rows:Z.array($m).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(),Gm=Z.object({nodes:Z.record(Z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Qy)}).strict(),eT=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 Km(e){return{source:e,status:"idle",stale:!0,preview:!1,resources:[],rows:[],hasNext:!1,hasPrevious:!1,page:1,filter:"all"}}function nc(e){let t=$a(e).map(n=>`\u672A\u77E5\u53D8\u91CF\uFF1A${n}`);for(let n=0;n<e.length;n++){if(e[n]!=="<"||!/[A-Za-z!/?{]/.test(e[n+1]??""))continue;let r=n;if(e.startsWith("<!--",n)){let i=e.indexOf("-->",n+4);n=i<0?e.length:i+2}else{let i="";for(n++;n<e.length;n++){let a=e[n];if(i)a===i&&(i="");else if(a==='"'||a==="'")i=a;else if(a===">")break}}/\{\{|\}\}/.test(e.slice(r,n+1))&&t.push("\u53D8\u91CF\u53EA\u80FD\u653E\u5728 HTML \u6587\u5B57\u4E2D\uFF0C\u4E0D\u80FD\u653E\u5165\u6807\u7B7E\u3001\u5C5E\u6027\u6216\u6CE8\u91CA")}return[...new Set(t)]}function Hm(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t])}function rT(e,t,n,r=!1){let i=nc(e);if(i.length)throw new Error(i[0]);let a=[...new Set(Va(e).filter(o=>t[o]===void 0))];return a.length&&!r?{value:Hm(n),missing:a}:{value:e.replace(/\{\{\s*([^{}]+?)\s*\}\}/g,(o,s)=>t[s.trim()]===void 0?o:Hm(t[s.trim()])),missing:a}}var Zy=4,rn={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}$/),Be=_.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Yy=_.enum(["none","xs","sm","md","lg","xl"]),Jy=_.enum(["none","sm","md","lg","full"]),rc=_.string().regex(/^#[0-9a-fA-F]{6}$/),Qm=_.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"),ic=_.union([Qm,_.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}$/)]),Wm=_.object({primary:rc,background:rc,text:rc,radius:Jy,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})?$/)]),Ee=(e,t)=>_.number().int().min(e).max(t),zm=_.union([_.enum(["fit","fill"]),Ee(1,1200)]),Xy=_.object({top:Ee(0,200),right:Ee(0,200),bottom:Ee(0,200),left:Ee(0,200)}).strict(),eS=_.object({top:Ee(-100,200),right:Ee(-100,200),bottom:Ee(-100,200),left:Ee(-100,200)}).strict(),Zm=_.object({x:Ee(0,100),y:Ee(0,100)}).strict(),tS=_.discriminatedUnion("type",[_.object({type:_.literal("color"),color:Di}).strict(),_.object({type:_.literal("linear"),angle:Ee(0,360),stops:_.array(_.object({color:Di,at:Ee(0,100)}).strict()).min(2).max(4)}).strict(),_.object({type:_.literal("image"),src:ic,fit:_.enum(["cover","contain"]),position:Zm.optional()}).strict()]),nS=_.discriminatedUnion("type",[_.object({type:_.literal("rect"),radius:_.union([Ee(0,200),_.object({topLeft:Ee(0,200),topRight:Ee(0,200),bottomRight:Ee(0,200),bottomLeft:Ee(0,200)}).strict()])}).strict(),_.object({type:_.literal("pill")}).strict()]),rS=_.object({width:Ee(0,12),color:Di,style:_.enum(["solid","dashed"])}).strict(),iS=_.object({x:Ee(-40,40),y:Ee(-40,40),blur:Ee(0,80),spread:Ee(-20,40),color:Di}).strict(),aS=_.object({font:_.enum(["system","serif","rounded","mono"]),size:Ee(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(),cr=_.object({width:zm,height:zm,padding:Xy,margin:eS,gap:Ee(0,120),grow:_.union([_.boolean(),_.number().min(0).max(12)]),background:tS,opacity:_.number().min(0).max(1),clipContent:_.boolean(),shape:nS,border:rS,shadow:iS,text:aS}).strict().partial(),Kt={id:Ni,name:_.string().trim().min(1).max(60).optional(),hidden:_.boolean().optional(),style:cr.optional(),fallback:Be.optional()},oS=_.object({...Kt,type:_.literal("text"),productField:_.enum(["name","price","trial","period"]).optional(),feature:_.object({id:_.uuid(),field:_.enum(["name","allowance"])}).strict().optional(),text:Be,variant:_.enum(["title","heading","body","caption"])}).strict(),sS=_.object({...Kt,type:_.literal("image"),src:ic,localizedSrc:_.record(xn,ic).optional(),alt:Be,aspect:_.enum(["auto","1:1","4:3","16:9","3:1"]),fit:_.enum(["cover","contain"]),position:Zm.optional()}).strict(),cS=_.object({...Kt,type:_.literal("button"),label:Be,variant:_.enum(["primary","secondary","link"]),action:Be,purpose:_.enum(["purchase","navigation","close"]).optional(),bind:tc.optional()}).strict(),uS=_.object({...Kt,type:_.literal("divider")}).strict(),lS=_.object({...Kt,type:_.literal("customer_data"),title:Be,data:Vm}).strict(),dS=_.object({...Kt,type:_.literal("spacer"),size:Yy}).strict(),mS=_.object({...Kt,type:_.literal("custom_html"),html:_.record(xn,_.string().max(rn.customHtml)),css:_.string().max(rn.customCss)}).strict(),pS=_.object({...Kt,type:_.literal("price"),fallback:Be,parts:_.object({current:cr.optional(),original:cr.optional(),period:cr.optional()}).strict().optional()}).strict(),fS=_.object({...Kt,type:_.literal("coupon_code"),label:Be,fallback:Be}).strict(),gS=_.object({...Kt,type:_.literal("countdown"),source:_.enum(["offer.ends_at","offer.expires_at","fixed"]),at:_.iso.datetime().optional(),granularity:_.enum(["day","hour","minute","second"]),expired:Be,fallback:Be}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),hS=_.object({...Kt,type:_.literal("plan_picker"),label:Be,fallback:Be,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:Ba.safeExtend({monthLabel:Be,yearLabel:Be,unavailableLabel:Be}).optional(),states:_.object({selected:cr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!La(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),bS=_.discriminatedUnion("type",[_.object({type:_.literal("input"),label:Be,keyboard:_.enum(["text","email","tel","url"]),maxLength:Ee(1,500)}).strict(),_.object({type:_.literal("multiselect"),label:Be,min:Ee(0,50),max:Ee(1,50)}).strict(),_.object({type:_.literal("select"),label:Be,defaultIndex:Ee(0,49),purpose:_.enum(["option","product","tier"]).optional(),pickerId:Ni.optional(),selectedStyle:cr.optional()}).strict(),_.object({type:_.literal("tabs"),label:Be,defaultIndex:Ee(0,49),purpose:_.literal("tier").optional()}).strict(),_.object({type:_.literal("toggle"),label:Be,defaultEnabled:_.boolean()}).strict(),_.object({type:_.literal("carousel"),label:Be}).strict()]),Ym=_.lazy(()=>_.object({...Kt,type:_.literal("stack"),direction:_.enum(["vertical","horizontal","overlay"]),align:_.enum(["start","center","end","stretch"]),justify:_.enum(["start","center","end","between"]),children:_.array(_S).max(rn.children),productSlot:_.object({index:Ee(0,19),period:_.enum(["month","year"]).optional(),requireBinding:_.boolean().optional()}).strict().optional(),interaction:bS.optional(),states:_.object({selected:cr.optional()}).strict().optional(),purpose:_.literal("benefits").optional(),purchaseAction:Be.optional(),buttonVariant:_.enum(["primary","secondary","link"]).optional(),bind:tc.optional()}).strict()),_S=_.lazy(()=>_.union([Ym,oS,sS,cS,uS,dS,mS,pS,fS,gS,hS,lS])),yS=_.union([_.string().max(500),_.number().finite(),_.boolean(),_.null()]),ji={id:Be,event:Be,properties:_.record(Be,yS).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},SS=_.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:Qm}).strict(),_.object({...ji,type:_.literal("claim_offer"),close:_.boolean(),couponId:_.uuid()}).strict()]),xS=_.object({defaultLocale:xn,locales:_.record(xn,_.record(Be,_.string().max(rn.stringLength)))}).strict(),ac=_.enum(["popup","paywall","onboarding","page"]),mT={popup:"/workspace/popups",paywall:"/workspace/paywalls",onboarding:"/workspace/funnels",page:"/workspace/pages"},vS=_.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()]),pT={sm:360,md:420,lg:560},IS=_.object({kind:_.literal("screen"),schemaVersion:_.literal(Zy),name:_.string().trim().min(1).max(80),surface:ac,initialPageId:Ni.optional(),presentation:vS,theme:Wm,pages:_.array(_.object({id:Ni,name:_.string().trim().min(1).max(60),root:Ym,theme:Wm.optional(),editorPosition:_.object({x:_.number().finite().min(-1e5).max(1e5),y:_.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(rn.pages),strings:xS,actions:_.array(SS).max(rn.actions)}).strict();function Ct(e,t){for(let n of e.pages)pn(n.root,t)}function fT(e,t){return{...e,pages:e.pages.map((n,r)=>r===0?{...n,root:t}:n)}}var kt=IS.superRefine((e,t)=>{let n=rn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(u=>u.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let u of e.actions)u.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(d=>d.id===u.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=u=>t.addIssue({code:"custom",message:u}),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>rn.locales&&r(`\u6700\u591A ${rn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let u of e.actions)a.has(u.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${u.id}`),a.add(u.id);let o=new Set;for(let u of e.pages)["next","back"].includes(u.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${u.id}`),o.has(u.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${u.id}`),o.add(u.id);let s=new Set,c=0,l=!1;Ct(e,(u,d)=>{if(c++,d>rn.depth&&(l=!0),s.has(u.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${u.id}`),s.add(u.id),u.type==="button"&&!a.has(u.action)&&r(`\u6309\u94AE ${u.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${u.action}`),u.type==="custom_html")for(let m of Object.keys(u.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${u.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(u.type==="image")for(let m of Object.keys(u.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${u.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),l&&r(`\u5C42\u7EA7\u6700\u591A ${rn.depth} \u5C42`)});function pn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)pn(i,t,n+1,e)}function oc(e){let t=[],n=new Set;return Ct(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function AS(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 Rr(e){let t=oc(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!AS(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function gT(e){let t=[],n=e.actions.some(c=>typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-"));n&&(!e.actions.some(c=>c.type==="claim_offer")||e.actions.some(c=>c.type==="event"&&typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-")))&&t.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 r(c,l){let u=c.type==="stack"||c.type==="button"?c.bind?.coupon??l:l;if(n&&c.type==="text"&&Object.values(e.strings.locales).some(d=>d[c.text]?.includes("{{offer."))&&!u&&t.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"),c.type==="button"){let d=e.actions.find(m=>m.id===c.action);d?.type==="claim_offer"&&u&&u!==d.couponId&&t.push(`\u9886\u53D6\u6309\u94AE ${c.id} \u4E0E\u5C55\u793A\u5185\u5BB9\u7ED1\u5B9A\u4E86\u4E0D\u540C\u7684\u4F18\u60E0\u5238`)}c.type==="stack"&&c.children.forEach(d=>r(d,u))}e.pages.forEach(c=>r(c.root));let i=[],a=kt.safeParse(e);a.success||t.push(...a.error.issues.map(c=>c.message));for(let c of Object.values(e.strings.locales))for(let l of Object.values(c))for(let u of $a(l))t.push(`\u672A\u77E5\u53D8\u91CF\uFF1A${u}`);Ct(e,c=>{if(c.type==="customer_data"&&Object.values(e.strings.locales).some(u=>/\{\{|\}\}/.test(u[c.title]??""))&&t.push(`\u6570\u636E\u7EC4\u4EF6 ${c.id} \u7684\u6807\u9898\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),(c.type==="text"?[c.text]:c.type==="button"?[c.label]:[]).some(u=>Object.values(e.strings.locales).some(d=>d[u]?.includes("{{")))&&!c.fallback&&t.push(`\u7EC4\u4EF6 ${c.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),c.fallback&&Object.values(e.strings.locales).some(u=>u[c.fallback]?.includes("{{"))&&t.push(`\u7EC4\u4EF6 ${c.id} \u7684\u5907\u7528\u6587\u6848\u9700\u8981\u4F7F\u7528\u9759\u6001\u6587\u5B57`),c.type==="custom_html"){for(let u of Object.values(c.html))t.push(...nc(u).map(d=>`HTML ${c.id}\uFF1A${d}`));Object.values(c.html).some(u=>u.includes("{{"))&&!c.fallback&&t.push(`HTML ${c.id} \u4F7F\u7528\u53D8\u91CF\uFF0C\u8BF7\u586B\u5199\u5907\u7528\u6587\u6848`),/\{\{|\}\}/.test(c.css)&&t.push(`HTML ${c.id} \u7684 CSS \u4E0D\u652F\u6301\u53D8\u91CF`)}(c.type==="stack"||c.type==="button")&&c.bind?.picker&&Fi(e,c.bind.picker)?.type!=="plan_picker"&&!Object.hasOwn(Tr(e),c.bind.picker)&&t.push(`\u5BB9\u5668 ${c.id} \u5F15\u7528\u7684\u5957\u9910\u9009\u62E9\u4E0D\u5B58\u5728`)});for(let c of Object.keys(Tr(e)))Fi(e,c)||t.push(`Product selection scope ${c} must reference a UI node`);let o=Rr(e);for(let c of o)c.complete||(c.locale===e.strings.defaultLocale?t.push(`\u9ED8\u8BA4\u8BED\u8A00 ${c.locale} \u8FD8\u6709 ${c.missing.length} \u5904\u5185\u5BB9\u6CA1\u586B`):t.push(`${c.locale} \u8FD8\u6709 ${c.missing.length} \u5904\u6CA1\u7FFB\u8BD1\uFF0C\u8BF7\u8865\u9F50\u6216\u5220\u9664\u8FD9\u79CD\u8BED\u8A00\u540E\u53D1\u5E03`));oc(e).length===0&&!e.pages.some(c=>wS(c.root))&&t.push("\u5F39\u7A97\u91CC\u8FD8\u6CA1\u6709\u53EF\u663E\u793A\u7684\u5185\u5BB9");let s=new Set;Ct(e,c=>{c.type==="button"&&s.add(c.action)});for(let c of e.actions)!s.has(c.id)&&!e.pages.some(l=>CS(l.root,c.id))&&i.push(`\u52A8\u4F5C ${c.id} \u6CA1\u6709\u88AB\u4EFB\u4F55\u6309\u94AE\u4F7F\u7528`);return{errors:t,warnings:i}}function wS(e){let t=!1;return pn(e,n=>{if(n.hidden)return!1;n.type==="image"&&(t=!0)}),t}function CS(e,t){let n=!1;return pn(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 PS(e){return Rr(e).filter(t=>t.complete||t.locale===e.strings.defaultLocale).map(t=>t.locale)}function sc(e,t){return xa(t,PS(e),e.strings.defaultLocale)}function hT(e,t){let n=e.strings.locales[t]??{},r=e.strings.locales[e.strings.defaultLocale]??{},i={};for(let o of oc(e)){if(o.field==="html"||o.field==="src")continue;let s=n[o.key]?.trim()?n[o.key]:r[o.key];s!==void 0&&(i[o.key]=s)}let a=o=>{if(o.type==="stack")return{...o,children:o.children.map(a)};if(o.type==="custom_html"){let s=o.html[t]?.trim()?o.html[t]:o.html[e.strings.defaultLocale];return{...o,html:s===void 0?{}:{[t]:s}}}if(o.type==="image"){let{localizedSrc:s,...c}=o;return{...c,src:s?.[t]??s?.[e.strings.defaultLocale]??o.src}}return o};return{...e,pages:e.pages.map(o=>({...o,root:a(o.root)})),strings:{defaultLocale:t,locales:{[t]:i}}}}function OS(e,t){let n=null;return pn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Fi(e,t){for(let n of e.pages){let r=OS(n.root,t);if(r)return r}return null}function bT(e){let t=Xn(e)?.split("-")[0];return t!==void 0&&["ar","he","fa","ur"].includes(t)}function _T(e,t,n){let r={};if(!t||typeof t!="object"||Array.isArray(t))return r;let i=t;if(Ct(e,a=>{if(a.type==="plan_picker"){let s=i[a.id];typeof s=="string"&&(r[a.id]=n?.pickers[a.id]?.options.includes(s)?s:"");return}if(a.type!=="stack"||!a.interaction)return;let o=Object.hasOwn(i,a.id)?i[a.id]:void 0;["select","tabs"].includes(a.interaction.type)&&typeof o=="string"&&a.children.some(s=>s.id===o)&&(r[a.id]=o),a.interaction.type==="toggle"&&typeof o=="boolean"&&(r[a.id]=o)}),e.surface==="paywall"&&typeof i.__page=="string"&&e.pages.some(a=>a.id===i.__page)&&(r.__page=i.__page),n){let a={...r};for(let[o,s]of Object.entries(i))(typeof s=="string"||typeof s=="boolean")&&(a[o]=s);Object.assign(r,Bm(e,a,n))}return r}import{z as it}from"zod";var ES=it.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Jm=it.discriminatedUnion("type",[it.object({type:it.literal("fixed"),productVersionId:it.string().min(1).max(200)}).strict(),it.object({type:it.literal("picker"),pickerId:ES,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")]),An=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 kS=ie.discriminatedUnion("type",[ie.strictObject({type:ie.literal("event"),event:ie.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ie.strictObject({type:ie.literal("open_url"),url:ie.url().refine(e=>new URL(e).protocol==="https:")})]),TS=kt,RS=ie.discriminatedUnion("type",[ie.object({type:ie.literal("checkout"),product:Jm}).strict(),ie.object({type:ie.literal("close")}).strict(),ie.object({type:ie.literal("action"),action:kS}).strict()]),Ga=ie.object({schemaVersion:ie.literal(3),kind:ie.literal("paywall"),name:ie.string().trim().min(1).max(80),presentation:An,requirement:Un.optional(),products:Um,offeringVersionId:ie.uuid().nullable(),offeringId:ie.uuid().nullable(),screen:TS,buttons:ie.record(ie.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),RS)}).strict(),Ka=Ga.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 NS(e))t.addIssue({code:"custom",message:r});for(let r of jS(e))t.addIssue({code:"custom",message:r});Rr(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 jS(e){let t=e.products.items.map(a=>a.productVersionId),n=Tr(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&&(!La(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(c=>r.add(c));let s=!1;n[o.pickerId]&&(s=!0,(o.allowedProductVersionIds.some(c=>!n[o.pickerId].ids.includes(c))||n[o.pickerId].ids.some(c=>!o.allowedProductVersionIds.includes(c)))&&i.push("picker")),Ct(e.screen,c=>{if(c.id!==o.pickerId||c.type!=="plan_picker")return;s=!0,(JSON.stringify(c.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||c.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=c.grouping?{tiers:c.grouping.tiers,assignments:c.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Ct(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function NS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let o of e.screen.pages)r.set(o.id,[]),pn(o.root,s=>{let c=s.type==="button"?s.action:s.type==="stack"?s.purchaseAction:void 0;if(c){let l=e.screen.actions.find(d=>d.id===c);l?.type==="navigate"&&r.get(o.id).push(l.pageId);let u=e.buttons[c];o.id!==n.id&&u&&u.type!=="close"&&t.push(`purchaseScreen:${s.id}`)}o.id!==n.id&&(s.type==="plan_picker"||s.type==="stack"&&s.productSlot)&&t.push(`packageScreen:${s.id}`)});let i=new Set;function a(o){if(!i.has(o)){i.add(o);for(let s of r.get(o)??[])a(s)}}a(e.screen.initialPageId??e.screen.pages[0].id);for(let o of e.screen.pages)i.has(o.id)||t.push(`unreachableScreen:${o.id}`);return[...new Set(t)]}var DS=ie.object({id:ie.uuid(),projectId:ie.uuid(),environmentId:ie.uuid(),revision:ie.number().int().nonnegative(),status:ie.enum(["draft","published","archived"]),publishedVersionId:ie.uuid().nullable(),updatedAt:ie.iso.datetime({offset:!0}),draft:Ga}).strict(),ET=ie.object({rows:ie.array(DS).max(200),nextCursor:ie.uuid().nullable()}).strict(),kT=ie.discriminatedUnion("action",[ie.object({action:ie.literal("save"),id:ie.uuid().nullable(),revision:ie.number().int().nonnegative(),document:Ga}).strict(),ie.object({action:ie.enum(["publish","archive"]),id:ie.uuid(),revision:ie.number().int().nonnegative()}).strict()]),TT=ie.object({paywalls:ie.array(ie.object({id:ie.uuid(),paywallId:ie.uuid(),version:ie.number().int().positive(),name:ie.string().min(1).max(80),presentation:An,buttons:Ga.shape.buttons}).strict()).max(500),limited:ie.boolean()}).strict();var Xm=Tt.strictObject({selector:Tt.discriminatedUnion("type",[Tt.strictObject({type:Tt.literal("paywall"),paywallId:Tt.uuid()}),Tt.strictObject({type:Tt.literal("version"),versionId:Tt.uuid()})]),customerId:Tt.uuid().optional(),commerce:Or,locale:Tt.string().min(1).max(35),requirement:Un.optional()}),Ha=Tt.strictObject({id:Tt.uuid(),paywallId:Tt.uuid(),version:Tt.number().int().positive(),document:Ka,offering:Er,capabilities:qa,check:sr.nullable()}).superRefine((e,t)=>{let n=new Set(Ri(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 xt}from"zod";var ep={requestId:xt.uuid(),sourceId:xt.uuid(),expectedAvailable:Qe},tp=xt.discriminatedUnion("action",[xt.strictObject({...ep,action:xt.enum(["add","subtract","set_remaining"]),amount:Y}),xt.strictObject({...ep,action:xt.literal("edit"),granted:Y,expiresAt:xt.iso.datetime({offset:!0}).nullable(),nextResetAt:xt.iso.datetime({offset:!0}).nullable(),expectedRevision:xt.number().int().nonnegative()})]),cc=xt.strictObject({sourceId:xt.uuid(),available:Qe,held:Qe,spent:Qe,adjustmentGrantId:xt.uuid().nullable()}),np=cc.extend({granted:Qe,expiresAt:xt.iso.datetime({offset:!0}).nullable(),nextResetAt:xt.iso.datetime({offset:!0}).nullable(),revision:xt.number().int().nonnegative()});import{z as Bt}from"zod";var rp=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()]),ip=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 pt}from"zod";import{z as lr}from"zod";var op=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],ap=lr.string().regex(/.+\/.+/),uc=lr.number().min(-100),ur=lr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),FS=lr.strictObject({input:ur,output:ur,cache_read:ur.optional(),cache_write:ur.optional(),reasoning:ur.optional(),input_audio:ur.optional(),output_audio:ur.optional()}),lc=(e,t)=>lr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),zT=lr.strictObject({defaultMarkup:uc,providerMarkups:lc(lr.string().min(1),uc),modelMarkups:lc(ap,uc),customModels:lc(ap,FS.partial())});import{z as ae}from"zod";var dr=ae.iso.datetime({offset:!0}),Mn=ae.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),US=ae.discriminatedUnion("kind",[ae.object({kind:ae.literal("absolute"),from:dr,to:dr}).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()]),sp=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"),MS=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:US,timezone:sp,filterBy:ae.array(MS).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:dr,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)"})}),cp=ae.object({from:dr,to:dr,interval:ae.enum(["hour","day","week","month"]),timezone:sp,rows:ae.array(ae.object({bucket:dr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid(),consumedUnits:Mn,refundedUnits:Mn,reservedUnits:Mn,charged:Mn,refunded:Mn,reserved:Mn,netUnits:Mn,netCharged:Mn}).strict()).max(100),nextCursor:ae.object({bucket:dr,group:ae.string().max(240),isOther:ae.boolean(),internal_feature_id:ae.uuid(),resourceId:ae.uuid()}).strict().nullable()}).strict();var jr=pt.string().regex(/^(0|[1-9]\d{0,29})$/),up=pt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),dc=pt.strictObject({bucket:pt.iso.datetime({offset:!0}),group:pt.string().max(240),isOther:pt.boolean(),internal_feature_id:pt.uuid()}),lp=pt.strictObject({...mr.shape,groupBy:pt.union([pt.enum(["customer","entity","entitlement"]),pt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:dc.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})}),dp=pt.strictObject({from:pt.iso.datetime({offset:!0}),to:pt.iso.datetime({offset:!0}),interval:mr.shape.interval,timezone:mr.shape.timezone,rows:pt.array(pt.strictObject({...dc.shape,eventCount:jr,units:up,tokenEventCount:jr,tokens:pt.strictObject(Object.fromEntries(op.map(e=>[e,jr]))),totalTokens:jr,providerCostEventCount:jr,providerCostUsd:up,invalidTelemetryEventCount:jr})).max(100),nextCursor:dc.nullable()});import{z as Xe}from"zod";var mp=Xe.object({requestId:Xe.uuid(),items:Xe.array(Xe.object({customerId:Xe.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"),pp=Xe.object({batchId:Xe.uuid(),after:Xe.number().int().min(-1).max(999),limit:Xe.number().int().min(1).max(100)}).strict(),fp=Xe.object({batchId:Xe.uuid(),status:Xe.enum(["queued","complete"]),total:Xe.number().int().min(1).max(1e3),processed:Xe.number().int().min(0).max(1e3),items:Xe.array(Xe.object({position:Xe.number().int().min(0).max(999),customerId:Xe.uuid(),idempotencyKey:Xe.string().min(1).max(120),status:Xe.enum(["queued","accepted","rejected","failed"]),receipt:Ai.nullable(),errorCode:Xe.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:Xe.number().int().min(0).max(999).nullable()}).strict();import{z as v}from"zod";var BS=v.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),gp=v.enum(["draft","active","paused","archived"]),hp=v.string().min(1).max(256),bp=v.array(hp).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),LS=v.strictObject({duration:v.enum(["day","week","month","year"]),length:v.number().int().min(1).max(3660)}),qS=v.strictObject({internal_feature_id:v.uuid(),allowance:v.number().nonnegative().max(1e15).nullable(),expiry:LS.nullable()}),VS=v.discriminatedUnion("type",[v.strictObject({type:v.literal("feature_grant"),grants:v.array(qS).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),v.strictObject({type:v.literal("free_product"),productId:hp,duration:Xt}),v.strictObject({type:v.literal("invoice_credits"),amount:v.number().positive().max(1e8),duration:Xt,rollover:v.boolean(),productIds:bp})]),$S=v.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),_p=v.object({key:$S,name:v.string().trim().min(1).max(80),configuration:VS}).strict(),yp=v.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),mc=v.object({code:yp,maxUses:v.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:v.boolean()}).strict(),Sp=v.object({key:v.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:v.string().trim().min(1).max(80),rewardId:v.uuid(),redeemOn:v.enum(["customer_creation","checkout"]),receivedBy:v.enum(["referrer","all"]),maxRedemptions:v.number().int().min(1).max(1e6).nullable(),productIds:bp,excludeTrial:v.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),xp={id:v.uuid(),projectId:v.uuid(),environmentId:v.uuid(),revision:v.number().int().nonnegative(),status:gp,createdAt:v.iso.datetime({offset:!0}),updatedAt:v.iso.datetime({offset:!0})},GS=_p.extend(xp).strict(),KS=Sp.safeExtend(xp).strict(),cR=v.strictObject({id:v.uuid(),key:v.string(),name:v.string(),type:BS,status:gp}),uR=v.discriminatedUnion("action",[v.object({action:v.literal("save"),id:v.uuid().nullable(),revision:v.number().int().nonnegative(),input:_p}).strict(),v.object({action:v.enum(["activate","pause","resume","archive","delete"]),id:v.uuid(),revision:v.number().int().nonnegative()}).strict()]),lR=v.discriminatedUnion("action",[v.object({action:v.literal("save"),id:v.uuid().nullable(),revision:v.number().int().nonnegative(),input:Sp}).strict(),v.object({action:v.enum(["activate","pause","resume","archive","delete"]),id:v.uuid(),revision:v.number().int().nonnegative()}).strict()]),vp=v.object({id:v.uuid(),rewardId:v.uuid(),programId:v.uuid().nullable(),customerId:v.uuid(),referrerId:v.uuid().nullable(),status:v.enum(["pending","applied"]),result:v.record(v.string(),v.unknown()).nullable(),createdAt:v.iso.datetime({offset:!0})}).strict(),Ip=v.object({code:yp,requestId:v.uuid()}).strict(),Ap=v.strictObject({redemptionId:v.uuid(),currency:z,requestId:v.uuid(),accepted:v.literal(!0)}),HS=v.strictObject({type:v.literal("checkout"),orderId:v.uuid(),productVersionId:v.uuid(),currency:z,duration:Xt,renewalAmountMinor:v.number().int().positive().max(1e8),status:v.enum(["created","pending","trialing","paid","cancelled","failed"]),url:v.url().nullable()}),wp=v.discriminatedUnion("type",[HS,v.strictObject({type:v.literal("subscription"),operationId:v.uuid(),membershipId:v.uuid(),productVersionId:v.uuid(),currency:z,duration:Xt,renewalAmountMinor:v.number().int().positive().max(1e8),status:v.enum(["pending","running","applied","failed"])})]),Cp=v.object({programId:v.uuid(),requestId:v.uuid()}).strict(),Pp=v.object({id:v.uuid(),programId:v.uuid(),code:mc.shape.code,createdAt:v.iso.datetime({offset:!0})}).strict(),dR=v.object({rows:v.array(GS).max(100),nextCursor:v.uuid().nullable()}).strict(),mR=v.object({rows:v.array(KS).max(100),nextCursor:v.uuid().nullable()}).strict(),WS=mc.extend({id:v.uuid(),redemptions:v.number().int().nonnegative()}).strict(),zS=v.strictObject({id:v.uuid(),programId:v.uuid().nullable(),customerId:v.uuid().nullable(),referrerId:v.uuid().nullable(),code:v.string().nullable(),status:v.enum(["pending","triggered","applied"]),createdAt:v.iso.datetime({offset:!0})}),pR=v.object({codes:v.array(WS).max(100),redemptions:v.array(zS).max(100),customers:v.record(v.uuid(),v.string()),codesCursor:v.uuid().nullable(),redemptionsCursor:v.uuid().nullable()}).strict(),fR=v.discriminatedUnion("action",[v.object({action:v.literal("create"),rewardId:v.uuid(),revision:v.number().int().nonnegative(),input:mc}).strict(),v.object({action:v.literal("remove"),rewardId:v.uuid(),revision:v.number().int().nonnegative(),codeId:v.uuid()}).strict()]);import{z as y}from"zod";import{z as J}from"zod";var pc=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"),Nr=J.intersection(Jt,J.object({tags:pc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Wa=J.string().trim().max(80),za=J.union([J.email().max(254),J.literal("")]),Qa=J.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"\u8BBE\u5907\u6307\u7EB9\u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26"),Op=J.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Ep=J.object({externalUserId:Op.optional(),name:Wa.default(""),email:za.default(""),attributes:Nr.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Dr=J.discriminatedUnion("type",[J.strictObject({type:J.literal("id"),value:J.uuid()}),J.strictObject({type:J.literal("externalUserId"),value:Op})]),Fr=J.strictObject({name:Wa.optional(),email:za.optional(),attributes:Nr.optional(),fingerprint:Qa.optional()}),pr=e=>!e.customerData||e.customer?.type==="externalUserId",fr="customerData requires an externalUserId customer",Ur=J.object({id:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),name:Wa,email:za,attributes:Nr,createdAt:J.iso.datetime()}).strict(),kp=J.object({customer:Ur,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()]),ZS=J.object({name:Wa.optional(),email:za.optional(),attributes:Nr.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:pc,remove:pc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),fc=J.object({lookup:QS}).strict(),Tp=fc.extend({requestId:J.uuid(),patch:ZS}).strict(),Rp=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(),jp=J.object({customers:Ur.array(),hasMore:J.boolean(),total:J.number().int().nonnegative().nullable(),evaluatedAt:J.iso.datetime()}).strict();var YS=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"]),Np={scope:Ue,permissions:y.array(YS),expiresAt:y.iso.datetime().nullable()},JR=y.discriminatedUnion("kind",[y.object({...Np,kind:y.literal("server"),keyId:y.string().min(1)}),y.object({...Np,kind:y.literal("customer"),customerId:y.string().min(1),identityKind:y.enum(["identified","guest"]),expiresAt:y.iso.datetime()})]),B=y.object({requestId:y.uuid(),scope:Ue}).strict(),JS=Ep.safeExtend({fingerprint:Qa.optional()}).strict(),XS=B.extend({customer:Ur,created:y.boolean()}),e0=y.enum(["unassigned","unknown","scheduled","active","expired"]),XR=y.object({customerId:y.string().min(1),evaluatedAt:y.iso.datetime(),status:e0,validity:ms.nullable(),planVersion:Rl.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()}))}),ej=y.enum(["UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","INTERNAL_ERROR"]);function Dp(){return B.extend({offer:ks.nullable(),reason:va.nullable()})}var M={readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid(),sourceId:y.uuid()}),response:B.extend({balance:np})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:tp}),response:B.extend({balance:cc})},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:B.extend({internal_feature_id:y.uuid(),config:ns,model_markups:ma})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid(),query:Oa}),response:B.extend({usage:wi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:Hd}),response:B.extend({usage:wi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:y.strictObject({customerId:y.uuid(),command:Bd}),response:B.extend({grant:Ms})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Ld,response:B.extend({grants:qd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:y.union(Em.options.map(e=>e.extend({customerId:y.uuid().optional(),customerToken:y.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:B.extend({operation:km})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:_m.extend({customerId:y.uuid().optional()}),response:B.extend({setup:Qs})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:ym.extend({customerId:y.uuid().optional()}),response:B.extend({setup:Qs})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:gm.safeExtend({customerId:y.uuid()}),response:B.extend({batch:ki})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ra.extend({customerId:y.uuid()}),response:B.extend({batch:ki})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ra.extend({customerId:y.uuid()}),response:B.extend({batch:ki})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ra.extend({customerId:y.uuid()}),response:B.extend({batch:ki})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:y.discriminatedUnion("action",[ja.options[0].extend({customerId:y.uuid()}),ja.options[1].extend({customerId:y.uuid()}),ja.options[2].extend({customerId:y.uuid()})]),response:B.extend({trial:zs})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:hm.extend({customerId:y.uuid()}),response:B.extend({trial:zs})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Fa,response:B.extend({subscriptions:Cm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Fa,response:B.extend({purchases:Pm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Im,response:B.extend({conflicts:Om})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Am,response:B.extend({resolution:wm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:xm,response:B.extend({verification:vm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:om.safeExtend({customerId:y.uuid().optional()}),response:B.extend({quote:Oi})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:or.extend({customerId:y.uuid().optional(),intent:y.enum(["confirm","cancel"]).optional()}),response:B.extend({operation:Pr})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:or.extend({customerId:y.uuid().optional()}),response:B.extend({operation:Pr})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:um.safeExtend({customerId:y.uuid().optional()}),response:B.extend({quote:dm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:or.extend({customerId:y.uuid().optional(),intent:y.enum(["confirm","cancel"]).optional()}),response:B.extend({operation:Hs})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:or.extend({customerId:y.uuid().optional()}),response:B.extend({operation:Hs})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:mm.safeExtend({customerId:y.uuid()}),response:B.extend({quote:fm})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:or.extend({customerId:y.uuid()}),response:B.extend({operation:Ta})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:or.extend({customerId:y.uuid()}),response:B.extend({operation:Ta})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:xd,response:B.extend({controls:Ts})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:fd,response:B.extend({prepared:hd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:bd,response:B.extend({authorization:Ia})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:wd,response:B.extend({coupons:Cd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:_d,response:B.extend({authorization:Ia})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Id,response:B.extend({invoices:Ad})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:vd,response:B.extend({invoice:gi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:y.object({customerId:y.uuid(),command:Sd}).strict(),response:B.extend({controls:Ts})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:y.object({customerId:y.uuid(),command:rp}).strict(),response:B.extend({entity:ip})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:y.strictObject({customerId:y.uuid().nullable(),query:lp}),response:B.extend({analytics:dp})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:y.object({customerId:y.uuid().nullable(),query:mr}).strict(),response:B.extend({analytics:cp})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:mp,response:B.extend({batchId:y.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:pp,response:B.extend({batch:fp})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:Tm.extend({customerId:y.string().min(1).optional()}),response:B.extend({check:sr})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Xm,response:B.extend({paywall:Ha})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:y.strictObject({selector:Dm,customerId:y.string().min(1).optional(),commerce:Or,requirement:Un.optional()}),response:B.extend({offering:Er,candidates:y.array(Ys).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:sr.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:B.extend({holdings:Wd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),query:Qd}).strict(),response:B.extend({ledger:Zd})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Vd.extend({customerId:y.uuid().optional()}),response:B.extend({detail:$d})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Bs.safeExtend({customerId:y.uuid().optional()}),response:B.extend({statement:Gd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:y.object({customerId:y.uuid().optional(),command:Ii.options[0]}).strict(),response:B.extend({quote:Fd})},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:Ye.optional(),entityId:y.uuid().optional(),idempotencyKey:y.string().min(1).max(120)}),y.strictObject({internal_feature_id:y.uuid(),quantity:Y.optional(),properties:Ye.optional(),entityId:y.uuid().optional(),idempotencyKey:y.string().min(1).max(120)})])}),response:B.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:B.extend({receipt:Ai})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Ip,response:B.extend({redemption:vp})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Cp,response:B.extend({referralCode:Pp})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Ap,response:B.extend({checkout:wp})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Jd,response:B.extend({seats:Vs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Xd,response:B.extend({seats:Vs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:JS,response:XS},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:fc,response:B.extend({customer:Ur})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Rp,response:B.extend(jp.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Tp,response:B.extend(kp.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:y.object({customerId:y.uuid()}).strict(),response:B.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:B.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:B.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:Qa.optional()}),response:B.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:B.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:B.extend({customer:Ur,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:Dp()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:y.object({}).strict(),response:B.extend({offers:y.array(ks)})},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:Dp()}},tj={setupPayment:M.setupPayment,readPaymentSetup:M.readPaymentSetup,previewSubscriptionBatch:M.previewSubscriptionBatch,confirmSubscriptionBatch:M.confirmSubscriptionBatch,readSubscriptionBatch:M.readSubscriptionBatch,abandonSubscriptionBatch:M.abandonSubscriptionBatch,manageSubscriptionTrial:M.manageSubscriptionTrial,readSubscriptionTrial:M.readSubscriptionTrial,listSubscriptions:M.listSubscriptions,listPurchases:M.listPurchases,listSubscriptionConflicts:M.listSubscriptionConflicts,retrySubscriptionConflict:M.retrySubscriptionConflict,readAiPricing:M.readAiPricing,readUsage:M.readUsage,setUsage:M.setUsage,previewRefund:M.previewRefund,refund:M.refund,readRefund:M.readRefund,previewUpdate:M.previewUpdate,update:M.update,readSubscriptionUpdate:M.readSubscriptionUpdate,restoreNativePurchase:M.restoreNativePurchase,verifySubscriptions:M.verifySubscriptions,previewAttach:M.previewAttach,attach:M.attach,readSubscriptionOperation:M.readSubscriptionOperation,manageBalanceGrant:M.manageBalanceGrant,readBalanceSource:M.readBalanceSource,adjustBalance:M.adjustBalance,listBalanceGrants:M.listBalanceGrants,readBillingControls:M.readBillingControls,prepareBillingAuthorization:M.prepareBillingAuthorization,confirmBillingAuthorization:M.confirmBillingAuthorization,setBillingCoupons:M.setBillingCoupons,revokeBillingAuthorization:M.revokeBillingAuthorization,listBillingInvoices:M.listBillingInvoices,confirmBillingAdjustment:M.confirmBillingAdjustment,manageBillingLimits:M.manageBillingLimits,createCustomer:M.createCustomer,getCustomer:M.getCustomer,listCustomers:M.listCustomers,updateCustomer:M.updateCustomer,createSession:M.createSession,renewSession:M.renewSession,revokeSessions:M.revokeSessions,createGuestCustomer:M.createGuestCustomer,resumeGuestSession:M.resumeGuestSession,claimGuestCustomer:M.claimGuestCustomer,checkEntitlement:M.checkEntitlement,resolveOffering:M.resolveOffering,resolvePaywall:M.resolvePaywall,readHoldings:M.readHoldings,readLedger:M.readLedger,readBillingInvoice:M.readBillingInvoice,readCreditStatement:M.readCreditStatement,quoteBalance:M.quoteBalance,trackUsage:M.trackUsage,mutateBalance:M.mutateBalance,manageUsageEntity:M.manageUsageEntity,readUsageAnalytics:M.readUsageAnalytics,readCreditAnalytics:M.readCreditAnalytics,submitUsageBatch:M.submitUsageBatch,readUsageBatch:M.readUsageBatch,listOffers:M.listOffers,grantOffer:M.grantOffer,redeemCoupon:M.redeemCoupon,redeemReward:M.redeemReward,createReferralCode:M.createReferralCode,claimRewardProduct:M.claimRewardProduct,readSeats:M.readSeats,manageSeat:M.manageSeat};var et={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},rj="00000000-0000-0000-0000-000000000000";var Up={primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},Ui=(e,t,n,r,i)=>({kind:"screen",schemaVersion:4,name:e,surface:"popup",presentation:{type:"modal",size:"md"},theme:{...Up},pages:[{id:"main",name:"\u4E3B\u9875\u9762",root:t}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":n,en:r}},actions:i}),Mr=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}}}),Za={id:"dismiss",type:"close",event:"popup.dismissed",properties:{},close:!0},Fp=[{id:"blank",label:"\u7A7A\u767D",description:"\u4E00\u4E2A\u6807\u9898\u548C\u4E00\u4E2A\u6309\u94AE\uFF0C\u4ECE\u96F6\u5F00\u59CB\u642D\u3002",document:Ui("\u672A\u547D\u540D\u5F39\u7A97",Mr([{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"},[Za])},{id:"announcement",label:"\u516C\u544A",description:"\u65B0\u529F\u80FD\u6216\u91CD\u8981\u901A\u77E5\uFF0C\u4E00\u4E2A\u4E3B\u6309\u94AE\u3002",document:Ui("\u65B0\u529F\u80FD\u516C\u544A",Mr([{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},Za])},{id:"upgrade",label:"\u5347\u7EA7\u5230 Pro",description:"\u5217\u51FA\u51E0\u9879\u6743\u76CA\uFF0C\u5F15\u5BFC\u5347\u7EA7\u3002",document:Ui("\u5347\u7EA7\u5230 Pro",Mr([{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},Za])},{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:{...Ui("\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},Za]),theme:{...Up,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:Ui("\u6EE1\u610F\u5EA6\u8C03\u67E5",Mr([{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 Ya(e="blank"){let t=Fp.find(n=>n.id===e)??Fp[0];return structuredClone(t.document)}var t0=(e,t,n)=>({type:"stack",id:e,name:"Web \u81EA\u9002\u5E94\u5E03\u5C40",direction:"horizontal",align:"center",justify:"center",children:[{...Mr(t),id:`${e}_intro`,name:"\u4ECB\u7ECD",style:{width:480,gap:20,padding:{top:0,right:0,bottom:0,left:0}}},{...Mr(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 aj(e,t="blank"){let n=Ya(t);if(e==="popup"||(n.surface=e,n.presentation={type:"fullscreen"},e==="page"))return n;if(e==="paywall"){let r=Ya("upgrade");r.actions=r.actions.map(a=>a.id==="upgrade"&&a.type==="event"?{...a,event:"paywall.upgrade_clicked",properties:{},close:!1}:a),r.strings.locales["zh-CN"].cta="\u4E86\u89E3\u5347\u7EA7\u65B9\u6848",r.strings.locales.en.cta="Explore upgrade options",r.strings.locales["zh-CN"].body="\u4E3A\u4F60\u7684\u5DE5\u4F5C\u533A\u9009\u62E9\u9002\u5408\u7684\u529F\u80FD\u4E0E\u534F\u4F5C\u65B9\u5F0F\u3002",r.strings.locales.en.body="Find the right features and collaboration tools for your workspace.";let i=r.pages[0].root.children;return r.pages[0].root=t0("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 Mp(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=Ya();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"?{height:280}:{},children:[]}}],strings:{defaultLocale:t,locales:{[t]:{}}},actions:[]}}import{z as fe}from"zod";var Mi=fe.number().int().min(0).max(1e4),dj=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:Mi,snapshotHash:fe.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:fe.iso.datetime({offset:!0})}),n0=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:Mi,issued:Mi,skipped:Mi,remaining:Mi,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)),r0=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:va.nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),mj=fe.strictObject({batch:n0,recipients:fe.array(r0).max(50),nextPosition:fe.number().int().min(1).max(1e4).nullable()}),pj=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 L}from"zod";var vt=L.number().int().min(0),Bi=L.iso.datetime({offset:!0}),Ja=L.strictObject({internalId:L.uuid(),version:L.number().int().positive()}),Bp=L.enum(["subscription_change_required","unsupported_operation_input"]),i0=L.enum([...Bp.options,"internal_error"]),hj=L.strictObject({productId:L.string().min(1),productName:L.string(),from:Ja,to:Ja,noBillingChanges:L.boolean(),counts:L.strictObject({customers:vt,movable:vt,blocked:vt,unsupported:vt,canceled:vt,custom:vt}),rows:L.array(L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),holdings:L.number().int().positive(),outcome:L.enum(["move","blocked","unsupported"]),reason:Bp.nullable()})).max(50),nextCursor:L.uuid().nullable()}),a0=L.enum(["queued","running","succeeded","no_changes","failed","canceled"]),Lp=L.enum(["running","succeeded","skipped","failed"]),qp=L.strictObject({internalId:L.uuid(),id:L.string().min(1),productId:L.string().min(1),productName:L.string(),from:Ja,to:Ja,noBillingChanges:L.boolean(),retryFailed:L.boolean(),step:L.enum(["queued","received","get_customers","migrate_customers","finished","failed"]),snapshot:L.strictObject({total_customers:vt,canceled_customers:vt,custom_customers:vt,migration_customers:vt}),createdAt:Bi,run:L.strictObject({id:L.uuid(),status:a0,errorMessage:L.string().nullable(),createdAt:Bi,startedAt:Bi.nullable(),finishedAt:Bi.nullable()}).nullable(),totals:L.strictObject({succeeded:vt,skipped:vt,failed:vt,running:vt,blocked:vt,remaining:vt})}),o0=L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),status:Lp,skipReason:L.enum(["no_updates_needed","ineligible"]).nullable(),updatedAt:Bi,error:L.strictObject({code:i0,message:L.string().nullable()}).nullable()}),bj=L.strictObject({migration:qp,items:L.array(o0).max(50),nextCursor:L.uuid().nullable()}),_j=L.array(qp).max(20),yj=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),requestId:L.uuid(),fromInternalId:L.uuid(),toInternalId:L.uuid()}),L.strictObject({action:L.enum(["process","retry","cancel"]),migrationId:L.uuid()})]),Sj=L.discriminatedUnion("action",[L.strictObject({action:L.literal("preview"),from:L.uuid(),to:L.uuid(),after:L.uuid().optional()}),L.strictObject({action:L.literal("read"),migrationId:L.uuid(),status:Lp.optional(),after:L.uuid().optional()}),L.strictObject({action:L.literal("list"),productId:L.string().min(1).max(120)})]);import{z as ft}from"zod";var gc=ft.iso.datetime({offset:!0}),Vp=ft.strictObject({internalId:ft.uuid(),productId:ft.string().min(1),name:ft.string(),version:ft.number().int().positive()}),s0=ft.strictObject({id:ft.uuid(),status:ft.literal("scheduled"),effectiveAt:gc,createdAt:gc,entityId:ft.string().nullable(),to:Vp,from:Vp.extend({customerProductId:ft.uuid(),status:ft.enum(["active","past_due","trialing"]),endsAt:gc.nullable()}).nullable(),scheduleId:ft.uuid().nullable(),providerManaged:ft.boolean()}),Ij=ft.array(s0).max(100),Aj=ft.strictObject({customerProductId:ft.uuid()});import{z as Li}from"zod";var c0=Li.url().refine(e=>new URL(e).protocol==="https:"),Pj=Li.strictObject({requestId:Li.uuid()}),Oj=Li.strictObject({url:c0,createdAt:Li.iso.datetime()});import{z as Ze}from"zod";var $p=Ze.object({id:Ze.uuid(),key:Ze.string().nullable(),label:Ze.string().min(1).max(80),description:Ze.string().max(300),category:Ze.string().min(1).max(40),tags:Ze.array(Ze.string().max(30)).max(10),surface:ac,source:Ze.enum(["official","private"]),document:kt,revision:Ze.number().int().positive(),archived_at:Ze.string().nullable(),created_at:Ze.string()}).strict(),Rj=Ze.object({projectId:Ze.uuid(),environmentId:Ze.uuid(),label:Ze.string().trim().min(1).max(80),description:Ze.string().trim().max(300),category:Ze.string().trim().min(1).max(40),document:kt}).strict(),jj=Ze.object({projectId:Ze.uuid(),environmentId:Ze.uuid(),id:Ze.uuid(),revision:Ze.number().int().positive()}).strict();import{z as H}from"zod";import{z as Se}from"zod";var Br=Oe;function Gp(e){let t={};for(let[n,r]of Object.entries(e.results??{})){let i=n.split(".");if(i.some(o=>["__proto__","constructor","prototype"].includes(o)))throw new Error("Reserved result path");let a=t;for(let o of i.slice(0,-1)){Object.hasOwn(a,o)||(a[o]={});let s=a[o];if(!s||typeof s!="object"||Array.isArray(s))throw new Error("Ambiguous result path");a=s}a[i[i.length-1]]=r}return{...e.attributes,parameters:e.parameters,answers:e.answers,results:t}}function hc(e,t){return Ft(Gp(t),e,t.savedGroups)}function qi(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i.startsWith("$")||t.add(i),i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.attributeKey=="string"&&t.add(a.attributeKey),["$and","$or","$nor","$not"].includes(i)&&n(a)}return n(e),[...t]}import{z as rt}from"zod";var Xa=rt.discriminatedUnion("kind",[rt.object({kind:rt.literal("ledger"),cursor:Ea}).strict(),rt.object({kind:rt.literal("billing"),cursor:rt.uuid()}).strict()]),u0=rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Vi=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"),l0=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function bc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>bc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||l0.test(n)||bc(r,t+1)))}var d0=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,an=rt.record(u0,Oe).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!bc(e)&&!d0.test(JSON.stringify(e)),"Credentials cannot be screen parameters");function Lj(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 an.parse(t),t}var Kp=rt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_c=rt.array(rt.object({key:Kp,componentId:Kp,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"),qj=rt.object({bindings:_c,answers:Vi}).strict();var eo=Se.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),yc=Se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),to=an.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Sc=Se.record(eo,Se.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),m0=Se.discriminatedUnion("source",[Se.strictObject({source:Se.literal("literal"),value:Br}),Se.strictObject({source:Se.enum(["parameter","answer","attribute","result"]),key:yc})]),Hp=Se.strictObject({type:Se.literal("external_task"),endpointId:Se.uuid(),taskKey:eo,inputs:Se.record(eo,m0).refine(e=>Object.keys(e).length<=20),outputs:Sc}),Wp=Se.strictObject({maxAttempts:Se.number().int().min(1).max(5),retryDelaySeconds:Se.number().int().min(1).max(30),backoff:Se.enum(["fixed","exponential"]),requestTimeoutSeconds:Se.number().int().min(1).max(10),timeoutSeconds:Se.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline"),Wj={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},zj=Se.strictObject({outcome:Se.enum(["success","failure"]),data:to});function Qj(e,t){let n=to.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 Zj(e,t){let n={};for(let[r,i]of Object.entries(e))if(i.source==="literal")n[r]=i.value;else{let a=i.source==="answer"?t.answers:i.source==="parameter"?t.parameters:i.source==="attribute"?t.attributes:t.results??{};if(!Object.hasOwn(a,i.key))throw new Error("Task input is missing");n[r]=a[i.key]}return to.parse(n)}var Yj=Se.discriminatedUnion("operation",[Se.strictObject({operation:Se.literal("signal"),runId:Se.uuid(),nodeId:yc,eventName:eo,eventId:Se.uuid(),data:to}),Se.strictObject({operation:Se.literal("read_results"),runId:Se.uuid()})]),Jj=Se.strictObject({scope:Ue,runId:Se.uuid(),eventId:Se.uuid(),accepted:Se.boolean()}),p0=Se.record(yc,Br),Xj=Se.strictObject({scope:Ue,runId:Se.uuid(),results:p0});import{z as ge}from"zod";var xc=ge.discriminatedUnion("type",[ge.strictObject({type:ge.literal("literal"),value:Oe}),ge.strictObject({type:ge.literal("feature"),featureKey:ge.string().min(1).max(128)})]),f0=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:Oe}),vc={funnelId:ge.uuid(),requestId:ge.uuid(),customer:Dr,customerData:Fr.optional(),attributes:Jt.refine(e=>!["parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"parameters, answers and results are reserved flow namespaces")},a2=ge.discriminatedUnion("operation",[ge.strictObject({operation:ge.literal("decide"),...vc}).refine(pr,fr),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()})]),o2=ge.strictObject({scope:Ue,decisionId:ge.uuid(),requestId:ge.uuid(),status:ge.enum(["pending","completed","failed"]),decision:f0.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"),s2=ge.strictObject({scope:Ue,decisionId:ge.uuid(),eventId:ge.uuid(),source:ge.literal("caller_reported")});import{z as He}from"zod";var g0=["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"],no=He.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),h0=He.discriminatedUnion("source",[He.strictObject({source:He.literal("literal"),value:Oe}),He.strictObject({source:He.enum(["parameter","answer","attribute","result"]),key:He.string().min(1).max(128)})]),zp=He.discriminatedUnion("type",[Hp,He.strictObject({type:He.literal("claim_offer"),couponId:He.uuid()}),He.strictObject({type:He.literal("event"),event:no}),He.strictObject({type:He.literal("open_url"),url:He.url().refine(e=>new URL(e).protocol==="https:")}),He.strictObject({type:He.literal("api"),operation:He.enum(g0),inputs:He.record(no,h0).refine(e=>Object.keys(e).length<=40),resultKey:no,outputs:He.record(no,He.strictObject({path:He.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+){0,9}$/).max(255),type:He.enum(["string","number","boolean","strings"])})).refine(e=>Object.keys(e).length<=20)})]);function p2(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{if(r.source==="literal")return[n,r.value];let i=r.source==="parameter"?t.parameters:r.source==="answer"?t.answers:r.source==="attribute"?t.attributes:t.results??{};if(!Object.hasOwn(i,r.key))throw new Error("Capability input is missing");return[n,Oe.parse(i[r.key])]}))}import{z as b0}from"zod";var fn=b0.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 tt=H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_0=H.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),on={id:tt,name:H.string().trim().min(1).max(80),position:H.strictObject({x:H.number().finite(),y:H.number().finite()}).optional()},y0={success:tt,cancel:tt,unavailable:tt,failure:tt},S0=H.discriminatedUnion("type",[H.strictObject({...on,type:H.literal("entry"),next:tt}),H.strictObject({...on,type:H.literal("screen"),screenId:tt,presentation:An,outputs:H.record(tt,tt),offering:H.discriminatedUnion("source",[H.strictObject({source:H.literal("result"),key:fn}),H.strictObject({source:H.literal("fixed"),versionId:H.uuid()})]).optional()}),H.strictObject({...on,type:H.literal("offering"),configuration:H.discriminatedUnion("source",[H.strictObject({source:H.literal("fixed"),versionId:H.uuid()}),H.strictObject({source:H.literal("feature"),featureKey:H.string().min(1).max(128)})]),resultKey:fn,next:tt}),H.strictObject({...on,type:H.literal("coupon"),couponId:H.uuid(),resultKey:fn,next:tt}),H.strictObject({...on,type:H.literal("output"),value:H.discriminatedUnion("type",[...xc.options,H.strictObject({type:H.literal("result"),key:fn}),H.strictObject({type:H.literal("selection"),screenId:tt,offeringKey:fn})])}),H.strictObject({...on,type:H.literal("condition"),cases:H.array(H.strictObject({condition:yt,target:tt})).min(1).max(50),default:tt}),H.strictObject({...on,type:H.literal("feature"),featureKey:H.string().min(1).max(128),next:tt}),H.strictObject({...on,type:H.literal("split"),experimentId:H.uuid(),routes:H.record(_0,tt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:tt}),H.strictObject({...on,type:H.literal("action"),...y0,execution:Wp,action:zp}),H.strictObject({...on,type:H.literal("end"),outcome:H.enum(["completed","closed","ineligible","failed"]),output:xc.optional()}),H.strictObject({...on,type:H.literal("wait"),wait:H.discriminatedUnion("type",[H.strictObject({type:H.literal("duration"),delaySeconds:H.number().int().min(1).max(2592e3),elapsed:tt}),H.strictObject({type:H.literal("event"),eventName:tt,outputs:Sc,timeoutSeconds:H.number().int().min(1).max(2592e3),received:tt,timeout:tt})])})]),Ic=H.strictObject({version:H.literal(4),entry:tt,nodes:H.array(S0).min(1).max(et.flowNodes)}),Ac=Ic.superRefine((e,t)=>{x0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Lr(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"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function x0(e,t){let n=[],r=new Map(e.nodes.map(u=>[u.id,u])),i=(u,d,m)=>{n.push(u),t?.({message:u,reason:d,path:m?["nodes",e.nodes.indexOf(m)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(u=>u.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(u=>u.type==="screen").length>et.pages||e.nodes.filter(u=>!["screen","entry","end","output"].includes(u.type)).length>et.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let u of e.nodes){for(let d of Lr(u))d===e.entry&&i("An entry cannot be a transition target","entryTarget",u),r.has(d)||i(`Missing target ${d}`,"missingTarget",u);u.type==="screen"&&(a.has(u.screenId)&&i("Every screen has exactly one node owner","screenOwner",u),a.add(u.screenId))}let o=new Set,s=new Set,c=new Set;function l(u){if(o.has(u)){i("Flow edges must not form a cycle","cycle",r.get(u));return}if(!(s.has(u)||!r.has(u))){o.add(u),c.add(u);for(let d of Lr(r.get(u)))l(d);o.delete(u),s.add(u)}}l(e.entry);for(let u of e.nodes)c.has(u.id)||i("Every node must be reachable from Entry","unreachable",u);return[...new Set(n)]}function v0(e,t){let n=e.cases.findIndex(r=>hc(r.condition,t));return{ruleIndex:n<0?null:n,target:n<0?e.default:e.cases[n].target}}function C2(e,t,n,r){let i=e.nodes.find(c=>c.id===t.nodeId),a=[...t.history];if(!i||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let o,s=[];switch(n.type){case"start":if(i.type!=="entry")throw new Error("Flow already started");o=i.next;break;case"next":if(i.type!=="screen"||!Object.hasOwn(i.outputs,n.output))throw new Error("Invalid screen output");o=i.outputs[n.output],a.push(i.id);break;case"back":if(i.type!=="screen"||!a.length)throw new Error("No previous screen");if(o=a.pop(),e.nodes.find(c=>c.id===o)?.type!=="screen")throw new Error("Invalid screen history");break;case"condition":if(i.type!=="condition")throw new Error("Not a condition node");{let c=v0(i,r);o=c.target,s.push({nodeId:i.id,...c})}break;case"feature":if(i.type!=="feature")throw new Error("Not a Feature node");o=i.next;break;case"configuration":if(i.type!=="offering"&&i.type!=="coupon")throw new Error("Not a configuration node");o=i.next;break;case"assignment":if(i.type!=="split")throw new Error("Not an Experiment node");if(o=n.variantId===null?i.notParticipating:i.routes[n.variantId],!o)throw new Error("Unknown native Variant key");break;case"result":if(i.type!=="action")throw new Error("Not a capability invocation");o=i[n.result];break;case"wait":if(i.type!=="wait")throw new Error("Not a wait node");if(i.wait.type==="duration"){if(n.result!=="elapsed")throw new Error("Invalid timer result");o=i.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid event result");o=i.wait[n.result]}break}if(!e.nodes.some(c=>c.id===o))throw new Error("Target does not exist");return{state:{nodeId:o,history:a.slice(-et.pages),status:"running"},entered:[o],routed:s}}import{z as F}from"zod";function sn(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t[i];if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t[i+1]);)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c,l]=s.split(/[eE]/),u=c.replace(/^-/,""),d=u.replace(".","").length,m=(u.includes(".")?u.indexOf("."):d)+Number(l),g=m<=0?2-m+d:m>=d?m:d+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}function Qp(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let l=r.find(u=>s===u||c&&s.startsWith(u+"."));i.add(l??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 l of qi(c.condition))l.startsWith("results.")&&a(l.slice(8),!0)}if(e.type==="screen"&&e.offering?.source==="result"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="result"&&a(s.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;return o?.type==="result"&&a(o.key),o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as E}from"zod";var qr=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ro=e=>E.record(E.string(),Oe).refine(t=>sn(t)<=e,"Funnel evidence exceeds its byte budget"),D2=E.enum(["presentation","timer","event","operation"]),Cc=E.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Pc=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()})]),F2=E.strictObject({schemaVersion:E.literal(1),kind:Cc,selector:Pc.nullable(),context:ro(131072),contract:E.strictObject({version:E.number().int().positive(),evaluator:E.string().min(1).max(128),policyRevision:E.number().int().nonnegative()})}).refine(e=>sn(e)<=131072,"Node input exceeds its byte budget"),U2=E.strictObject({schemaVersion:E.literal(1),kind:Cc,outcome:E.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:ro(131072),route:E.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:ro(131072)}).refine(e=>sn(e)<=131072,"Node result exceeds its byte budget"),M2=E.strictObject({schemaVersion:E.literal(1),operations:E.record(qr,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:qr,id:E.uuid()}).nullable()}))}).refine(e=>sn(e)<=65536,"Execution state exceeds its byte budget"),gr={receiptId:E.uuid()},wc=E.iso.datetime({offset:!0}),B2=E.discriminatedUnion("type",[E.strictObject({type:E.literal("node_entered"),details:E.strictObject({kind:Cc})}),E.strictObject({type:E.literal("presentation_shown"),details:E.strictObject({...gr,source:E.literal("client"),occurredAt:wc.optional()})}),E.strictObject({type:E.literal("decision_accepted"),details:E.strictObject(gr)}),E.strictObject({type:E.literal("signal_received"),details:E.strictObject({signalId:E.uuid(),nodeId:qr,eventName:qr,data:ro(8192),source:E.literal("server"),occurredAt:wc})}),E.strictObject({type:E.literal("signal_consumed"),details:E.strictObject({...gr,signalId:E.uuid()})}),E.strictObject({type:E.literal("wait_elapsed"),details:E.strictObject(gr)}),E.strictObject({type:E.literal("wait_timeout"),details:E.strictObject(gr)}),E.strictObject({type:E.literal("operation_completed"),details:E.strictObject({...gr,operation:qr,reference:E.strictObject({type:qr,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({...gr,source:E.enum(["client","server"]),occurredAt:wc,reference:E.string().min(1).max(128).optional()})})]);var Ht=F.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),I0=F.discriminatedUnion("type",[F.strictObject({id:Ht,type:F.literal("owned"),document:kt.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:Ht,type:F.literal("paywall"),paywallVersionId:F.uuid()})]),Zp=F.strictObject({type:F.enum(["string","number","boolean","strings","json"]),nullable:F.boolean()}),kc={kind:F.literal("funnel"),schemaVersion:F.literal(3),screens:F.array(I0).max(et.pages),references:F.record(Ht,Pc).refine(e=>Object.keys(e).length<=500),inputs:F.array(F.strictObject({key:Ht,screenId:Ht,componentId:Ht,required:F.boolean()})).max(et.questions),variables:F.record(fn,Zp).refine(e=>Object.keys(e).length<=et.logicNodes),outputSchema:Zp,execution:F.strictObject({runTimeoutSeconds:F.number().int().min(1).max(2592e3),maxTransitions:F.number().int().min(1).max(1e4)})},Lt=F.strictObject({...kc,graph:Ic});function Jp(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])),a=(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 o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(f=>g!==f&&f.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function l(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],x=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(x&&!a("flag",x)&&n("Flag selectors require an explicit GB resource reference","feature",h),f.type==="feature"&&l(f.featureKey,f),(f.type==="offering"||f.type==="coupon")&&l(f.resultKey,f),f.type==="action"&&f.action.type==="api"&&l(f.action.resultKey,f),f.type==="action"&&f.action.type==="external_task")for(let I of Object.keys(f.action.outputs))l(`${f.id}.${I}`,f);if(f.type==="wait"&&f.wait.type==="event")for(let I of Object.keys(f.wait.outputs))l(`${f.id}.${I}`,f);if(f.type==="split"&&!a("experiment",f.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),f.type==="coupon"&&!a("reward",f.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),f.type==="action"&&f.action.type==="claim_offer"&&!a("reward",f.action.couponId)&&n("Coupon claims require a Reward reference","coupon",h),f.type==="offering"&&f.configuration.source==="fixed"&&!a("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"&&!a("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"&&!a("paywall_version",I.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),I?.type==="owned"){Rr(I.document).some(T=>!T.complete)&&n("Owned screens require complete local content","translations",h);let S=new Set(I.document.actions.map(T=>T.id));(S.size!==Object.keys(f.outputs).length||Object.keys(f.outputs).some(T=>!S.has(T)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),pn(I.document.pages[0].root,T=>{!f.offering&&(T.type==="plan_picker"||(T.type==="stack"||T.type==="button")&&T.bind?.plan||T.type==="customer_data"&&["customer_plans","credit_packs"].includes(T.data.source))&&n("Product presentation requires an Offering Version","offering",h),T.type==="customer_data"&&Object.values(T.data.outputs??{}).some(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"&&!Yp(e.outputSchema,f.output.value)&&n("Terminal output does not match outputSchema","output",h),f.type==="output"&&f.value.type==="literal"&&!Yp(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 mi(I.condition))a("saved_group",S)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let S of qi(I.condition))S.startsWith("answers.")&&!e.inputs.some(T=>T.key===S.slice(8))&&n("Unknown answer reference","answer",h)}}for(let[g,f]of e.graph.nodes.entries())for(let h of Qp(f,c)){let S=function(T){if(T===f.id)return!0;if(I.has(T))return!1;I.add(T);let D=e.graph.nodes.find(be=>be.id===T);return D?(x.has(T)?D.type==="action"?[D.cancel,D.unavailable,D.failure]:D.type==="wait"&&D.wait.type==="event"?[D.wait.timeout]:[]:Lr(D)).some(S):!1};var m=S;if(!Object.hasOwn(e.variables,h)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let x=s.get(h)??new Set,I=new Set;(!x.size||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),x=h?.type==="owned"?Fi(h.document,f.componentId):null;(x?.type!=="stack"||!x.interaction||!["input","toggle","select","multiselect","tabs"].includes(x.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g])}let u=0,d=0;for(let g of e.screens)g.type==="owned"&&(pn(g.document.pages[0].root,()=>{u++}),d+=g.document.actions.length);(u>et.components||d>et.actions||sn(e)>et.documentBytes)&&n("Funnel document exceeds its budget","budget")}var Xp=F.strictObject({...kc,graph:Ac}).superRefine(Jp),ef=F.strictObject({...kc,graph:Ac,displayName:F.string().trim().min(1).max(80)}).superRefine(Jp);function Yp(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 Oc=F.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),io={requestId:F.uuid(),nodeId:Ht,visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),customerToken:Oc.optional()},A0=F.discriminatedUnion("type",[F.strictObject({type:F.literal("screen"),output:Ht,answers:Vi,selection:F.record(Ht,F.union([F.string().max(200),F.boolean()])).optional()}),F.strictObject({type:F.literal("paywall_quote"),actionId:Ht,productVersionId:F.uuid(),offerId:F.uuid().optional(),nativeOffer:Fn.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"])})]),w0=F.object({nodeId:Ht,visit:F.number().int().nonnegative(),revision:F.number().int().nonnegative(),components:F.record(Ht,F.object({resourceKey:F.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:F.number().int().min(1).max(1e5),after:Xa.nullable(),filter:F.enum(["all","purchase","refund","source","usage","debt","settlement"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),$i=F.discriminatedUnion("operation",[F.strictObject({operation:F.literal("start"),funnelId:F.uuid(),requestId:F.uuid(),customer:Dr.optional(),customerData:Fr.optional(),locale:F.string().min(1).max(35),parameters:an}).refine(pr,fr),F.strictObject({operation:F.literal("get"),data:w0.optional(),purchase:F.strictObject({receiptId:F.uuid(),operationId:F.uuid()}).optional(),customerToken:Oc.optional()}),F.strictObject({operation:F.literal("resume"),requestId:F.uuid(),customerToken:Oc.optional()}),F.strictObject({operation:F.literal("submit"),...io,input:A0}),F.strictObject({operation:F.literal("back"),...io}),F.strictObject({operation:F.literal("shown"),...io}),F.strictObject({operation:F.literal("close"),...io})]);function Ec(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=Ec(n,t);if(r)return r}return null}function C0(e,t,n,r,i){let a=e.graph.nodes.find(l=>l.id===t);if(a?.type!=="screen")throw new Error("Input is only accepted on a screen");let o=e.screens.find(l=>l.id===a.screenId),s=e.inputs.filter(l=>l.screenId===a.screenId),c={...r};for(let[l,u]of Object.entries(n)){let d=s.find(f=>f.key===l);if(!d||o?.type!=="owned")throw new Error("Unknown screen input");let m=Ec(o.document.pages[0].root,d.componentId);if(m?.type!=="stack"||!m.interaction)throw new Error("Input is unavailable");let g=m.interaction;switch(g.type){case"input":if(typeof u!="string"||u.length>g.maxLength)throw new Error("Invalid input text");if(u&&g.keyboard==="email"&&!F.email().safeParse(u).success)throw new Error("Invalid email");if(u&&g.keyboard==="url"&&!F.url().safeParse(u).success)throw new Error("Invalid URL");break;case"toggle":if(typeof u!="boolean")throw new Error("Invalid toggle value");break;case"select":case"tabs":if(typeof u!="string"||!m.children.some(f=>f.id===u&&!f.hidden))throw new Error("Invalid selected option");break;case"multiselect":if(!Array.isArray(u)||new Set(u).size!==u.length||u.length>g.max||i&&u.length<g.min||u.some(f=>!m.children.some(h=>h.id===f&&!h.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}c[l]=u}if(i)for(let l of s){let u=c[l.key];if(l.required&&(u===void 0||u===""||Array.isArray(u)&&u.length===0))throw new Error(`Required input: ${l.key}`);u!==void 0&&!Object.hasOwn(n,l.key)&&C0(e,t,{[l.key]:u},{},!1);let d=o?.type==="owned"?Ec(o.document.pages[0].root,l.componentId):null;if(d?.type==="stack"&&d.interaction?.type==="multiselect"&&Array.isArray(u)&&u.length<d.interaction.min)throw new Error("Not enough selected options")}return c}import{z as ke}from"zod";import{z as P0}from"zod";var Tc=P0.enum(["local","remote"]);var O0=ke.strictObject({id:ke.uuid(),projectId:ke.uuid(),environmentId:ke.uuid(),name:ke.string().min(1).max(80),revision:ke.number().int().nonnegative(),evaluationMode:Tc,evaluationRevision:ke.number().int().nonnegative(),state:ke.enum(["active","paused","archived"]),publishedVersionId:ke.uuid().nullable(),updatedAt:ke.iso.datetime({offset:!0}),draft:Lt}),uN=ke.strictObject({rows:ke.array(O0).max(200),nextCursor:ke.uuid().nullable()}),lN=ke.discriminatedUnion("action",[ke.strictObject({action:ke.literal("setEvaluationMode"),id:ke.uuid(),revision:ke.number().int().nonnegative(),evaluationMode:Tc}),ke.strictObject({action:ke.literal("create"),requestId:ke.uuid(),name:ke.string().trim().min(1).max(80),document:Lt}),ke.strictObject({action:ke.literal("save"),id:ke.uuid(),revision:ke.number().int().nonnegative(),name:ke.string().trim().min(1).max(80),document:Lt}),ke.strictObject({action:ke.enum(["publish","archive","pause","activate"]),id:ke.uuid(),revision:ke.number().int().nonnegative()})]).superRefine((e,t)=>{(e.action==="create"||e.action==="save")&&sn(e.document)>et.documentBytes&&t.addIssue({code:"custom",path:["document"],message:"Funnel document exceeds its byte budget"})});function dN(e){let t=e==="en",n=Mp("popup",e);return n.name=t?"Welcome":"\u6B22\u8FCE",n.pages[0].root.children=[{id:"heading",type:"text",text:"heading",variant:"title"},{id:"continue_button",type:"button",label:"continue",variant:"primary",action:"continue"}],n.actions=[{id:"continue",type:"event",event:"continue",properties:{},close:!1}],n.strings.locales[e]={heading:t?"Welcome":"\u6B22\u8FCE",continue:t?"Continue":"\u7EE7\u7EED"},Xp.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 de}from"zod";var Vr=de.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Rc=de.enum(["running","waiting","completed","closed","ineligible","failed"]),E0=de.discriminatedUnion("type",[de.strictObject({type:de.literal("wait"),receiptId:de.uuid(),kind:de.enum(["timer","event","operation"]),deadline:de.iso.datetime({offset:!0}).nullable(),eventName:Vr.optional()}),de.strictObject({type:de.literal("open_url"),receiptId:de.uuid(),url:de.url().refine(e=>new URL(e).protocol==="https:")}),de.strictObject({type:de.literal("event"),receiptId:de.uuid(),event:Vr})]),k0=de.strictObject({type:de.literal("funnel"),id:de.uuid(),versionId:de.uuid()}),jc=de.strictObject({id:de.uuid(),source:k0,revision:de.number().int().nonnegative(),visit:de.number().int().nonnegative(),nodeId:Vr,nodeType:de.enum(["entry","screen","condition","split","feature","action","wait","end","offering","coupon","output"]),status:Rc,canBack:de.boolean(),authenticated:de.boolean(),locale:de.string().min(1).max(35),answers:Vi,parameters:an,variables:de.record(de.string(),Oe),output:Oe.nullable(),screen:de.strictObject({id:Vr,document:kt,presentation:An,outputs:de.array(Vr).max(250),inputs:_c,offeringKey:fn.optional(),capabilities:qa,customerData:Gm,dataCursors:de.record(Vr,Xa.nullable())}).nullable(),paywall:de.strictObject({receiptId:de.uuid(),resolution:Ha,quote:Oi.nullable(),operation:Pr.nullable(),purchaseRequestId:de.uuid().nullable()}).nullable(),instruction:E0.nullable(),pendingRequest:de.strictObject({requestId:de.uuid(),authenticationRequired:de.boolean()}).nullable(),runExpiresAt:de.iso.datetime({offset:!0}),credentialExpiresAt:de.iso.datetime({offset:!0}).nullable()}),tf=de.strictObject({scope:Ue,run:jc,purchase:de.strictObject({receiptId:de.uuid(),quote:Oi.nullable(),operation:Pr.nullable()}).optional(),runToken:de.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:de.uuid().optional()});import{z as Rt}from"zod";import{z as ao}from"zod";var PN=ao.strictObject({operation:ao.literal("renew_run"),runId:ao.uuid(),customerId:ao.uuid()}),nf=tf.refine(e=>!!e.runToken,"Renewal returns a credential");var DN=Rt.discriminatedUnion("operation",[Rt.strictObject({operation:Rt.literal("campaign_decide"),...vc}).refine(pr,fr),Rt.strictObject({operation:Rt.literal("campaign_start"),funnelId:Rt.uuid(),requestId:Rt.uuid(),customer:Dr,customerData:Fr.optional(),locale:Rt.string().min(1).max(35),parameters:an,cooldownSeconds:Rt.number().int().min(1).max(2592e3)}).refine(pr,fr)]),FN=Rt.union([Rt.strictObject({scope:Ue,suppressed:Rt.literal(!0),reason:Rt.enum(["frequency","in_progress"]),retryAt:Rt.iso.datetime({offset:!0})}),nf]);import{z as Ve}from"zod";import{z as R}from"zod";var Nc=R.tuple([R.number().min(0).max(1),R.number().min(0).max(1)]).refine(([e,t])=>e<=t),T0=R.strictObject({attribute:R.string().optional(),seed:R.string(),hashVersion:R.union([R.literal(1),R.literal(2)]),ranges:R.array(Nc).max(100)}),R0=R.strictObject({id:R.string().min(1).max(255),condition:yt,gate:R.boolean().optional()}),j0=R.strictObject({key:R.string().optional(),name:R.string().optional(),passthrough:R.boolean().optional()}),rf={condition:yt.optional(),parentConditions:R.array(R0).max(100).optional(),weights:R.array(R.number().min(0).max(1)).max(20).optional(),coverage:R.number().min(0).max(1).optional(),hashAttribute:R.string().optional(),fallbackAttribute:R.string().optional(),hashVersion:R.union([R.literal(1),R.literal(2)]).optional(),disableStickyBucketing:R.boolean().optional(),bucketVersion:R.number().int().nonnegative().optional(),minBucketVersion:R.number().int().nonnegative().optional(),filters:R.array(T0).max(100).optional(),namespace:R.tuple([R.string(),R.number().min(0).max(1),R.number().min(0).max(1)]).optional(),ranges:R.array(Nc).max(20).optional(),meta:R.array(j0).max(20).optional(),seed:R.string().optional(),name:R.string().optional(),phase:R.string().optional()},af=R.strictObject({...rf,key:R.string().min(1).max(255),variations:R.tuple([Oe,Oe]).rest(Oe).refine(e=>e.length<=20),urlPatterns:R.array(R.strictObject({include:R.boolean(),type:R.enum(["regex","simple"]),pattern:R.string()})).max(100).optional(),force:R.number().int().nonnegative().optional(),active:R.boolean().optional(),persistQueryString:R.boolean().optional(),status:R.enum(["draft","running","stopped"]).optional(),groups:R.array(R.string()).optional()}),N0=R.strictObject({value:Oe,variationId:R.number().int(),key:R.string(),name:R.string().optional(),bucket:R.number().optional(),passthrough:R.boolean().optional(),inExperiment:R.boolean(),hashUsed:R.boolean().optional(),hashAttribute:R.string(),hashValue:R.string(),featureId:R.string().nullable(),stickyBucketUsed:R.boolean().optional()}),D0=R.strictObject({...rf,id:R.string().max(255).optional(),force:Oe.optional(),variations:R.array(Oe).min(2).max(20).optional(),key:R.string().optional(),range:Nc.optional(),tracks:R.array(R.strictObject({experiment:af,result:N0})).max(100).optional()}),F0=R.strictObject({defaultValue:Oe.optional(),rules:R.array(D0).max(500).optional()}),U0=R.record(R.string(),R.union([R.array(R.union([R.string(),R.number()])),R.strictObject({type:R.literal("list"),attributeKey:R.string(),values:R.array(R.union([R.string(),R.number()])),useEmptyListGroup:R.boolean().optional()}),R.strictObject({type:R.literal("condition"),condition:yt})])),Gi=R.strictObject({scope:Ue,generation:R.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:R.iso.datetime({offset:!0}),expiresAt:R.iso.datetime({offset:!0}).nullable(),features:R.record(R.string(),F0),savedGroups:U0,experiments:R.record(R.uuid(),af)});function of(e,t){let n=new Set,r=new Set,i=new Set,a=[];function o(d){for(let m of mi(d))s(m)}function s(d){i.has(d)||!Object.hasOwn(t.savedGroups,d)||(i.add(d),a.push(()=>{let m=t.savedGroups[d];!Array.isArray(m)&&m.type==="condition"&&o(m.condition)}))}function c(d){o(d.condition);for(let m of d.parentConditions??[])l(m.id),o(m.condition)}function l(d,m=!1){if(!Object.hasOwn(t.features,d)){if(m)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),a.push(()=>{for(let g of t.features[d].rules??[]){c(g);for(let f of g.tracks??[])c(f.experiment)}}))}function u(d){if(!Object.hasOwn(t.experiments,d))throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),a.push(()=>c(t.experiments[d])))}for(let d of e.graph.nodes){d.type==="feature"&&l(d.featureKey,!0),d.type==="split"&&u(d.experimentId),d.type==="condition"&&d.cases.forEach(g=>o(g.condition)),d.type==="offering"&&d.configuration.source==="feature"&&l(d.configuration.featureKey,!0);let m=d.type==="output"?d.value:d.type==="end"?d.output:null;m?.type==="feature"&&l(m.featureKey,!0)}for(let d=0;d<a.length;d++)a[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 Ki=Ve.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),cf=Ve.strictObject({entry:Ki,nodes:Ve.array(Ve.strictObject({id:Ki,type:Ve.enum(["entry","screen","condition","split","feature","action","wait","end","offering","coupon","output"]),outputs:Ve.record(Ve.string(),Ki),resources:Ve.strictObject({screenId:Ki.optional(),paywallVersionId:Ve.uuid().optional(),couponId:Ve.uuid().optional(),experimentId:Ve.uuid().optional(),featureKey:Ve.string().optional(),offeringVersionId:Ve.uuid().optional()})})).min(1).max(500)}),sf={scope:Ue,funnelId:Ve.uuid(),versionId:Ve.uuid(),evaluationRevision:Ve.number().int().nonnegative(),expiresAt:Ve.iso.datetime({offset:!0}).nullable(),topology:cf},M0=Ve.discriminatedUnion("evaluationMode",[Ve.strictObject({...sf,evaluationMode:Ve.literal("local"),growth:Gi,conditions:Ve.record(Ki,Ve.array(Ve.strictObject({condition:yt,port:Ve.string()})))}),Ve.strictObject({...sf,evaluationMode:Ve.literal("remote")})]);function B0(e){return cf.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let i=e.screens.find(a=>a.id===t.screenId);i?.type==="paywall"&&(r.paywallVersionId=i.paywallVersionId)}break;case"condition":t.cases.forEach((i,a)=>{n[`case:${a}`]=i.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let i of["success","cancel","unavailable","failure"])n[i]=t[i];t.action.type==="claim_offer"&&(r.couponId=t.action.couponId);break;case"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 ZN(e){let t=ef.parse(e.document),n=e.evaluationMode==="local"?Gi.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:B0(t)};return M0.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((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}import{z as U}from"zod";var lf={commands:et.flowNodes*4,receipts:et.flowNodes*2,requestBytes:et.documentBytes+2e6},$r=U.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),uf={requestId:U.uuid(),nodeId:$r,visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative()},L0=U.union([$i.options[3].omit({customerToken:!0}),$i.options[4].omit({customerToken:!0}),$i.options[5].omit({customerToken:!0}),$i.options[6].omit({customerToken:!0}),U.strictObject({operation:U.literal("wait"),...uf,result:U.enum(["elapsed","received","timeout"])}),U.strictObject({operation:U.literal("simulate"),...uf,outcome:U.enum(["success","cancel","failure","unavailable"])})]),Dc=U.enum(["success","cancel","failure","unavailable","pending"]),Fc=U.strictObject({seed:U.uuid(),now:U.iso.datetime({offset:!0}),locale:U.string().min(2).max(35),currency:z,parameters:an,attributes:U.record(U.string(),Br).refine(e=>Object.keys(e).length<=100),authenticated:U.boolean(),holdings:U.enum(["sample","empty"]),results:U.record(U.string(),Oe).optional(),outcomes:U.record($r,Dc),variants:U.record($r,U.string().min(1).max(128).nullable())}),Uc=U.strictObject({schemaVersion:U.literal(1),growth:Gi,paywalls:U.record(U.uuid(),Ka),offerings:U.record(U.uuid(),Er),surfaces:U.record($r,Oe)}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=1e6,"Preview dependencies exceed their byte budget"),q0=U.array(U.strictObject({command:L0,authenticated:U.boolean(),outcome:Dc})).max(lf.commands),V0=U.discriminatedUnion("type",[U.strictObject({type:U.literal("draft"),document:Lt}),U.strictObject({type:U.literal("snapshot"),id:U.uuid()})]),uD=U.strictObject({previewId:U.uuid(),source:V0,scenario:Fc,journal:q0,dependencySnapshot:Uc.optional()}),lD=U.strictObject({mode:U.literal("simulation"),run:jc,dependencySnapshot:Uc,traceTruncated:U.boolean(),trace:U.array(U.strictObject({nodeId:$r,visit:U.number().int().nonnegative(),type:U.enum(["entered","shown","assigned","feature_evaluated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:U.record(U.string(),U.union([U.string(),U.number(),U.boolean(),U.null()]))})).max(2e3),receipts:U.array(U.strictObject({id:U.uuid(),nodeId:$r,visit:U.number().int().nonnegative(),outcome:Dc})).max(lf.receipts)}),dD=U.strictObject({id:U.uuid(),projectId:U.uuid(),environmentId:U.uuid(),document:Lt,scenario:Fc,dependencySnapshot:Uc,expiresAt:U.iso.datetime({offset:!0})}),mD=U.discriminatedUnion("action",[U.strictObject({action:U.literal("create"),requestId:U.uuid(),document:Lt,scenario:Fc}),U.strictObject({action:U.literal("revoke"),id:U.uuid()})]);import{z as ve}from"zod";var gD=ve.object({overall:ve.object({entered:ve.number(),running:ve.number(),closed:ve.number(),completed:ve.number(),authenticated:ve.number(),authReached:ve.number(),paid:ve.number(),free:ve.number()}),steps:ve.array(ve.object({node_id:ve.string(),visitors:ve.number()})),edges:ve.array(ve.object({node_id:ve.string(),target:ve.string(),visitors:ve.number()})),currencies:ve.array(ve.object({currency:ve.string(),grossCents:ve.number(),refundCents:ve.number()})),variants:ve.array(ve.object({experimentId:ve.uuid(),revision:ve.number(),variantId:ve.string(),exposed:ve.number(),completed:ve.number(),paid:ve.number(),exposedRuns:ve.number().optional(),completedRuns:ve.number().optional(),paidRuns:ve.number().optional()}))});var Mc={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 _D(e,t,n=[]){let r=Xn(t)??"en",[i,...a]=r.split("-"),o=i==="zh"&&!a.includes("Hans")&&a.some(f=>["Hant","TW","HK","MO"].includes(f))?"zh-Hant":i,s=Mc[o]??Mc.en,c=Mc[o]?r:"en",l=f=>new Intl.NumberFormat(c).format(f),u=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?` (+${l(n.length-3)})`:"")}`:""}`,e.eligibility.firstPurchaseOnly?s[3]:s[2],Object.keys(e.eligibility.condition).length?`${s[4]}${df(e.eligibility.condition)?`: ${df(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),m=[e.startsAt?`${s[5]}: ${u(e.startsAt)}`:null,e.endsAt?`${s[6]}: ${u(e.endsAt)}`:s[7]].filter(Boolean).join(" \xB7 "),g=[d,m,`${s[8]}: ${l(e.grantWindowHours)} ${s[9]}`,`${s[10]}: ${l(e.perCustomerLimit)}`,e.totalLimit===null?null:`${s[11]}: ${l(e.totalLimit)}`].filter(Boolean).join(" \xB7 ");return{eligibility:d,validity:m,terms:g}}function df(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 Bc={"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 mf(e){return e.actions.map(t=>t.properties.templateKey).find(t=>typeof t=="string"&&t.startsWith("popup-coupon-"))}function vD(e,t){let n=mf(e);if(!n||!Object.hasOwn(Bc,n))return e;let r=i=>{let a={...i.root.bind,coupon:t};return i.root.bind?.coupon!==t&&delete a.promotionCode,{bind:a}};return{...e,pages:e.pages.map(i=>({...i,root:{...i.root,...r(i)}})),actions:e.actions.map(i=>i.properties.templateKey===n&&i.type!=="close"?{id:i.id,type:"claim_offer",couponId:t,event:"offer.claimed",properties:i.properties,close:i.close}:i)}}function ID(e){let t=mf(e),n=t?Bc[t]:void 0;return!n||e.actions.some(r=>r.type==="claim_offer")?e:{...e,strings:{...e.strings,locales:Object.fromEntries(Object.entries(e.strings.locales).map(([r,i])=>[r,Object.fromEntries(Object.entries(i).map(([a,o])=>[a,o.replaceAll("{{offer.discount}}",n.discount).replaceAll("{{offer.headline}}",r.startsWith("zh")?n.zh:n.en).replaceAll("{{offer.terms}}",r.startsWith("zh")?"\u6F14\u793A\u91D1\u989D \xB7 \u7ED1\u5B9A\u4F18\u60E0\u5238\u540E\u81EA\u52A8\u663E\u793A\u771F\u5B9E\u6761\u6B3E":"Demo amount \xB7 Bind a coupon to show actual terms")]))]))}}}import{z as te}from"zod";var Wt=te.string().min(1).max(255),Bn=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)}),$0=te.strictObject({feature_id:Wt,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()}),G0=te.strictObject({feature_id:Wt.optional(),enabled:te.boolean().default(!1),limit_type:te.enum(["absolute","usage_percentage"]).optional(),overage_limit:Bn.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"),K0=te.strictObject({feature_id:Wt,enabled:te.boolean().default(!0),limit:Bn,interval:te.enum(["day","week","month","year"]),anchor:te.enum(["billing_cycle","utc"]).optional(),filter:pf.optional()}),H0=te.strictObject({feature_id:Wt.optional(),enabled:te.boolean().default(!0),threshold:Bn,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"),W0=te.strictObject({feature_id:Wt,enabled:te.boolean().default(!1)}),z0=te.strictObject({auto_topups:te.array($0).nullable(),spend_limits:te.array(G0).nullable(),usage_limits:te.array(K0).nullable(),usage_alerts:te.array(H0).nullable(),overage_allowed:te.array(W0).nullable()}),PD=z0.omit({auto_topups:!0}),Q0=Nr,OD=te.strictObject({internal_id:te.uuid(),id:Wt.nullable(),project_id:te.uuid(),environment_id:te.uuid(),name:te.string().max(80).nullable(),email:te.string().max(254).nullable(),metadata:Q0.nullable(),created_at:te.number().finite().nonnegative().max(864e13)}),ED=te.strictObject({id:Wt,internal_product_id:Wt,product_id:Wt.nullable(),status:te.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:Bn.nullable(),free_trial_id:Wt.nullable(),trial_ends_at:Bn.nullable(),starts_at:Bn.nullable(),access_starts_at:Bn.nullable(),ended_at:Bn.nullable(),product:te.strictObject({internal_id:Wt,id:Wt,name:te.string(),version:te.number().int().positive(),is_add_on:te.boolean()})});function jD(e,t,n=[]){let r={nodes:{}},i=t.startsWith("zh"),a=(s,c)=>i?s:c,o=(s,c,l,u,d=[])=>({id:s,label:c,value:l,status:u,detail:d,facts:[]});return Ct(e,s=>{if(s.type!=="customer_data")return;let c={...Km(s.data.source),status:"ready",stale:!1,preview:!0};if(s.data.source==="credit_balance"){let l=s.data.resourceKey??n[0]?.key??"credits";c.resources=[{key:l,name:n.find(u=>u.key===l)?.label??a("\u521B\u4F5C\u79EF\u5206","Creative credits"),spendable:"3,840",available:"4,040",reserved:"200",expiry:a("1,200 \xB7 2026\u5E7411\u67081\u65E5","1,200 \xB7 November 1, 2026"),sources:[o("sample-monthly",a("\u4F1A\u5458\u6708\u5EA6\u79EF\u5206","Monthly membership credits"),"2,640",a("\u53EF\u7528","Available")),o("sample-pack",a("\u8D2D\u4E70\u79EF\u5206\u5305","Purchased credit pack"),"1,200",a("\u53EF\u7528","Available"))],sourceCount:2,sourcePage:1,hasNextSources:!1,hasPreviousSources:!1}]}else s.data.source==="credit_transactions"?(c.rows=[o("sample-usage-1",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67083\u65E5 09:42","Oct 3, 09:42")]),o("sample-usage-2",a("\u89C6\u9891\u751F\u6210","Video generation"),"",a("\u9884\u6263","Reserved"),[a("10\u67083\u65E5 09:30","Oct 3, 09:30")]),o("sample-usage-3",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u9000\u56DE","Refund"),[a("10\u67082\u65E5 16:10","Oct 2, 16:10")]),o("sample-usage-4",a("\u89C6\u9891\u751F\u6210","Video generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67082\u65E5 15:24","Oct 2, 15:24")]),o("sample-usage-5",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67082\u65E5 14:08","Oct 2, 14:08")])].slice(0,s.data.pageSize),c.rows.forEach((l,u)=>{l.facts=[{label:a("\u521B\u4F5C\u79EF\u5206","Creative credits"),value:["12","180","12","180","24"][u]}]})):s.data.source==="membership"?c.rows=[o("sample-plan",a("\u4E13\u4E1A\u7248 \xB7 \u6708\u4ED8","Pro \xB7 Monthly"),"",a("\u6709\u6548","Active"),[a("\u5F53\u524D\u5468\u671F\u7ED3\u675F \xB7 2026\u5E7411\u67081\u65E5","Current period ends \xB7 November 1, 2026")])]:s.data.source==="customer_plans"?c.rows=[o("sample-free",a("\u57FA\u7840\u7248","Starter"),a("\u514D\u8D39","Free"),a("\u53EF\u9009\u62E9","Available")),o("sample-pro",a("\u4E13\u4E1A\u7248","Pro"),a("$29 / \u6708","$29 / month"),a("\u5F53\u524D\u5957\u9910","Current plan")),o("sample-team",a("\u56E2\u961F\u7248","Team"),a("$79 / \u6708","$79 / month"),a("\u53EF\u9009\u62E9","Available"))].slice(0,s.data.pageSize):s.data.source==="billing_controls"?c.rows=[o("sample-control",a("\u6708\u5EA6\u7528\u91CF\u4E0A\u9650","Monthly usage limit"),"240 / 1,000",a("\u793A\u4F8B \xB7 \u672A\u6388\u6743\u4ED8\u6B3E","Sample \xB7 Payments not authorized"),[a("\u4EC5\u5C55\u793A\u793A\u4F8B\uFF0C\u9884\u89C8\u4E0D\u4F1A\u542F\u7528\u81EA\u52A8\u5145\u503C\u6216\u540E\u4ED8\u8D39\u3002","Preview does not authorize auto top-ups or postpaid billing.")])]:s.data.source==="billing"?c.rows=[{...o("sample-invoice","GROW-2026-001","$29.00",a("\u5DF2\u652F\u4ED8","Paid"),["October 1, 2026"]),billingActions:[{action:"invoice_open",label:a("\u67E5\u770B\u53D1\u7968","View invoice")}]}]:s.data.source==="credit_packs"?c.rows=[o("sample-pack-small",a("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12","",[a("1,200 \u79EF\u5206 \xB7 90 \u5929\u6709\u6548","1,200 credits \xB7 90 days validity")]),o("sample-pack-large",a("\u521B\u4F5C\u6269\u5C55\u5305","Creative expansion"),"$40","",[a("5,000 \u79EF\u5206 \xB7 180 \u5929\u6709\u6548","5,000 credits \xB7 180 days validity")])].slice(0,s.data.pageSize).map((l,u)=>({...l,...s.data.allowPurchase?{purchaseId:`10000000-0000-4000-8000-${String(u+1).padStart(12,"0")}`}:{}})):s.data.source==="credit_pack_orders"?c.rows=[o("sample-order",a("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12",a("\u5DF2\u4ED8\u6B3E","Paid"),["2026-10-01 12:30"])]:c.rows=[o("sample-offer",a("\u4F1A\u5458\u7EED\u8D39\u4F18\u60E0","Membership renewal offer"),"",a("\u53EF\u7528","Available"),[a("2026\u5E7411\u67081\u65E5\u5230\u671F","Expires November 1, 2026")])];r.nodes[s.id]=c}),r}import{z as Te}from"zod";import{z as me}from"zod";var Z0=me.enum(["customer","coupon","audience"]),Y0=me.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),oo=me.object({baseRevision:me.number().int().nonnegative(),latestRevision:me.number().int().nonnegative(),mode:me.enum(["merge","use_latest"]),decisions:me.array(me.object({field:Y0,mine:me.number().int().min(0).max(1e3),latest:me.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),ff=me.number().int().nonnegative().nullable(),J0=me.object({resource:Z0,id:me.uuid(),projectId:me.uuid(),environmentId:me.uuid(),fromRevision:ff,toRevision:ff,provenance:me.enum(["recorded","historical"]),changes:me.array(me.object({field:me.string(),redacted:me.boolean(),before:me.union([me.string(),me.number(),me.boolean(),me.null()]),after:me.union([me.string(),me.number(),me.boolean(),me.null()])})),merge:oo.safeExtend({source:me.literal("client")}).nullable()}),X0=me.object({createdAt:me.iso.datetime({offset:!0}),id:me.uuid()}).strict(),FD=me.object({events:me.array(me.object({id:me.uuid(),action:me.string(),actorId:me.uuid().nullable(),actorEmail:me.email().nullable(),createdAt:me.iso.datetime({offset:!0}),object:J0})),nextCursor:X0.nullable()});var qD={type:"condition",condition:{}},VD=Te.strictObject({id:Te.uuid(),name:Te.string().min(1).max(80),description:Te.string().max(500),config:Sa,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})}),$D=Te.discriminatedUnion("action",[Te.strictObject({action:Te.literal("save"),id:Te.uuid().nullable(),audit:oo.nullable().optional(),revision:Te.number().int().min(0),name:Te.string().trim().min(1).max(80),description:Te.string().max(500),config:Sa}),Te.strictObject({action:Te.literal("archive"),id:Te.uuid(),audit:oo.nullable().optional(),revision:Te.number().int().min(1)})]),ex=Te.object({id:Te.uuid(),name:Te.string().nullable(),external_user_id:Te.string(),attributes:Jt,created_at:Te.iso.datetime({offset:!0})}),GD=Te.object({customers:ex.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 zD=Hi.object({defaultLocale:xn,locales:Hi.record(xn,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 QD(e,t){let n=e.displayCopy;if(!n)return{name:e.name,description:""};let r=Object.keys(n.locales).filter(s=>n.locales[s].name.trim()),i=xa([t],r,n.defaultLocale),a=n.locales[i],o=n.locales[n.defaultLocale];return{name:a?.name.trim()?a.name:o?.name.trim()?o.name:e.name,description:a?.description.trim()?a.description:o?.description.trim()?o.description:""}}var gf="#172033",so="#667085",tx="#E2E6EE",nx="#2C3C96",Pt=e=>({top:e,right:e,bottom:e,left:e}),gt=e=>({type:"color",color:e}),qt=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,a=so,o={}){return this.zh[t]=n,this.en[t]=r,{id:t,type:"text",text:t,variant:i>=30?"title":"body",style:{text:{size:i,color:a,weight:i>=30?600:400,lineHeight:1.35,...i>=30?{letterSpacing:-1.2}:{}},...o}}}stack(t,n,r={},i=!1){return{id:t,type:"stack",direction:i?"horizontal":"vertical",align:"stretch",justify:"start",children:n,style:{gap:i?40:24,...r}}}widget(t,n,r,i,a=!1,o={}){let s=t+"_title";return this.zh[s]=r,this.en[s]=i,{id:t,type:"customer_data",title:s,data:{source:n,layout:a?"compact":"full",pageSize:n==="credit_transactions"?5:4,showSources:n==="credit_balance"&&!a,allowPurchase:n==="credit_packs"},style:o}}rule(t,n=tx){return{id:t,type:"divider",style:{background:gt(n),height:1}}}header(t,n,r,i,a,o=!1){return this.stack("account_header",[this.stack("intro",[this.text("eyebrow","\u5DE5\u4F5C\u7A7A\u95F4 / \u8D26\u6237","WORKSPACE / ACCOUNT",11,o?"#A9B4CB":so,{text:{size:11,color:o?"#A9B4CB":so,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,o?"#FFFFFF":gf),this.text("description",r,i,14,o?"#A9B4CB":so)],{gap:12,width:660,grow:!0}),...a?[a]:[]],{gap:32},!0)}document(t,n=!1){return kt.parse({kind:"screen",schemaVersion:4,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:nx,background:n?"#101A30":"#F5F6FA",text:gf,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 uo="#19202E",rx="#667080",Lc="#2C3C96",hf="#DDE2E9",bf="#F0F3FA",ix=(e=72,t=uo)=>({text:{size:e,color:t,weight:600,font:"system"}}),co=(e,t=1)=>({width:e,grow:t}),ax={background:gt("#FFFFFF"),shape:{type:"rect",radius:10}};function ox(e){return new qt(e,{theme:{background:"#FFFFFF",text:uo,primary:Lc},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function sx(e,t,n,r,i){let a=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,Lc,{text:{size:13,color:Lc,weight:700,letterSpacing:.8}});return e.stack("page_header",[a,e.text("heading",t,n,40,uo,{text:{size:40,color:uo,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,rx)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function _f(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new qt("\u8D26\u6237\u4E00\u89C8",{theme:{background:e,text:t,primary:n,radius:"none"},width:1120,gap:36,padding:{top:32,right:24,bottom:48,left:24}}),a=(o,s,c)=>i.text(o,s,c,12,n,{text:{size:12,color:n,font:"mono",weight:500,letterSpacing:1.1}});return i.document([i.stack("journal_masthead",[i.stack("journal_identity",[i.text("wordmark","GROW","GROW",22,t,{text:{size:22,color:t,weight:700,letterSpacing:-1}}),a("edition","\u8D26\u6237 / ACCOUNT","ACCOUNT / JOURNAL")],{gap:16},!0),i.rule("masthead_rule",t),i.stack("journal_intro",[i.text("heading","\u8D26\u6237\u4E00\u89C8","Your account.",64,t,{width:720,grow:2,text:{size:64,color:t,font:"serif",weight:400,lineHeight:1.12,letterSpacing:-2}}),i.stack("intro_note",[a("intro_index","\u4E3A\u4F60\u7684\u4E0B\u4E00\u6B21\u521B\u4F5C","FOR YOUR NEXT CHAPTER"),i.text("description",`\u4F60\u7684\u4F1A\u5458\u3001\u79EF\u5206\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C
|
|
18
|
+
\u5728\u4E00\u5904\u4ECE\u5BB9\u638C\u63E1\u3002`,`Membership, credits and purchases.
|
|
19
|
+
A little clarity for what's next.`,14,r)],{width:300,grow:1,gap:12,padding:{top:8,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("account_summary",[i.stack("member_column",[a("member_index","01 / \u4F1A\u5458","01 / MEMBERSHIP"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:t,font:"serif",size:40,weight:400}})],{width:660,grow:2,gap:16}),i.stack("balance_column",[a("balance_index","02 / \u79EF\u5206","02 / CREDITS"),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:t,font:"serif",size:64,weight:400}})],{width:340,grow:1,gap:16})],{gap:48,padding:{top:12,right:0,bottom:12,left:0}},!0),i.rule("records_rule","#D9CFC1"),i.stack("account_records",[i.stack("purchase_column",[a("purchase_index","03 / \u8D2D\u4E70\u8BB0\u5F55","03 / PURCHASES"),i.widget("orders","credit_pack_orders","\u6BCF\u4E00\u7B14\u8D2D\u4E70","Your purchases",!1,{text:{color:t}})],{width:660,grow:2,gap:16}),i.stack("offer_column",[a("offer_index","04 / \u4E13\u5C5E\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u53EF\u7528\u4F18\u60E0","Available offers",!0,{text:{color:t}})],{width:340,grow:1,gap:16})],{gap:48},!0),i.rule("catalog_rule","#D9CFC1"),i.stack("account_catalog",[a("catalog_index","05 / \u65B9\u6848","05 / PLANS"),i.widget("plans","customer_plans","\u63A2\u7D22\u9002\u5408\u4F60\u7684\u65B9\u6848","Find your next plan",!0,{text:{color:t}})],{gap:16}),i.text("journal_footer","GROW / \u8BA9\u521B\u4F5C\u7EE7\u7EED","GROW / KEEP CREATING",11,r,{text:{size:11,color:r,font:"mono",letterSpacing:1}})])}function yf(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new qt("\u79EF\u5206\u5DE5\u4F5C\u53F0",{theme:{background:"#EDF1F7",text:e,primary:"#244F9E",radius:"sm"},width:1200,gap:24,padding:{top:24,right:24,bottom:40,left:24}}),i=(a,o,s)=>r.text(a,o,s,11,t,{text:{size:11,color:t,font:"mono",weight:500,letterSpacing:1}});return r.document([r.stack("terminal_header",[i("wordmark","GROW / \u79EF\u5206\u5DE5\u4F5C\u53F0","GROW / CREDIT WORKSPACE"),r.stack("terminal_intro",[r.text("heading","\u79EF\u5206\u4E0E\u7528\u91CF","Credits & usage",36,e,{width:780,grow:2,text:{size:36,color:e,weight:600,letterSpacing:-1.2,lineHeight:1.15}}),r.text("description","\u4F59\u989D\u3001\u5230\u671F\u6765\u6E90\u4E0E\u6BCF\u4E00\u7B14\u4F7F\u7528\u3002","Balance, expiry and every transaction.",13,t,{width:340,grow:1})],{gap:32},!0)],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),r.stack("terminal_workspace",[r.stack("ledger_workspace",[r.stack("credit_summary",[i("balance_index","01 / \u8D26\u6237\u4F59\u989D","01 / BALANCE"),r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,{text:{size:80,color:e,font:"mono",weight:500}})],{gap:16,padding:Pt(28),background:gt("#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:Pt(28),background:gt("#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:Pt(24),background:gt("#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:Pt(24),background:gt("#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:Pt(24),background:gt("#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 Sf(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new qt("\u4F1A\u5458\u4FF1\u4E50\u90E8",{theme:{background:t,text:e,primary:e,radius:"none"},width:1160,gap:32,padding:{top:28,right:24,bottom:48,left:24}}),a=(o,s,c,l=n)=>i.text(o,s,c,12,l,{text:{size:12,color:l,font:"mono",letterSpacing:1,weight:500}});return i.document([i.stack("club_masthead",[i.stack("club_identity",[i.text("wordmark","GROW CLUB","GROW CLUB",22,e,{text:{size:22,color:e,weight:700,letterSpacing:-.6}}),a("club_edition","\u4F1A\u5458 / MEMBERSHIP","MEMBERSHIP / YOUR SPACE")],{gap:20},!0),i.rule("club_rule",e),i.stack("club_intro",[i.text("heading","\u4F1A\u5458\u4E0E\u65B9\u6848","Room to grow.",64,e,{width:752,grow:2,text:{size:64,color:e,font:"serif",weight:400,lineHeight:1.1,letterSpacing:-2}}),i.stack("club_description",[a("club_intro_label","\u4E3A\u6301\u7EED\u7684\u521B\u9020\u529B","FOR WHAT COMES NEXT"),i.text("description",`\u67E5\u770B\u4F60\u7684\u4F1A\u5458\u72B6\u6001\uFF0C
|
|
20
|
+
\u627E\u5230\u9002\u5408\u4E0B\u4E00\u6B65\u7684\u65B9\u6848\u3002`,`Your membership, at a glance.
|
|
21
|
+
A plan for what comes next.`,14,n)],{width:320,grow:1,gap:12,padding:{top:10,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("membership_summary",[i.stack("member_spread",[a("member_index","01 / \u4F60\u7684\u4F1A\u5458","01 / YOUR MEMBERSHIP","#CCD9CA"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:"#FFFFFF",font:"serif",size:52,weight:400}})],{width:744,grow:2,gap:20,padding:Pt(32),background:gt(e)}),i.stack("balance_inset",[a("balance_index","02 / \u521B\u4F5C\u4F59\u989D","02 / CREDIT BALANCE",e),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:e,size:60,weight:500}})],{width:376,grow:1,gap:20,padding:Pt(28),background:gt(r)})],{gap:0},!0),i.stack("plan_comparison",[a("plans_index","03 / \u9009\u62E9\u4F60\u7684\u4E0B\u4E00\u6B65","03 / YOUR NEXT STEP"),i.widget("plans","customer_plans","\u627E\u5230\u9002\u5408\u4F60\u7684\u65B9\u6848","A plan to make it yours",!1,{text:{color:e,font:"serif"}})],{gap:16,padding:{top:8,right:0,bottom:8,left:0}}),i.rule("benefits_rule","#C8CEC2"),i.stack("benefit_records",[i.stack("member_offers",[a("offers_index","04 / \u4F60\u7684\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u4F1A\u5458\u4F18\u60E0","Member offers",!1,{text:{color:e}})],{width:556,grow:1,gap:16}),i.stack("member_purchases",[a("orders_index","05 / \u8D2D\u4E70\u8BB0\u5F55","05 / PURCHASES"),i.widget("orders","credit_pack_orders","\u8D2D\u4E70\u4E0E\u8BB0\u5F55","Purchases & records",!1,{text:{color:e}})],{width:556,grow:1,gap:16})],{gap:48},!0),i.rule("footer_rule","#C8CEC2"),a("club_footer","GROW CLUB / \u7559\u51FA\u521B\u9020\u7684\u7A7A\u95F4","GROW CLUB / ROOM FOR WHAT'S NEXT")])}function xf(){let e=ox("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([sx(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,{...co(784,2),...ix(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{...co(328),background:gt(bf),padding:Pt(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",hf),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,co(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",hf),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{...co(328),...ax,padding:Pt(24),gap:24,background:gt(bf)})],{gap:48},!0)])}function vf(){return xf()}var gn=(e,t=1)=>({width:e,grow:t}),lo=(e=16)=>({shape:{type:"rect",radius:e}}),ot=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),wn=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function cx(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 ux(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,a="system"){let o=e.stack("masthead",[cx(e,t,n,r,a),ux(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return o.justify="between",o.align="center",o}function If(e,t,n=!1,r=5){let i=e.widget("activity","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",n,ot(t));return i.data.pageSize=r,i}function lx(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new qt("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:wn(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,ot(t,96)),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,ot(t))],{...gn(680,2),gap:32,padding:wn(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,ot(e))],{...gn(328),background:gt(r),padding:Pt(24),...lo(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),If(i,t,!1,4)])}function dx(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new qt("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:wn(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,ot(e,96,"serif"))],{...gn(628,2),padding:wn(12,0),gap:24}),r.stack("membership_column",[r.widget("membership","membership","\u4F1A\u5458\u72B6\u6001","Membership",!1,ot(e)),r.widget("offers","offer_history","\u8D26\u6237\u4F18\u60E0","Your offers",!0,ot(e))],{...gn(356),gap:20,padding:wn(12,0)})],{gap:96},!0),r.rule("orders_rule",n),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Purchases",!1,ot(e))])}function mx(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new qt("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:wn(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,ot("#F4F7F0"))],{...gn(640,2),gap:24,background:gt(n),padding:Pt(32),...lo(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,ot(e,64))],{...gn(400),background:gt("#E9EFE5"),padding:Pt(28),...lo(20)})],{gap:24},!0),i.widget("plans","customer_plans","\u65B9\u6848\u4E0E\u4EF7\u683C","Plans & pricing",!1,ot(e)),i.rule("offer_rule","#D5DFD3"),i.widget("offers","offer_history","\u6211\u7684\u4F18\u60E0","Your offers",!0,ot(e))])}function px(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new qt("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:wn(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,{...gn(688,2),...ot(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...gn(372),...ot(e)})],{gap:72,padding:wn(4,0,8)},!0),r.rule("activity_rule",n),If(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,ot(e))])}function fx(){let e="#3F3029",t="#8B766A",n="#A34525",r=new qt("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:wn(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,ot(e,56)),r.rule("context_rule","#DBC5B5"),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,ot(e))],{...gn(304),gap:28,padding:Pt(24),background:gt("#F1E5D9"),...lo(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,ot(e))],{...gn(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,ot(e))])}function Af(){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:lx},{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:dx},{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:mx},{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:vf},{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:px},{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:fx}].map(({create:e,...t})=>({...t,document:e()}))}function gx(){return yf()}function hx(){return _f()}function bx(){return Sf()}function cF(){return[...Af(),{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:gx()},{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:hx()},{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:bx()}]}import{z as jt}from"zod";var wf=jt.object({id:jt.string().min(1).max(136),name:jt.string().min(1).max(128),type:jt.enum(["entry","condition","feature"])}).strict(),_x=jt.object({id:jt.uuid(),name:jt.string().min(1).max(80),status:jt.enum(["draft","published","archived"]),draftNodes:jt.array(wf).max(600),publishedNodes:jt.array(wf).max(600),runningVersions:jt.number().int().nonnegative()}).strict().refine(e=>e.draftNodes.length>0||e.publishedNodes.length>0||e.runningVersions>0,"A Funnel usage must have a current reference or an unfinished run"),dF=jt.object({rows:jt.array(_x).max(50),nextCursor:jt.uuid().nullable()}).strict();import{z as xe}from"zod";var It=xe.number().int().nonnegative(),Cf=xe.strictObject({at:xe.iso.datetime({offset:!0}),id:xe.uuid()}),hF=xe.strictObject({versionId:xe.uuid().nullable(),from:xe.iso.datetime({offset:!0}).nullable(),to:xe.iso.datetime({offset:!0}).nullable(),after:Cf.nullable()}).refine(e=>!e.from||!e.to||Date.parse(e.from)<Date.parse(e.to),"Time range must increase"),bF=xe.strictObject({funnelId:xe.uuid(),snapshotAt:xe.iso.datetime({offset:!0}),versions:xe.array(xe.strictObject({id:xe.uuid(),version:xe.number().int().positive(),createdAt:xe.iso.datetime({offset:!0})})).max(100),versionsLimited:xe.boolean(),overall:xe.strictObject({started:It,completed:It,closed:It,failed:It,waiting:It,paid:It}),decisions:xe.strictObject({queries:It,completed:It,reportedUsed:It,pending:It,failed:It}),revenue:xe.array(xe.strictObject({currency:z,grossMinor:xe.string().regex(/^\d+$/),refundMinor:xe.string().regex(/^\d+$/),netMinor:xe.string().regex(/^-?\d+$/)})).max(100),nodes:xe.array(xe.strictObject({versionId:xe.uuid(),nodeId:xe.string(),visits:It,completed:It,shown:It,waiting:It})).max(1e4),recentRuns:xe.array(xe.strictObject({id:xe.uuid(),versionId:xe.uuid(),customerId:xe.uuid(),status:Rc,nodeId:xe.string(),visit:It,createdAt:xe.iso.datetime({offset:!0}),updatedAt:xe.iso.datetime({offset:!0})})).max(100),nextCursor:Cf.nullable()});import{z as Ln}from"zod";var vF=Ln.object({requestId:Ln.uuid(),coupon:od,audienceId:Ln.uuid().nullable(),productVersionId:Ln.uuid().optional(),presentation:An,locale:Ln.enum(["en","zh-CN"])}).strict(),IF=Ln.object({couponId:Ln.uuid(),funnelId:Ln.uuid()}).strict();import{z as Ae}from"zod";var ht=Ae.number().int().nonnegative(),mo=Ae.string().regex(/^-?\d+$/),yx=Ae.object({currency:z,grossMinor:mo,refundMinor:mo,netMinor:mo,purchases:ht,refunds:ht}).strict(),PF=Ae.object({snapshotAt:Ae.iso.datetime({offset:!0}),customers:Ae.object({total:ht,created:ht,paid:ht}).strict(),memberships:Ae.object({active:ht,trial:ht,pastDue:ht,ended:ht}).strict(),runs:Ae.object({started:ht,completed:ht,closed:ht,paid:ht}).strict(),revenue:Ae.array(yx).max(100),unknownMoney:ht,funnels:Ae.array(Ae.object({id:Ae.uuid(),name:Ae.string(),started:ht,completed:ht,paid:ht}).strict()).max(50),daily:Ae.array(Ae.object({date:Ae.iso.date(),currency:z,netMinor:mo}).strict()).max(9e3)}).strict(),OF=Ae.object({customerId:Ae.uuid(),rows:Ae.array(Ae.object({id:Ae.string().regex(/^\d+$/),funnelId:Ae.uuid(),funnelName:Ae.string(),versionId:Ae.uuid(),runId:Ae.uuid(),nodeId:Ae.string(),experimentId:Ae.uuid(),visit:Ae.number().int().nonnegative(),variationKey:Ae.string(),inExperiment:Ae.boolean(),hashUsed:Ae.boolean(),acceptedAt:Ae.iso.datetime({offset:!0}),runStatus:Ae.string()}).strict()).max(50),nextCursor:Ae.string().regex(/^\d+$/).nullable()}).strict();import{z as zt}from"zod";import{z as bt}from"zod";var Pf=bt.discriminatedUnion("provider",[bt.strictObject({provider:bt.literal("apple"),orderId:bt.uuid(),receiptId:bt.uuid(),signedTransaction:bt.string().min(1).max(131072)}),bt.strictObject({provider:bt.literal("google"),orderId:bt.uuid(),receiptId:bt.uuid(),purchaseToken:bt.string().min(1).max(16384)})]),Of=bt.strictObject({orderId:bt.uuid(),receiptId:bt.uuid(),transactionIds:bt.array(bt.string().min(1).max(255)).min(1).max(50),membership:bt.boolean()});var DF=zt.strictObject({operation:zt.literal("native_receipt"),requestId:zt.uuid(),customerToken:zt.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:zt.uuid(),receiptId:zt.uuid(),nativeEvidence:Pf.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),FF=zt.strictObject({scope:Ue,requestId:zt.uuid(),orderId:zt.uuid(),receiptId:zt.uuid(),orderStatus:zt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:zt.boolean(),nativeCompletion:Of.optional()});import{z as Sx}from"zod";var xx=$p.extend({document:Sx.union([kt.refine(e=>e.pages.length===1,"Use a single owned screen template"),Lt.refine(e=>e.screens.every(t=>t.type==="owned"),"Flow templates own their screens")])}).superRefine((e,t)=>{if((e.document.kind==="funnel"?e.surface!=="onboarding":e.surface!==e.document.surface)&&t.addIssue({code:"custom",message:"Template category does not match its document"}),e.document.kind==="funnel"){let n=e.document,r=n.graph.nodes.filter(i=>i.type==="screen");(new Set(n.screens.map(i=>i.id)).size!==n.screens.length||new Set(n.graph.nodes.map(i=>i.id)).size!==n.graph.nodes.length||r.length!==n.screens.length||n.screens.some(i=>r.filter(a=>a.screenId===i.id).length!==1))&&t.addIssue({code:"custom",message:"Every template screen requires one unique flow node"})}});function KF(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 vx(e,t){let n=structuredClone(xx.parse(e).document);if(n.kind==="funnel"){let l=function(u){if(Array.isArray(u)){u.forEach(l);return}if(!u||typeof u!="object")return;let d=u;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(l)};var s=l;let c="00000000-0000-0000-0000-000000000000";for(let u of Object.values(n.references))"id"in u&&(u.id=c);for(let u of n.graph.nodes)u.type==="condition"&&u.cases.forEach(d=>l(d.condition));for(let u of n.screens)u.type==="owned"&&Ef(u.document);return Lt.parse({...n,screens:n.screens.map(u=>u.type==="owned"?{...u,document:{...u.document,strings:{...u.document.strings,defaultLocale:sc(u.document,[t])}}}:u),graph:{...n.graph,nodes:n.graph.nodes.map(u=>u.type==="split"?{...u,experimentId:"00000000-0000-0000-0000-000000000000"}:u.type==="offering"?{...u,configuration:u.configuration.source==="fixed"?{source:"fixed",versionId:c}:u.configuration}:u.type==="coupon"?{...u,couponId:c}:u)}})}let r={...n,strings:{...n.strings,defaultLocale:sc(n,[t])}},i=[{id:"entry",type:"entry",name:t==="en"?"Entry":"\u5165\u53E3",next:"screen"},{id:"done",name:t==="en"?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed",output:{type:"literal",value:null}},{id:"closed",name:t==="en"?"Closed":"\u5173\u95ED",type:"end",outcome:"closed"}],a={};r.actions=r.actions.map((c,l)=>{let u=`action_${l}`;return a[c.id]=c.close?"closed":"done",c.type==="open_url"?(a[c.id]=u,i.push({id:u,name:c.id,type:"output",value:{type:"literal",value:{intent:"open_url",url:c.url}}})):c.type==="claim_offer"&&(a[c.id]="unconnected"),{id:c.id,type:"event",event:c.id,properties:{},close:!1}}),Ef(r),i.push({id:"screen",name:e.label,type:"screen",screenId:"screen",presentation:e.surface==="page"?{type:"inline"}:n.presentation,outputs:a});let o=new Set(i.flatMap(Lr));return Lt.parse({references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",schemaVersion:3,inputs:(()=>{let c=[];return Ct(r,l=>{l.type==="stack"&&l.interaction&&["input","select","multiselect","toggle","tabs"].includes(l.interaction.type)&&c.push({key:`answer_${crypto.randomUUID().replaceAll("-","")}`,screenId:"screen",componentId:l.id,required:!1})}),c})(),screens:[{id:"screen",type:"owned",document:r}],graph:{version:4,entry:"entry",nodes:i.filter(c=>c.type!=="end"||o.has(c.id))}})}function HF(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=vx(t,n),i=`tpl_${crypto.randomUUID().replaceAll("-","").slice(0,16)}_`,a=new Map,o=d=>d==="unconnected"?d:(a.has(d)||a.set(d,`${i}${crypto.randomUUID().replaceAll("-","").slice(0,24)}`),a.get(d)),s=r.graph.nodes.slice().sort((d,m)=>+(m.type==="screen")-+(d.type==="screen")).filter(d=>d.type!=="entry").map(d=>d.type==="screen"?{...d,id:o(d.id),screenId:o(d.screenId),outputs:Object.fromEntries(Object.entries(d.outputs).map(([m,g])=>[m,o(g)]))}:d.type==="action"?{...d,id:o(d.id),success:o(d.success),cancel:o(d.cancel),unavailable:o(d.unavailable),failure:o(d.failure)}:{...d,id:o(d.id)}),c=Lt.parse({...e,screens:[...e.screens,...r.screens.map(d=>({...d,id:o(d.id)}))],inputs:[...e.inputs,...r.inputs.map(d=>({...d,screenId:o(d.screenId)}))],graph:{...e.graph,nodes:[...e.graph.nodes,...s]}}),l=0,u=0;for(let d of c.screens)d.type==="owned"&&(Ct(d.document,()=>{l++}),u+=d.document.actions.length);if(l>et.components||u>et.actions||sn(c)>et.documentBytes)throw new Error("Template exceeds the flow capacity");return c}function Ef(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 Ix(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function zF(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function kf(e){return Ix(e)?e.intervalCount??1:1}function QF(e,t){return e.interval===t.interval&&kf(e)===kf(t)}function ZF(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"]},a={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},o=e==="week"?`/${a[r]??a.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?o:`/${n} ${o.slice(1)}${r==="en"?"s":""}`}import{z as $e}from"zod";var Tf=$e.enum(["membership","trial","topup","manual","rollover","seat"]),Rf=$e.enum(["scheduled","active","expired","revoked","unavailable"]),tU=$e.strictObject({customerId:$e.uuid().nullable(),entityId:$e.uuid().nullable(),internal_feature_id:$e.uuid().nullable(),reason:Tf.nullable(),status:Rf.nullable(),after:$e.uuid().nullable(),limit:$e.number().int().min(1).max(50)}),nU=$e.strictObject({snapshotAt:$e.iso.datetime({offset:!0}),rows:$e.array($e.strictObject({id:$e.uuid(),customerId:$e.uuid(),fundingCustomerId:$e.uuid(),entityId:$e.uuid().nullable(),internal_feature_id:$e.uuid(),key:Yt,name:$e.string().min(1).max(120),kind:$e.enum(["access","metered","credit"]),reason:Tf,status:Rf,unlimited:$e.boolean(),granted:Qe,available:Qe,held:Qe,spent:Qe,revoked:Qe,transferred:Qe,startsAt:$e.iso.datetime({offset:!0}).nullable(),expiresAt:$e.iso.datetime({offset:!0}).nullable(),grantId:$e.uuid().nullable(),membershipId:$e.uuid().nullable(),seatPoolId:$e.uuid().nullable()})).max(50),nextCursor:$e.uuid().nullable()});import{z as q}from"zod";var Nf=q.strictObject({property:q.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/),datatype:q.enum(["boolean","string","number","enum","string[]","number[]","object","array","json"]),enumValues:q.array(q.string()).min(1).nullable(),format:q.enum(["","version","date","isoCountryCode"]),hashAttribute:q.boolean(),stored:q.boolean(),description:q.string().max(2e3),status:q.enum(["active","archived"])}).superRefine((e,t)=>{["parameters","answers","results","__proto__","constructor","prototype"].includes(e.property)&&t.addIssue({code:"custom",message:"Reserved attribute property"}),(e.datatype==="enum"!=(e.enumValues!==null)||e.hashAttribute&&!["string","number","enum"].includes(e.datatype))&&t.addIssue({code:"custom",message:"Hash attributes must be scalar strings or numbers; enums require values"})}),Df=q.strictObject({name:q.string().min(1).max(128),label:q.string().min(1).max(80),description:q.string().max(2e3),status:q.enum(["active","inactive"]),hashAttribute:q.string().min(1).max(128),seed:q.string().min(1).max(128)}),qc={id:q.uuid(),revision:q.number().int().positive()},sU=q.strictObject({groups:q.array(q.strictObject({id:q.uuid(),name:q.string(),type:q.enum(["condition","list"])})),experiments:q.array(q.strictObject({...qc,configuration:vr,archivedAt:q.iso.datetime({offset:!0}).nullable()})),namespaces:q.array(q.strictObject({...qc,configuration:Df})),attributes:q.array(q.strictObject({...qc,configuration:Nf})),truncated:q.boolean()}),Vc={id:q.uuid().nullable(),revision:q.number().int().min(0)},cU=q.discriminatedUnion("resource",[q.strictObject({...Vc,resource:q.literal("experiment"),configuration:vr.safeExtend({archivedAt:q.iso.datetime({offset:!0}).nullable()})}),q.strictObject({...Vc,resource:q.literal("namespace"),configuration:Df}),q.strictObject({...Vc,resource:q.literal("attribute"),configuration:Nf})]),uU=q.strictObject({operation:q.literal("evaluate"),attributes:Jt,condition:yt.optional(),features:Xl,featureKey:q.string().min(1).max(128),customerId:q.uuid().nullable()}),lU=q.strictObject({experimentId:q.uuid(),participants:q.number().int().nonnegative(),cohorts:q.array(q.strictObject({variationKey:q.string().nullable(),participants:q.number().int().nonnegative()})),phases:q.array(q.strictObject({phaseIndex:q.number().int().nonnegative(),participants:q.number().int().nonnegative()})),stickyIdentities:q.number().int().nonnegative(),snapshotAt:q.iso.datetime()}),jf=q.strictObject({resource:q.enum(["group","experiment","coupon"]),id:q.uuid()}),dU=q.strictObject({rows:q.array(jf.extend({name:q.string(),status:q.string()})).max(50),total:q.number().int().nonnegative(),nextCursor:jf.nullable()});var po=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Ax(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!po(n.condition,r.condition)||!po(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,l])=>{let u=c;for(let[d,m]of[...r.namespace.ranges].sort((g,f)=>g[0]-f[0]))d<=u&&m>u&&(u=m);return u<l})&&i.push("namespaceRange"),(!po(n.variationWeights,r.variationWeights)||!po(e.variations.map(c=>c.key),t.variations.map(c=>c.key)))&&i.push("weights"),(e.disableStickyBucketing!==t.disableStickyBucketing||n.seed!==r.seed)&&i.push("identity");let a=i.some(c=>["namespace","namespaceRange","weights","identity"].includes(c)),o=!t.disableStickyBucketing,s=a||i.length>0&&!o?"new-phase":o?"same-phase-sticky":"same-phase-everyone";return{reasons:i,disableSamePhase:a,recommended:s,risk:i.length?a?"danger":"warning":"safe"}}function fU(e,t,n,r,i){let a=structuredClone(t),o=a.phases.at(-1),s=!a.disableStickyBucketing;if(n==="same-phase-sticky"&&!s||n==="new-phase-block-sticky"&&!s)throw Error("Sticky bucketing is required");if(Ax(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");return a.bucketVersion=e.bucketVersion+(s&&n!=="same-phase-sticky"?1:0),a.minBucketVersion=n==="new-phase-block-sticky"?a.bucketVersion:e.minBucketVersion,n.startsWith("new-phase")&&(a.phases=structuredClone(e.phases),a.phases[a.phases.length-1].dateEnded=r,a.phases.push({...o,name:o.name,reason:o.reason,dateStarted:r,dateEnded:null,seed:i})),vr.parse(a)}import{z as wx}from"zod";var bU=wx.enum(["owner","admin","developer","sales","member"]),Cx=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],Ff=Cx.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 _U(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 SU=["boolean","metered","credit_system","ai_credit_system"];function xU(e,t,n,r=!1){let i=[],a=(o,s)=>i.push({field:o,code:s});return e.type!==t.type&&(e.type==="credit_system"!=(t.type==="credit_system")&&a("type","type_switch_credit_system"),n.customerHistory&&a("type","attached_to_customer"),n.entityFeature&&a("type","used_as_entity_feature"),n.usagePrice&&a("type","has_usage_price"),n.creditSystems&&a("type","used_in_credit_system"),n.productEntitlements&&(e.type==="credit_system"||t.type==="credit_system")&&a("type","used_in_product_credit_system")),e.id!==t.id&&(r&&a("id","id_already_exists"),n.customerHistory&&a("id","attached_to_customer")),e.type!=="boolean"&&t.type!=="boolean"&&e.config?.usage_type!==t.config?.usage_type&&t.config?.usage_type&&(n.creditSystems&&a("usage_type","used_in_credit_system"),n.entityFeature&&a("usage_type","used_as_entity_feature"),n.customerHistory&&a("usage_type","attached_to_customer")),i}/*!
|
|
22
|
+
* decimal.js v10.6.0
|
|
23
|
+
* An arbitrary-precision Decimal type for JavaScript.
|
|
24
|
+
* https://github.com/MikeMcl/decimal.js
|
|
25
|
+
* Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
|
|
26
|
+
* MIT Licence
|
|
27
|
+
*/var Gr=9e15,Gn=1e9,$c="0123456789abcdef",ho="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",bo="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Gc={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Gr,maxE:Gr,crypto:!1},qf,Cn,ue=!0,yo="[DecimalError] ",$n=yo+"Invalid argument: ",Vf=yo+"Precision limit exceeded",$f=yo+"crypto unavailable",Gf="[object Decimal]",At=Math.floor,st=Math.pow,Px=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Ox=/^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,cn=1e7,ne=7,kx=9007199254740991,Tx=ho.length-1,Kc=bo.length-1,k={toStringTag:Gf};k.absoluteValue=k.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),X(e)};k.ceil=function(){return X(new this.constructor(this),this.e+1,2)};k.clampedTo=k.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($n+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};k.comparedTo=k.cmp=function(e){var t,n,r,i,a=this,o=a.d,s=(e=new a.constructor(e)).d,c=a.s,l=e.s;if(!o||!s)return!c||!l?NaN:c!==l?c:o===s?0:!o^c<0?1:-1;if(!o[0]||!s[0])return o[0]?c:s[0]?-l:0;if(c!==l)return c;if(a.e!==e.e)return a.e>e.e^c<0?1:-1;for(r=o.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==s[t])return o[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1};k.cosine=k.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())+ne,r.rounding=1,n=Rx(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)};k.cubeRoot=k.cbrt=function(){var e,t,n,r,i,a,o,s,c,l,u=this,d=u.constructor;if(!u.isFinite()||u.isZero())return new d(u);for(ue=!1,a=u.s*st(u.s*u,1/3),!a||Math.abs(a)==1/0?(n=_t(u.d),e=u.e,(a=(e-n.length+1)%3)&&(n+=a==1||a==-2?"0":"00"),a=st(n,1/3),e=At((e+1)/3)-(e%3==(e<0?-1:2)),a==1/0?n="5e"+e:(n=a.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new d(n),r.s=u.s):r=new d(a.toString()),o=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),l=c.plus(u),r=Le(l.plus(u).times(s),l.plus(c),o+2,1),_t(s.d).slice(0,o)===(n=_t(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(X(s,e+1,0),s.times(s).times(s).eq(u))){r=s;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(X(r,e+1,1),t=!r.times(r).times(r).eq(u));break}return ue=!0,X(r,e,d.rounding,t)};k.decimalPlaces=k.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-At(this.e/ne))*ne,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};k.dividedBy=k.div=function(e){return Le(this,new this.constructor(e))};k.dividedToIntegerBy=k.divToInt=function(e){var t=this,n=t.constructor;return X(Le(t,new n(e),0,1,1),n.precision,n.rounding)};k.equals=k.eq=function(e){return this.cmp(e)===0};k.floor=function(){return X(new this.constructor(this),this.e+1,3)};k.greaterThan=k.gt=function(e){return this.cmp(e)>0};k.greaterThanOrEqualTo=k.gte=function(e){var t=this.cmp(e);return t==1||t===0};k.hyperbolicCosine=k.cosh=function(){var e,t,n,r,i,a=this,o=a.constructor,s=new o(1);if(!a.isFinite())return new o(a.s?1/0:NaN);if(a.isZero())return s;n=o.precision,r=o.rounding,o.precision=n+Math.max(a.e,a.sd())+4,o.rounding=1,i=a.d.length,i<32?(e=Math.ceil(i/3),t=(1/xo(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),a=Kr(o,1,a.times(t),new o(1),!0);for(var c,l=e,u=new o(8);l--;)c=a.times(a),a=s.minus(c.times(u.minus(c.times(u))));return X(a,o.precision=n,o.rounding=r,!0)};k.hyperbolicSine=k.sinh=function(){var e,t,n,r,i=this,a=i.constructor;if(!i.isFinite()||i.isZero())return new a(i);if(t=a.precision,n=a.rounding,a.precision=t+Math.max(i.e,i.sd())+4,a.rounding=1,r=i.d.length,r<3)i=Kr(a,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/xo(5,e)),i=Kr(a,2,i,i,!0);for(var o,s=new a(5),c=new a(16),l=new a(20);e--;)o=i.times(i),i=i.times(s.plus(o.times(c.times(o).plus(l))))}return a.precision=t,a.rounding=n,X(i,t,n,!0)};k.hyperbolicTangent=k.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Le(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};k.inverseCosine=k.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()?hn(t,r,i):new t(0):new t(NaN):e.isZero()?hn(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))};k.inverseHyperbolicCosine=k.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,ue=!1,n=n.times(n).minus(1).sqrt().plus(n),ue=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};k.inverseHyperbolicSine=k.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,ue=!1,n=n.times(n).plus(1).sqrt().plus(n),ue=!0,r.precision=e,r.rounding=t,n.ln())};k.inverseHyperbolicTangent=k.atanh=function(){var e,t,n,r,i=this,a=i.constructor;return i.isFinite()?i.e>=0?new a(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=a.precision,t=a.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?X(new a(i),e,t,!0):(a.precision=n=r-i.e,i=Le(i.plus(1),new a(1).minus(i),n+e,1),a.precision=e+4,a.rounding=1,i=i.ln(),a.precision=e,a.rounding=t,i.times(.5))):new a(NaN)};k.inverseSine=k.asin=function(){var e,t,n,r,i=this,a=i.constructor;return i.isZero()?new a(i):(t=i.abs().cmp(1),n=a.precision,r=a.rounding,t!==-1?t===0?(e=hn(a,n+4,r).times(.5),e.s=i.s,e):new a(NaN):(a.precision=n+6,a.rounding=1,i=i.div(new a(1).minus(i.times(i)).sqrt().plus(1)).atan(),a.precision=n,a.rounding=r,i.times(2)))};k.inverseTangent=k.atan=function(){var e,t,n,r,i,a,o,s,c,l=this,u=l.constructor,d=u.precision,m=u.rounding;if(l.isFinite()){if(l.isZero())return new u(l);if(l.abs().eq(1)&&d+4<=Kc)return o=hn(u,d+4,m).times(.25),o.s=l.s,o}else{if(!l.s)return new u(NaN);if(d+4<=Kc)return o=hn(u,d+4,m).times(.5),o.s=l.s,o}for(u.precision=s=d+10,u.rounding=1,n=Math.min(28,s/ne+2|0),e=n;e;--e)l=l.div(l.times(l).plus(1).sqrt().plus(1));for(ue=!1,t=Math.ceil(s/ne),r=1,c=l.times(l),o=new u(l),i=l;e!==-1;)if(i=i.times(c),a=o.minus(i.div(r+=2)),i=i.times(c),o=a.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===a.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),ue=!0,X(o,u.precision=d,u.rounding=m,!0)};k.isFinite=function(){return!!this.d};k.isInteger=k.isInt=function(){return!!this.d&&At(this.e/ne)>this.d.length-2};k.isNaN=function(){return!this.s};k.isNegative=k.isNeg=function(){return this.s<0};k.isPositive=k.isPos=function(){return this.s>0};k.isZero=function(){return!!this.d&&this.d[0]===0};k.lessThan=k.lt=function(e){return this.cmp(e)<0};k.lessThanOrEqualTo=k.lte=function(e){return this.cmp(e)<1};k.logarithm=k.log=function(e){var t,n,r,i,a,o,s,c,l=this,u=l.constructor,d=u.precision,m=u.rounding,g=5;if(e==null)e=new u(10),t=!0;else{if(e=new u(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new u(NaN);t=e.eq(10)}if(n=l.d,l.s<0||!n||!n[0]||l.eq(1))return new u(n&&!n[0]?-1/0:l.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)a=!0;else{for(i=n[0];i%10===0;)i/=10;a=i!==1}if(ue=!1,s=d+g,o=Vn(l,s),r=t?_o(u,s+10):Vn(e,s),c=Le(o,r,s,1),zi(c.d,i=d,m))do if(s+=10,o=Vn(l,s),r=t?_o(u,s+10):Vn(e,s),c=Le(o,r,s,1),!a){+_t(c.d).slice(i+1,i+15)+1==1e14&&(c=X(c,d+1,0));break}while(zi(c.d,i+=10,m));return ue=!0,X(c,d,m)};k.minus=k.sub=function(e){var t,n,r,i,a,o,s,c,l,u,d,m,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(l=g.d,m=e.d,s=f.precision,c=f.rounding,!l[0]||!m[0]){if(m[0])e.s=-e.s;else if(l[0])e=new f(g);else return new f(c===3?-0:0);return ue?X(e,s,c):e}if(n=At(e.e/ne),u=At(g.e/ne),l=l.slice(),a=u-n,a){for(d=a<0,d?(t=l,a=-a,o=m.length):(t=m,n=u,o=l.length),r=Math.max(Math.ceil(s/ne),o)+2,a>r&&(a=r,t.length=1),t.reverse(),r=a;r--;)t.push(0);t.reverse()}else{for(r=l.length,o=m.length,d=r<o,d&&(o=r),r=0;r<o;r++)if(l[r]!=m[r]){d=l[r]<m[r];break}a=0}for(d&&(t=l,l=m,m=t,e.s=-e.s),o=l.length,r=m.length-o;r>0;--r)l[o++]=0;for(r=m.length;r>a;){if(l[--r]<m[r]){for(i=r;i&&l[--i]===0;)l[i]=cn-1;--l[i],l[r]+=cn}l[r]-=m[r]}for(;l[--o]===0;)l.pop();for(;l[0]===0;l.shift())--n;return l[0]?(e.d=l,e.e=So(l,n),ue?X(e,s,c):e):new f(c===3?-0:0)};k.modulo=k.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):(ue=!1,r.modulo==9?(t=Le(n,e.abs(),0,3,1),t.s*=e.s):t=Le(n,e,0,r.modulo,1),t=t.times(e),ue=!0,n.minus(t))};k.naturalExponential=k.exp=function(){return Hc(this)};k.naturalLogarithm=k.ln=function(){return Vn(this)};k.negated=k.neg=function(){var e=new this.constructor(this);return e.s=-e.s,X(e)};k.plus=k.add=function(e){var t,n,r,i,a,o,s,c,l,u,d=this,m=d.constructor;if(e=new m(e),!d.d||!e.d)return!d.s||!e.s?e=new m(NaN):d.d||(e=new m(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(l=d.d,u=e.d,s=m.precision,c=m.rounding,!l[0]||!u[0])return u[0]||(e=new m(d)),ue?X(e,s,c):e;if(a=At(d.e/ne),r=At(e.e/ne),l=l.slice(),i=a-r,i){for(i<0?(n=l,i=-i,o=u.length):(n=u,r=a,o=l.length),a=Math.ceil(s/ne),o=a>o?a+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=l.length,i=u.length,o-i<0&&(i=o,n=u,u=l,l=n),t=0;i;)t=(l[--i]=l[i]+u[i]+t)/cn|0,l[i]%=cn;for(t&&(l.unshift(t),++r),o=l.length;l[--o]==0;)l.pop();return e.d=l,e.e=So(l,r),ue?X(e,s,c):e};k.precision=k.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error($n+e);return n.d?(t=Hf(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};k.round=function(){var e=this,t=e.constructor;return X(new t(e),e.e+1,t.rounding)};k.sine=k.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())+ne,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)};k.squareRoot=k.sqrt=function(){var e,t,n,r,i,a,o=this,s=o.d,c=o.e,l=o.s,u=o.constructor;if(l!==1||!s||!s[0])return new u(!l||l<0&&(!s||s[0])?NaN:s?o:1/0);for(ue=!1,l=Math.sqrt(+o),l==0||l==1/0?(t=_t(s),(t.length+c)%2==0&&(t+="0"),l=Math.sqrt(t),c=At((c+1)/2)-(c<0||c%2),l==1/0?t="5e"+c:(t=l.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new u(t)):r=new u(l.toString()),n=(c=u.precision)+3;;)if(a=r,r=a.plus(Le(o,a,n+2,1)).times(.5),_t(a.d).slice(0,n)===(t=_t(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(X(a,c+1,0),a.times(a).eq(o))){r=a;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(X(r,c+1,1),e=!r.times(r).eq(o));break}return ue=!0,X(r,c,u.rounding,e)};k.tangent=k.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Le(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,X(Cn==2||Cn==4?n.neg():n,e,t,!0)):new r(NaN)};k.times=k.mul=function(e){var t,n,r,i,a,o,s,c,l,u=this,d=u.constructor,m=u.d,g=(e=new d(e)).d;if(e.s*=u.s,!m||!m[0]||!g||!g[0])return new d(!e.s||m&&!m[0]&&!g||g&&!g[0]&&!m?NaN:!m||!g?e.s/0:e.s*0);for(n=At(u.e/ne)+At(e.e/ne),c=m.length,l=g.length,c<l&&(a=m,m=g,g=a,o=c,c=l,l=o),a=[],o=c+l,r=o;r--;)a.push(0);for(r=l;--r>=0;){for(t=0,i=c+r;i>r;)s=a[i]+g[r]*m[i-r-1]+t,a[i--]=s%cn|0,t=s/cn|0;a[i]=(a[i]+t)%cn|0}for(;!a[--o];)a.pop();return t?++n:a.shift(),e.d=a,e.e=So(a,n),ue?X(e,d.precision,d.rounding):e};k.toBinary=function(e,t){return Wc(this,2,e,t)};k.toDecimalPlaces=k.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Nt(e,0,Gn),t===void 0?t=r.rounding:Nt(t,0,8),X(n,e+n.e+1,t))};k.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=bn(r,!0):(Nt(e,0,Gn),t===void 0?t=i.rounding:Nt(t,0,8),r=X(new i(r),e+1,t),n=bn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};k.toFixed=function(e,t){var n,r,i=this,a=i.constructor;return e===void 0?n=bn(i):(Nt(e,0,Gn),t===void 0?t=a.rounding:Nt(t,0,8),r=X(new a(i),e+i.e+1,t),n=bn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};k.toFraction=function(e){var t,n,r,i,a,o,s,c,l,u,d,m,g=this,f=g.d,h=g.constructor;if(!f)return new h(g);if(l=n=new h(1),r=c=new h(0),t=new h(r),a=t.e=Hf(f)-g.e-1,o=a%ne,t.d[0]=st(10,o<0?ne+o:o),e==null)e=a>0?t:l;else{if(s=new h(e),!s.isInt()||s.lt(l))throw Error($n+s);e=s.gt(t)?a>0?t:l:s}for(ue=!1,s=new h(_t(f)),u=h.precision,h.precision=a=f.length*ne*2;d=Le(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=l,l=c.plus(d.times(i)),c=i,i=t,t=s.minus(d.times(i)),s=i;return i=Le(e.minus(n),r,0,1,1),c=c.plus(i.times(l)),n=n.plus(i.times(r)),c.s=l.s=g.s,m=Le(l,r,a,1).minus(g).abs().cmp(Le(c,n,a,1).minus(g).abs())<1?[l,r]:[c,n],h.precision=u,ue=!0,m};k.toHexadecimal=k.toHex=function(e,t){return Wc(this,16,e,t)};k.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:Nt(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(ue=!1,n=Le(n,e,0,t,1).times(e),ue=!0,X(n)):(e.s=n.s,n=e),n};k.toNumber=function(){return+this};k.toOctal=function(e,t){return Wc(this,8,e,t)};k.toPower=k.pow=function(e){var t,n,r,i,a,o,s=this,c=s.constructor,l=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(st(+s,l));if(s=new c(s),s.eq(1))return s;if(r=c.precision,a=c.rounding,e.eq(1))return X(s,r,a);if(t=At(e.e/ne),t>=e.d.length-1&&(n=l<0?-l:l)<=kx)return i=Wf(c,s,n,r),e.s<0?new c(1).div(i):X(i,r,a);if(o=s.s,o<0){if(t<e.d.length-1)return new c(NaN);if((e.d[t]&1)==0&&(o=1),s.e==0&&s.d[0]==1&&s.d.length==1)return s.s=o,s}return n=st(+s,l),t=n==0||!isFinite(n)?At(l*(Math.log("0."+_t(s.d))/Math.LN10+s.e+1)):new c(n+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?o/0:0):(ue=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Hc(e.times(Vn(s,r+n)),r),i.d&&(i=X(i,r+5,1),zi(i.d,r,a)&&(t=r+10,i=X(Hc(e.times(Vn(s,t+n)),t),t+5,1),+_t(i.d).slice(r+1,r+15)+1==1e14&&(i=X(i,r+1,0)))),i.s=o,ue=!0,c.rounding=a,X(i,r,a))};k.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=bn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Nt(e,1,Gn),t===void 0?t=i.rounding:Nt(t,0,8),r=X(new i(r),e,t),n=bn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};k.toSignificantDigits=k.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Nt(e,1,Gn),t===void 0?t=r.rounding:Nt(t,0,8)),X(new r(n),e,t)};k.toString=function(){var e=this,t=e.constructor,n=bn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};k.truncated=k.trunc=function(){return X(new this.constructor(this),this.e+1,1)};k.valueOf=k.toJSON=function(){var e=this,t=e.constructor,n=bn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function _t(e){var t,n,r,i=e.length-1,a="",o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+"",n=ne-r.length,n&&(a+=qn(n)),a+=r;o=e[t],r=o+"",n=ne-r.length,n&&(a+=qn(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return a+o}function Nt(e,t,n){if(e!==~~e||e<t||e>n)throw Error($n+e)}function zi(e,t,n,r){var i,a,o,s;for(a=e[0];a>=10;a/=10)--t;return--t<0?(t+=ne,i=0):(i=Math.ceil((t+1)/ne),t%=ne),a=st(10,ne-t),s=e[i]%a|0,r==null?t<3?(t==0?s=s/100|0:t==1&&(s=s/10|0),o=n<4&&s==99999||n>3&&s==49999||s==5e4||s==0):o=(n<4&&s+1==a||n>3&&s+1==a/2)&&(e[i+1]/a/100|0)==st(10,t-2)-1||(s==a/2||s==0)&&(e[i+1]/a/100|0)==0:t<4?(t==0?s=s/1e3|0:t==1?s=s/100|0:t==2&&(s=s/10|0),o=(r||n<4)&&s==9999||!r&&n>3&&s==4999):o=((r||n<4)&&s+1==a||!r&&n>3&&s+1==a/2)&&(e[i+1]/a/1e3|0)==st(10,t-3)-1,o}function fo(e,t,n){for(var r,i=[0],a,o=0,s=e.length;o<s;){for(a=i.length;a--;)i[a]*=t;for(i[0]+=$c.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function Rx(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/xo(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=Kr(e,1,t.times(i),new e(1));for(var a=n;a--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var Le=(function(){function e(r,i,a){var o,s=0,c=r.length;for(r=r.slice();c--;)o=r[c]*i+s,r[c]=o%a|0,s=o/a|0;return s&&r.unshift(s),r}function t(r,i,a,o){var s,c;if(a!=o)c=a>o?1:-1;else for(s=c=0;s<a;s++)if(r[s]!=i[s]){c=r[s]>i[s]?1:-1;break}return c}function n(r,i,a,o){for(var s=0;a--;)r[a]-=s,s=r[a]<i[a]?1:0,r[a]=s*o+r[a]-i[a];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,a,o,s,c){var l,u,d,m,g,f,h,x,I,S,T,D,P,be,nt,We,Ne,ce,V,Fe,Q=r.constructor,dt=r.s==i.s?1:-1,pe=r.d,se=i.d;if(!pe||!pe[0]||!se||!se[0])return new Q(!r.s||!i.s||(pe?se&&pe[0]==se[0]:!se)?NaN:pe&&pe[0]==0||!se?dt*0:dt/0);for(c?(g=1,u=r.e-i.e):(c=cn,g=ne,u=At(r.e/g)-At(i.e/g)),V=se.length,Ne=pe.length,I=new Q(dt),S=I.d=[],d=0;se[d]==(pe[d]||0);d++);if(se[d]>(pe[d]||0)&&u--,a==null?(be=a=Q.precision,o=Q.rounding):s?be=a+(r.e-i.e)+1:be=a,be<0)S.push(1),f=!0;else{if(be=be/g+2|0,d=0,V==1){for(m=0,se=se[0],be++;(d<Ne||m)&&be--;d++)nt=m*c+(pe[d]||0),S[d]=nt/se|0,m=nt%se|0;f=m||d<Ne}else{for(m=c/(se[0]+1)|0,m>1&&(se=e(se,m,c),pe=e(pe,m,c),V=se.length,Ne=pe.length),We=V,T=pe.slice(0,V),D=T.length;D<V;)T[D++]=0;Fe=se.slice(),Fe.unshift(0),ce=se[0],se[1]>=c/2&&++ce;do m=0,l=t(se,T,V,D),l<0?(P=T[0],V!=D&&(P=P*c+(T[1]||0)),m=P/ce|0,m>1?(m>=c&&(m=c-1),h=e(se,m,c),x=h.length,D=T.length,l=t(h,T,x,D),l==1&&(m--,n(h,V<x?Fe:se,x,c))):(m==0&&(l=m=1),h=se.slice()),x=h.length,x<D&&h.unshift(0),n(T,h,D,c),l==-1&&(D=T.length,l=t(se,T,V,D),l<1&&(m++,n(T,V<D?Fe:se,D,c))),D=T.length):l===0&&(m++,T=[0]),S[d++]=m,l&&T[0]?T[D++]=pe[We]||0:(T=[pe[We]],D=1);while((We++<Ne||T[0]!==void 0)&&be--);f=T[0]!==void 0}S[0]||S.shift()}if(g==1)I.e=u,qf=f;else{for(d=1,m=S[0];m>=10;m/=10)d++;I.e=d+u*g-1,X(I,s?a+I.e+1:a,o,f)}return I}})();function X(e,t,n,r){var i,a,o,s,c,l,u,d,m,g=e.constructor;e:if(t!=null){if(d=e.d,!d)return e;for(i=1,s=d[0];s>=10;s/=10)i++;if(a=t-i,a<0)a+=ne,o=t,u=d[m=0],c=u/st(10,i-o-1)%10|0;else if(m=Math.ceil((a+1)/ne),s=d.length,m>=s)if(r){for(;s++<=m;)d.push(0);u=c=0,i=1,a%=ne,o=a-ne+1}else break e;else{for(u=s=d[m],i=1;s>=10;s/=10)i++;a%=ne,o=a-ne+i,c=o<0?0:u/st(10,i-o-1)%10|0}if(r=r||t<0||d[m+1]!==void 0||(o<0?u:u%st(10,i-o-1)),l=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(a>0?o>0?u/st(10,i-o):0:d[m-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,l?(t-=e.e+1,d[0]=st(10,(ne-t%ne)%ne),e.e=-t||0):d[0]=e.e=0,e;if(a==0?(d.length=m,s=1,m--):(d.length=m+1,s=st(10,ne-a),d[m]=o>0?(u/st(10,i-o)%st(10,o)|0)*s:0),l)for(;;)if(m==0){for(a=1,o=d[0];o>=10;o/=10)a++;for(o=d[0]+=s,s=1;o>=10;o/=10)s++;a!=s&&(e.e++,d[0]==cn&&(d[0]=1));break}else{if(d[m]+=s,d[m]!=cn)break;d[m--]=0,s=1}for(a=d.length;d[--a]===0;)d.pop()}return ue&&(e.e>g.maxE?(e.d=null,e.e=NaN):e.e<g.minE&&(e.e=0,e.d=[0])),e}function bn(e,t,n){if(!e.isFinite())return Qf(e);var r,i=e.e,a=_t(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+"."+a.slice(1)+qn(r):o>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(e.e<0?"e":"e+")+e.e):i<0?(a="0."+qn(-i-1)+a,n&&(r=n-o)>0&&(a+=qn(r))):i>=o?(a+=qn(i+1-o),n&&(r=n-i-1)>0&&(a=a+"."+qn(r))):((r=i+1)<o&&(a=a.slice(0,r)+"."+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+="."),a+=qn(r))),a}function So(e,t){var n=e[0];for(t*=ne;n>=10;n/=10)t++;return t}function _o(e,t,n){if(t>Tx)throw ue=!0,n&&(e.precision=n),Error(Vf);return X(new e(ho),t,1,!0)}function hn(e,t,n){if(t>Kc)throw Error(Vf);return X(new e(bo),t,n,!0)}function Hf(e){var t=e.length-1,n=t*ne+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 qn(e){for(var t="";e--;)t+="0";return t}function Wf(e,t,n,r){var i,a=new e(1),o=Math.ceil(r/ne+4);for(ue=!1;;){if(n%2&&(a=a.times(t),Bf(a.d,o)&&(i=!0)),n=At(n/2),n===0){n=a.d.length-1,i&&a.d[n]===0&&++a.d[n];break}t=t.times(t),Bf(t.d,o)}return ue=!0,a}function Mf(e){return e.d[e.d.length-1]&1}function zf(e,t,n){for(var r,i,a=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){a=i;break}r=a.cmp(i),(r===n||r===0&&a.s===n)&&(a=i)}return a}function Hc(e,t){var n,r,i,a,o,s,c,l=0,u=0,d=0,m=e.constructor,g=m.rounding,f=m.precision;if(!e.d||!e.d[0]||e.e>17)return new m(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(ue=!1,c=f):c=t,s=new m(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(st(2,d))/Math.LN10*2+5|0,c+=r,n=a=o=new m(1),m.precision=c;;){if(a=X(a.times(e),c,1),n=n.times(++u),s=o.plus(Le(a,n,c,1)),_t(s.d).slice(0,c)===_t(o.d).slice(0,c)){for(i=d;i--;)o=X(o.times(o),c,1);if(t==null)if(l<3&&zi(o.d,c-r,g,l))m.precision=c+=10,n=a=s=new m(1),u=0,l++;else return X(o,m.precision=f,g,ue=!0);else return m.precision=f,o}o=s}}function Vn(e,t){var n,r,i,a,o,s,c,l,u,d,m,g=1,f=10,h=e,x=h.d,I=h.constructor,S=I.rounding,T=I.precision;if(h.s<0||!x||!x[0]||!h.e&&x[0]==1&&x.length==1)return new I(x&&!x[0]?-1/0:h.s!=1?NaN:x?0:h);if(t==null?(ue=!1,u=T):u=t,I.precision=u+=f,n=_t(x),r=n.charAt(0),Math.abs(a=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=_t(h.d),r=n.charAt(0),g++;a=h.e,r>1?(h=new I("0."+n),a++):h=new I(r+"."+n.slice(1))}else return l=_o(I,u+2,T).times(a+""),h=Vn(new I(r+"."+n.slice(1)),u-f).plus(l),I.precision=T,t==null?X(h,T,S,ue=!0):h;for(d=h,c=o=h=Le(h.minus(1),h.plus(1),u,1),m=X(h.times(h),u,1),i=3;;){if(o=X(o.times(m),u,1),l=c.plus(Le(o,new I(i),u,1)),_t(l.d).slice(0,u)===_t(c.d).slice(0,u))if(c=c.times(2),a!==0&&(c=c.plus(_o(I,u+2,T).times(a+""))),c=Le(c,new I(g),u,1),t==null)if(zi(c.d,u-f,S,s))I.precision=u+=f,l=o=h=Le(d.minus(1),d.plus(1),u,1),m=X(h.times(h),u,1),i=s=1;else return X(c,I.precision=T,S,ue=!0);else return I.precision=T,c;c=l,i+=2}}function Qf(e){return String(e.s*e.s/0)}function go(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)%ne,n<0&&(r+=ne),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=ne;r<i;)e.d.push(+t.slice(r,r+=ne));t=t.slice(r),r=ne-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),ue&&(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,a,o,s,c,l,u;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Kf.test(t))return go(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Ox.test(t))n=16,t=t.toLowerCase();else if(Px.test(t))n=2;else if(Ex.test(t))n=8;else throw Error($n+t);for(a=t.search(/p/i),a>0?(c=+t.slice(a+1),t=t.substring(2,a)):t=t.slice(2),a=t.indexOf("."),o=a>=0,r=e.constructor,o&&(t=t.replace(".",""),s=t.length,a=s-a,i=Wf(r,new r(n),a,a*2)),l=fo(t,n,cn),u=l.length-1,a=u;l[a]===0;--a)l.pop();return a<0?new r(e.s*0):(e.e=So(l,u),e.d=l,ue=!1,o&&(e=Le(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?st(2,c):un.pow(2,c))),ue=!0,e)}function Nx(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:Kr(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/xo(5,n)),t=Kr(e,2,t,t);for(var i,a=new e(5),o=new e(16),s=new e(20);n--;)i=t.times(t),t=t.times(a.plus(i.times(o.times(i).minus(s))));return t}function Kr(e,t,n,r,i){var a,o,s,c,l=1,u=e.precision,d=Math.ceil(u/ne);for(ue=!1,c=n.times(n),s=new e(r);;){if(o=Le(s.times(c),new e(t++*t++),u,1),s=i?r.plus(o):r.minus(o),r=Le(o.times(c),new e(t++*t++),u,1),o=s.plus(r),o.d[d]!==void 0){for(a=d;o.d[a]===s.d[a]&&a--;);if(a==-1)break}a=s,s=r,r=o,o=a,l++}return ue=!0,o.d.length=d+1,o}function xo(e,t){for(var n=e;--t;)n*=e;return n}function Zf(e,t){var n,r=t.s<0,i=hn(e,e.precision,1),a=i.times(.5);if(t=t.abs(),t.lte(a))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(a))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 Wc(e,t,n,r){var i,a,o,s,c,l,u,d,m,g=e.constructor,f=n!==void 0;if(f?(Nt(n,1,Gn),r===void 0?r=g.rounding:Nt(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())u=Qf(e);else{for(u=bn(e),o=u.indexOf("."),f?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(u=u.replace(".",""),m=new g(1),m.e=u.length-o,m.d=fo(bn(m),10,i),m.e=m.d.length),d=fo(u,10,i),a=c=d.length;d[--c]==0;)d.pop();if(!d[0])u=f?"0p+0":"0";else{if(o<0?a--:(e=new g(e),e.d=d,e.e=a,e=Le(e,m,n,r,0,i),d=e.d,a=e.e,l=qf),o=d[n],s=i/2,l=l||d[n+1]!==void 0,l=r<4?(o!==void 0||l)&&(r===0||r===(e.s<0?3:2)):o>s||o===s&&(r===4||l||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,l)for(;++d[--n]>i-1;)d[n]=0,n||(++a,d.unshift(1));for(c=d.length;!d[c-1];--c);for(o=0,u="";o<c;o++)u+=$c.charAt(d[o]);if(f){if(c>1)if(t==16||t==8){for(o=t==16?4:3,--c;c%o;c++)u+="0";for(d=fo(u,i,t),c=d.length;!d[c-1];--c);for(o=1,u="1.";o<c;o++)u+=$c.charAt(d[o])}else u=u.charAt(0)+"."+u.slice(1);u=u+(a<0?"p":"p+")+a}else if(a<0){for(;++a;)u="0"+u;u="0."+u}else if(++a>c)for(a-=c;a--;)u+="0";else a<c&&(u=u.slice(0,a)+"."+u.slice(a))}u=(t==16?"0x":t==2?"0b":t==8?"0o":"")+u}return e.s<0?"-"+u:u}function Bf(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 Bx(e){return new this(e).asin()}function Lx(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,a=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=hn(this,a,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?hn(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=hn(this,a,1).times(.5),n.s=e.s):t.s<0?(this.precision=a,this.rounding=1,n=this.atan(Le(e,t,a,1)),t=hn(this,a,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Le(e,t,a,1)),n}function Gx(e){return new this(e).cbrt()}function Kx(e){return X(e=new this(e),e.e+1,2)}function Hx(e,t,n){return new this(e).clamp(t,n)}function Wx(e){if(!e||typeof e!="object")throw Error(yo+"Object expected");var t,n,r,i=e.defaults===!0,a=["precision",1,Gn,"rounding",0,8,"toExpNeg",-Gr,0,"toExpPos",0,Gr,"maxE",0,Gr,"minE",-Gr,0,"modulo",0,9];for(t=0;t<a.length;t+=3)if(n=a[t],i&&(this[n]=Gc[n]),(r=e[n])!==void 0)if(At(r)===r&&r>=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error($n+n+": "+r);if(n="crypto",i&&(this[n]=Gc[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($n+n+": "+r);return this}function zx(e){return new this(e).cos()}function Qx(e){return new this(e).cosh()}function Yf(e){var t,n,r;function i(a){var o,s,c,l=this;if(!(l instanceof i))return new i(a);if(l.constructor=i,Lf(a)){l.s=a.s,ue?!a.d||a.e>i.maxE?(l.e=NaN,l.d=null):a.e<i.minE?(l.e=0,l.d=[0]):(l.e=a.e,l.d=a.d.slice()):(l.e=a.e,l.d=a.d?a.d.slice():a.d);return}if(c=typeof a,c==="number"){if(a===0){l.s=1/a<0?-1:1,l.e=0,l.d=[0];return}if(a<0?(a=-a,l.s=-1):l.s=1,a===~~a&&a<1e7){for(o=0,s=a;s>=10;s/=10)o++;ue?o>i.maxE?(l.e=NaN,l.d=null):o<i.minE?(l.e=0,l.d=[0]):(l.e=o,l.d=[a]):(l.e=o,l.d=[a]);return}if(a*0!==0){a||(l.s=NaN),l.e=NaN,l.d=null;return}return go(l,a.toString())}if(c==="string")return(s=a.charCodeAt(0))===45?(a=a.slice(1),l.s=-1):(s===43&&(a=a.slice(1)),l.s=1),Kf.test(a)?go(l,a):jx(l,a);if(c==="bigint")return a<0?(a=-a,l.s=-1):l.s=1,go(l,a.toString());throw Error($n+a)}if(i.prototype=k,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=Wx,i.clone=Yf,i.isDecimal=Lf,i.abs=Dx,i.acos=Fx,i.acosh=Ux,i.add=Mx,i.asin=Bx,i.asinh=Lx,i.atan=qx,i.atanh=Vx,i.atan2=$x,i.cbrt=Gx,i.ceil=Kx,i.clamp=Hx,i.cos=zx,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=av,i.mod=ov,i.mul=sv,i.pow=cv,i.random=uv,i.round=lv,i.sign=dv,i.sin=mv,i.sinh=pv,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(ue=!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 ue=!0,new this(1/0);n=t}return ue=!0,n.sqrt()}function Lf(e){return e instanceof un||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 zf(this,arguments,-1)}function av(){return zf(this,arguments,1)}function ov(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,a=0,o=new this(1),s=[];if(e===void 0?e=this.precision:Nt(e,1,Gn),r=Math.ceil(e/ne),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));a<r;)i=t[a],i>=429e7?t[a]=crypto.getRandomValues(new Uint32Array(1))[0]:s[a++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);a<r;)i=t[a]+(t[a+1]<<8)+(t[a+2]<<16)+((t[a+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,a):(s.push(i%1e7),a+=4);a=r/4}else throw Error($f);else for(;a<r;)s[a++]=Math.random()*1e7|0;for(r=s[--a],e%=ne,r&&e&&(i=st(10,ne-e),s[a]=(r/i|0)*i);s[a]===0;a--)s.pop();if(a<0)n=0,s=[0];else{for(n=-1;s[0]===0;n-=ne)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<ne&&(n-=ne-r)}return o.e=n,o.d=s,o}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 mv(e){return new this(e).sin()}function pv(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(ue=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return ue=!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)}k[Symbol.for("nodejs.util.inspect.custom")]=k.toString;k[Symbol.toStringTag]="Decimal";var un=k.constructor=Yf(Gc);ho=new un(ho);bo=new un(bo);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=[],a=new Uint8Array(n),o=!1;for(;!o;){o=!0;let s=0;for(let c=0;c<a.length;c++){let l=s*256+a[c];a[c]=Math.floor(l/62),s=l%62,a[c]!==0&&(o=!1)}i.push(s)}for(i.reverse();i.length<r;)i.unshift(0);return i.map(s=>e[s]).join("")}}))(Iv),{generateKsuid:Jf}=((e,t,n,r,i)=>({generateKsuid:({prefix:o=""}={})=>{let s=new Uint8Array(e),c=Math.floor(Date.now()/1e3)-t;s[0]=c>>>24&255,s[1]=c>>>16&255,s[2]=c>>>8&255,s[3]=c&255;let l=n({size:16});s.set(l,4);let u=r({bytes:s,padTo:i});return`${o}${u}`}}))(Sv,xv,vv,wv,Av);var Xf={randomSync:()=>({string:Jf({})})};import{z as Ie}from"zod/v4";var Cv=202,Pv=502,Ov=400,Ev=409,kv=100,Tv=201,Rv=417;var jv=403,Nv=504,Dv=410,Fv=505,Uv=418,Mv=419,Bv=507,Lv=500,qv=411,Vv=423,$v=420,Gv=405,Kv=301,Hv=302,Wv=207,zv=300,Qv=511,Zv=204,Yv=203,Jv=406,Xv=404,eI=501,tI=304,nI=200,rI=206,iI=402,aI=308,oI=412,sI=428,cI=102,uI=407,lI=431,dI=408,mI=413,pI=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:Cv,BAD_GATEWAY:Pv,BAD_REQUEST:Ov,CONFLICT:Ev,CONTINUE:kv,CREATED:Tv,EXPECTATION_FAILED:Rv,FORBIDDEN:jv,GATEWAY_TIMEOUT:Nv,GONE:Dv,HTTP_VERSION_NOT_SUPPORTED:Fv,IM_A_TEAPOT:Uv,INSUFFICIENT_SPACE_ON_RESOURCE:Mv,INSUFFICIENT_STORAGE:Bv,INTERNAL_SERVER_ERROR:Lv,LENGTH_REQUIRED:qv,LOCKED:Vv,METHOD_FAILURE:$v,METHOD_NOT_ALLOWED:Gv,MOVED_PERMANENTLY:Kv,MOVED_TEMPORARILY:Hv,MULTI_STATUS:Wv,MULTIPLE_CHOICES:zv,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:aI,PRECONDITION_FAILED:oI,PRECONDITION_REQUIRED:sI,PROCESSING:cI,PROXY_AUTHENTICATION_REQUIRED:uI,REQUEST_HEADER_FIELDS_TOO_LARGE:lI,REQUEST_TIMEOUT:dI,REQUEST_TOO_LONG:mI,REQUEST_URI_TOO_LONG:pI,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 Kn;(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"})(Kn||(Kn={}));var vo=function(){return vo=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},vo.apply(this,arguments)},NU=vo(vo({},eg),{getStatusCode:rg,getStatusText:ig});var{generateId:Hr}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(Xf),{BILLING_CONTROL_KEYS:Io}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:CI}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:ag}={entToPrice:({ent:t,prices:n})=>{let r=n.filter(i=>i.entitlement_id===t.id);return r.find(i=>i.internal_product_id===t.internal_product_id)??r[0]}},{nullish:Qt}={nullish:t=>t==null},{FeatureType:wt}=(()=>{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:Ao}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:Qi}={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:Pn}=(()=>{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:OI}={usageCurrenciesToTiers:(t,n)=>{if(!t||n<=0)return;let r=Object.entries(t);if(r.length===0)return;let i=Array.from({length:n},()=>[]);for(let[a,o]of r)(o.usage_tiers??[]).forEach((s,c)=>{c<n&&i[c].push({currency:a,amount:s.amount,...s.flat_amount!==void 0?{flat_amount:s.flat_amount}:{}})});return i}},{TierInfinite:zc}={TierInfinite:"inf"},{FeatureUsageType:Hn}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:zr}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Usage="usage"})(e||(e={})),{PriceType:e}})(),{BillingType:Qr}=(()=>{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:Zi}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Wn}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:On}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:Zr}=(()=>{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:a}){super(n),this.name="InternalError",this.code=r||"internal_error",this.statusCode=i,this.data=a}}return{InternalError:e}})(),{getItemFeatureType:og}=((e,t)=>({getItemFeatureType:({item:r,features:i})=>{let a=i.find(o=>o.id===r.feature_id);if(a)return a.type===e.Boolean?t.Static:a.type===e.CreditSystem?t.SingleUse:a.config?.usage_type}}))(wt,On),{billingControlsFromColumns:sg}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(Io),{nullish:Yr}={nullish:t=>t==null},{RecaseError:Dt}=(()=>{class e extends Error{code;statusCode;data;constructor({message:n,code:r,statusCode:i=400,data:a}){super(n),this.name="RecaseError",this.code=r||"invalid_request",this.statusCode=i,this.data=a}}return{RecaseError:e}})(),{ErrCode:Vt}={ErrCode:{PlanAlreadyAttached:"plan_already_attached",PendingPlanConflict:"pending_plan_conflict",IdempotencyKeyAlreadyExists:"idempotency_key_already_exists",IdempotencyKeyNotFound:"idempotency_key_not_found",DuplicateIdempotencyKey:"duplicate_idempotency_key",InvalidApiVersion:"invalid_api_version",NoSecretKey:"no_secret_key",InvalidSecretKey:"invalid_secret_key",NoAuthHeader:"no_auth_header",InvalidAuthHeader:"invalid_auth_header",FailedToVerifySecretKey:"failed_to_verify_secret_key",FailedToFetchKeyFromAutumn:"failed_to_fetch_key_from_autumn",InsufficientScopes:"insufficient_scopes",NoPublishableKey:"no_publishable_key",InvalidPublishableKey:"invalid_publishable_key",GetOrgFromPublishableKeyFailed:"get_org_from_publishable_key_failed",EndpointNotPublic:"endpoint_not_public",FailedToVerifyPublishableKey:"failed_to_verify_publishable_key",InvalidInputs:"invalid_inputs",InvalidRequest:"invalid_request",InvalidExpand:"invalid_expand",InvalidOptions:"invalid_options",InvalidCursor:"invalid_cursor",RequestTemporarilyDisabled:"request_temporarily_disabled",OrgNotFound:"org_not_found",OrgHasCustomers:"org_has_customers",MigrationNotFound:"migration_not_found",FeatureNotFound:"feature_not_found",InvalidFeature:"invalid_feature",DuplicateFeatureId:"duplicate_feature_id",InvalidEventName:"invalid_event_name",FeatureLimitReached:"feature_limit_reached",InternalError:"internal_error",DuplicateCustomerId:"duplicate_customer_id",StripeKeyNotFound:"stripe_key_not_found",DuplicateCustomerEmail:"duplicate_customer_email",StripeError:"stripe_error",StripeKeyInvalid:"stripe_key_invalid",StripeAccountMismatch:"stripe_account_mismatch",StripeConfigNotFound:"stripe_config_not_found",StripeDeleteCustomerFailed:"stripe_delete_customer_failed",StripeCreateCustomerFailed:"stripe_create_customer_failed",StripeCreateProductFailed:"stripe_create_product_failed",StripeCancelSubscriptionFailed:"stripe_cancel_subscription_failed",StripeGetPaymentMethodFailed:"stripe_get_payment_method_failed",StripeCardDeclined:"stripe_card_declined",StripeUpdateSubscriptionFailed:"stripe_update_subscription_failed",StripeCancelSubscriptionScheduleFailed:"stripe_cancel_subscription_schedule_failed",StripeCreateSubscriptionFailed:"stripe_create_subscription_failed",PriceNotFound:"price_not_found",CreatePriceFailed:"create_price_failed",InvalidPrice:"invalid_price",InvalidPriceId:"invalid_price_id",InvalidPriceOptions:"invalid_price_options",InvalidPriceConfig:"invalid_price_config",CusPriceNotFound:"cus_price_not_found",InvalidCustomer:"invalid_customer",CreateCustomerFailed:"create_customer_failed",CustomerNotFound:"customer_not_found",CustomersNotFound:"customers_not_found",CustomerAlreadyHasProduct:"customer_already_has_product",CustomerHasNoPaymentMethod:"customer_has_no_payment_method",CustomerHasNoBaseProduct:"customer_has_no_base_product",AttachProductToCustomerFailed:"attach_product_to_customer_failed",CustomerEntitlementNotFound:"customer_entitlement_not_found",MultipleCustomersFound:"multiple_customers_found",InvalidUpdateCustomerParams:"invalid_update_customer_params",CurrencyMismatch:"currency_mismatch",CreateStripeProductFailed:"create_stripe_product_failed",DeleteStripeProductFailed:"delete_stripe_product_failed",CreateStripeSubscriptionFailed:"create_stripe_subscription_failed",CusProductNotFound:"cus_product_not_found",DuplicateSubscriptionId:"duplicate_subscription_id",InvalidEntitlement:"invalid_entitlement",CreateEntitlementFailed:"create_entitlement_failed",DeleteEntitlementFailed:"delete_entitlement_failed",InsufficientBalance:"insufficient_balance",CreateInvoiceFailed:"create_invoice_failed",InvalidEvent:"invalid_event",CreateEventFailed:"create_event_failed",DuplicateEvent:"duplicate_event",NoActiveCusProducts:"no_active_cus_products",GetCusProductsFailed:"get_cus_products_failed",GetCusPriceFailed:"get_cus_price_failed",PayInvoiceFailed:"invoice_payment_failed",InvalidReward:"invalid_reward",ProductNotInStripe:"product_not_in_stripe",DuplicateRewardId:"duplicate_reward_id",DuplicatePromoCode:"duplicate_promo_code",PromoCodeAlreadyExistsInStripe:"promo_code_already_exists_in_stripe",PromoCodeFirstTimeOnly:"promo_code_first_time_only",EntityNotFound:"entity_not_found",EntityAlreadyDeleted:"entity_already_deleted",ReferralCodeMaxRedemptionsReached:"referral_code_max_redemptions_reached",ReferralNotFound:"referral_not_found",CustomerAlreadyRedeemedReferralCode:"customer_already_redeemed_referral_code",CustomerCannotRedeemOwnCode:"customer_cannot_redeem_own_code",InvalidProductItem:"invalid_product_item",EntityIdRequired:"entity_id_required",LockAlreadyExists:"lock_already_exists",InsertSubscriptionFailed:"insert_subscription_failed",UpdateSubscriptionFailed:"update_subscription_failed",RewardNotFound:"reward_not_found",RewardProgramNotFound:"reward_program_not_found",InsertRewardProgramFailed:"insert_reward_program_failed",InsertReferralCodeFailed:"insert_referral_code_failed",ReferralCodeNotFound:"referral_code_not_found",UpdateRewardRedemptionFailed:"update_reward_redemption_failed",RewardRedemptionNotFound:"reward_redemption_not_found",InsertRewardRedemptionFailed:"insert_reward_redemption_failed",InsertMigrationJobFailed:"insert_migration_job_failed",InsertMigrationErrorFailed:"insert_migration_error_failed",MigrationJobNotFound:"migration_job_not_found",MigrationAlreadyInProgress:"migration_already_in_progress",CustomerExportInProgress:"customer_export_in_progress",SupabaseNotFound:"supabase_not_found",EntityBalanceNotFound:"entity_balance_not_found",TinybirdDisabled:"tinybird_disabled",ClickHouseDisabled:"tinybird_disabled",PaymentMethodNotFound:"payment_method_not_found",VercelSubscriptionAlreadyExists:"vercel_subscription_already_exists",VercelSubscriptionNotFound:"vercel_subscription_not_found",VercelResourceNotFound:"vercel_resource_not_found",ProductNotFound:"product_not_found",NestedVariantNotAllowed:"nested_variant_not_allowed",CannotForkArchivedBase:"cannot_fork_archived_base",ProductIdAlreadyExists:"product_id_already_exists",DuplicateVersionSlug:"duplicate_version_slug",CannotPreviewOnVariant:"cannot_preview_on_variant",InvalidPropagationTarget:"invalid_propagation_target",ConflictingVariantAnchor:"conflicting_variant_anchor",VariantCrossPlanAnchor:"variant_cross_plan_anchor",TooManyVariants:"too_many_variants",ConflictingVersionFlags:"conflicting_version_flags",VariantCannotBeDefault:"variant_cannot_be_default",HistoricalPlanVersionCannotBeDefault:"historical_plan_version_cannot_be_default",UnderMaintenance:"under_maintenance"}},{validateFeatureId:kI}=((e,t)=>({validateFeatureId:r=>{if(!r.match(/^[a-zA-Z0-9_-]+$/))throw new e({message:"Feature ID can only contain alphanumeric characters, underscores, and hyphens",code:t.InvalidFeature,statusCode:400})}}))(Dt,Vt),{notNullish:Jr}=(e=>({notNullish:n=>!e(n)}))(Yr),{keyToTitle:cg}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:TI}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:RI}=(()=>{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:Qc}=(()=>{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:wo}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:Xr}=(()=>{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:Yi}=(()=>{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:mg}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ie),{flatCreditRateShape:pg}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(Ie),{CreditTierSchema:BI}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(Ie),{CreditMultiplierSchema:LI}=((e,t)=>({CreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional(),add:e.number().optional()}).refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add"})}))(Ie,mg),{MarkupEntrySchema:fg}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(Ie),{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()}))(Ie,fg),{isFeaturePriceItem:Yc}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(Jr),{notNullish:hr}={notNullish:t=>t!=null},{isAiCreditSystem:Jc}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(wt),{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 a=Object.entries(n).find(([o])=>o===r)?.[1];return a===void 0||a===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,a=n.add!==void 0;!i&&!a&&r(`Multiplier "${t}" needs a factor or an add.`);let o=Number(n.factor);i&&!(Number.isFinite(o)&&o>0)&&r(`Multiplier "${t}" factor must be greater than zero.`);let s=Number(n.add);a&&!Number.isFinite(s)&&r(`Multiplier "${t}" add must be a number.`),i&&(n.factor=o),a&&(n.add=s)}},{minimumCreditRateAmount:HI}={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:WI}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((a,o)=>{let s=[];for(let l of r){let u=l.factor!==void 0&&l.factor<1||l.add!==void 0&&l.add<0,d=s.every(m=>e(m.match,l.match));(u||l===o)&&e(o.match,l.match)&&d&&s.push(l)}let c=s.reduce((l,u)=>l.mul(u.factor!==void 0&&u.factor<1?u.factor:1).add(u.add!==void 0&&u.add<0?u.add:0),new t(i));return t.min(a,c)},new t(i))}))(gg,un),{validateCreditSystemSchemaReferences:zI}=((e,t,n,r)=>({validateCreditSystemSchemaReferences:({config:a,allFeatures:o,selfFeatureId:s})=>{let c=Array.isArray(a?.schema)?a.schema:[];if(c.length!==0)for(let l of c){let u=l.metered_feature_id;if(!u||u===s)continue;let d=o.find(m=>m.id===u);if(d){if(d.type===e.CreditSystem)throw new t({message:`Credit system schema cannot reference another credit system (${u}). 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 ${u}. 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 ${u}. Only consumable (single-use) metered features are allowed.`,code:n.InvalidFeature,statusCode:400})}}}}))(wt,Dt,Vt,Hn),{isPriceItem:Xc}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(Jr,Yr),{isFeatureItem:Co}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(Jr,Yr),{itemToBillingInterval:zn}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(Qt,Pn),{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:Po}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(Qt,Wr,On),{itemToEntIntervalCount:Oo}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:ei}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:Eo}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(hr,Qt),{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}}))(Qt),{UsageTierSchema:eu}=((e,t)=>({UsageTierSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional()}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(r=>({...r,amount:r.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional()}))}))(Ie,Qi),{IgnoredFixedPriceMetadataSchema:YI}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(Ie),{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)}))(Wn),{getResetUsage:bg}=((e,t,n,r)=>({getResetUsage:({item:a,feature:o})=>{if(a.feature_id)return e(a.reset_usage_when_enabled)&&(t(a)||n(a))&&o?o?.config?.usage_type===r.Single:a.reset_usage_when_enabled}}))(Yr,Co,Yc,Hn),{hasUnlimitedAllowanceType:t1}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(Ao),{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:tu}=(()=>{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:a1}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:o1}={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:ti}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(hr),{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 a=[...new Set(r.flatMap(s=>(s.additional_currencies??[]).map(c=>e(c.currency))))];if(a.length===0)return;let o={};for(let s of a)o[s]={usage_tiers:n.map((c,l)=>{let u=(r[l]?.additional_currencies??[]).find(d=>e(d.currency)===s);return{to:c.to,amount:u?.amount??0,...u?.flat_amount!==void 0?{flat_amount:u.flat_amount}:{}}})};return o}if(i?.length&&n.length>0){let a={};for(let{currency:o,amount:s}of i)a[e(o)]={usage_tiers:[{to:n[0].to,amount:s}]};return a}}}))(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}))(Xr,Yi),{getBillingType:d1}=((e,t,n,r)=>({getBillingType:a=>{if(a.type===e.Fixed&&a.interval===t.OneOff)return n.OneOff;if(a.type===e.Fixed)return n.FixedCycle;let o=a;return o.bill_when===r.InAdvance||o.bill_when===r.StartOfPeriod?n.UsageInAdvance:o.bill_when===r.EndOfPeriod&&o.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(zr,Pn,Qr,Zi),{stripeResourceFields:m1}={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:p1}={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)}))(Qt),{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:a,sameEnts:o,features:s})=>({prices:[...t,...r,...a],entitlements:[...n,...i,...o].map(c=>({...c,feature:s.find(l=>l.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})}}))(Dt,Vt),{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:C1}={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:O1}={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:nu}={additionalCurrenciesCompatible:(t,n)=>(t??[]).every(r=>{let i=(n??[]).find(a=>a.currency.toLowerCase()===r.currency.toLowerCase());return!i||(r.amount??null)===(i.amount??null)&&(r.flat_amount??null)===(i.flat_amount??null)})},{toBasePriceParams:k1}={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:T1}=(e=>({tiersEqual:(n,r)=>!n?.length&&!r?.length?!0:!n||!r||n.length!==r.length?!1:n.every((i,a)=>{let o=r[a];return i.to===o.to&&(i.amount??0)===(o.amount??0)&&(i.flat_amount??null)===(o.flat_amount??null)&&e(i.additional_currencies,o.additional_currencies)})}))(nu),{rolloversEqual:R1}={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}])))}))(tu),{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 a=n.price?.interval??n.reset?.interval;a!==void 0&&(i.interval=a);let o=n.price?.interval_count??n.reset?.interval_count;return a!==void 0&&(i.interval_count=o??1),r===e.IdentityAndIncluded&&typeof n.included=="number"&&n.unlimited!==!0&&(n.reset!=null||n.price!=null)&&(i.included=n.included),i}}))(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(a=>{let o=i.findIndex(s=>r(a,s));return o===-1?!1:(i.splice(o,1),!0)})}},{normalizeIntervalCount:B1}={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:L1}={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:VU}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:$1}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(Qt),{isPriceItem:ko}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(hr,Qt),{isDefaultTrialV2:$U}=(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:H1}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:W1}={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:z1}={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 o={[t.Minute]:1,[t.Hour]:60,[t.Day]:1440,[t.Week]:1440*7,[t.Month]:1440*30,[t.Quarter]:1440*90,[t.SemiAnnual]:1440*180,[t.Year]:1440*365,[t.Lifetime]:1e9}[r];return new e(o).mul(i??1)}}))(un,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)}))(Pn),{normalizeIncludedUsage:wg}={normalizeIncludedUsage:t=>t??0},{rolloversAreSame:Cg}={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)}))(Xr,Yi),{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)}))(hr,Wn),{additionalCurrenciesAreSame:ru}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let a=(c,l)=>c.currency.localeCompare(l.currency),o=[...r].sort(a),s=[...i].sort(a);return o.every((c,l)=>c.currency===s[l].currency&&(c.amount??null)===(s[l].amount??null)&&(c.flat_amount??null)===(s[l].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:a,logDifferences:o=!1})=>{let s=i.price===a.price&&e({item:i})==e({item:a})&&t({item:i})==t({item:a})&&n(i.additional_currencies,a.additional_currencies);return!s&&o&&console.log(`Price items different: ${i.price}`),s}}))(zn,ei,ru),{calculateProrationAmount:tA}=(e=>({calculateProrationAmount:({periodEnd:n,periodStart:r,now:i,amount:a,allowNegative:o=!1})=>{let s=new e(n).minus(i),c=new e(n).minus(r),l=s.div(c).mul(a);return l.lte(0)&&!o?0:l.toNumber()}}))(un),{getResetUsage:nA}=((e,t,n,r)=>({getResetUsage:({item:a,feature:o})=>{if(a.feature_id)return e(a.reset_usage_when_enabled)&&(t(a)||n(a))&&o?o?.config?.usage_type===r.Single:a.reset_usage_when_enabled}}))(Qt,Eo,ti,Hn),{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(a=>a.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(a=>a.condition)}},{normalizeBillingControlsForCompare:aA}=(e=>({normalizeBillingControlsForCompare:n=>{if(!n)return;let r=n.spend_limits?.map(a=>{if(a.skip_overage_billing===!0)return a;let{skip_overage_billing:o,...s}=a;return s}),i=Object.fromEntries(e.flatMap(a=>{let o=a==="spend_limits"?r:n[a];return o==null||o.length===0?[]:[[a,o]]}));return Object.keys(i).length>0?i:void 0}}))(Io),{sortControls:oA}={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??{},(a,o)=>o&&typeof o=="object"&&!Array.isArray(o)?Object.keys(o).sort().reduce((s,c)=>(s[c]=o[c],s),{}):o);return r(t)===r(n)}},{freeTrialsAreSame: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(a=>a.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)}))(Ie,CI),{entToItemInterval:Pg}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))(Wr),{billingToItemInterval:Og}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(Pn),{isContUseFeature:Eg}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(Hn),{getBillingType:iu}=((e,t,n,r)=>({getBillingType:a=>{if(a.type===e.Fixed&&a.interval===t.OneOff)return n.OneOff;if(a.type===e.Fixed)return n.FixedCycle;let o=a;return o.bill_when===r.InAdvance||o.bill_when===r.StartOfPeriod?n.UsageInAdvance:o.bill_when===r.EndOfPeriod&&o.should_prorate?n.InArrearProrated:n.UsageInArrear}}))(zr,Pn,Qr,Zi),{isAllocatedPrice:kg}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(iu,Qr),{priceToEnt:au}=(e=>{function t({price:n,entitlements:r,errorOnNotFound:i}){let a=r.filter(s=>s.id===n.entitlement_id),o=a.find(s=>s.internal_product_id===n.internal_product_id)??a[0];if(!o&&i)throw new e({message:`Entitlement not found for price ${n.id}`});return o}return{priceToEnt:t}})(EI),{isBooleanFeatureItem:Tg}=((e,t)=>({isBooleanFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)&&t(r.interval)&&t(r.included_usage)}))(Jr,Yr),{constructBooleanFeature:dA}=((e,t,n)=>({constructBooleanFeature:({featureId:i,orgId:a,env:o,name:s})=>({internal_id:e("fe"),org_id:a,env:o,created_at:Date.now(),id:i,name:s||t(i),type:n.Boolean,config:null,archived:!1,event_names:[],model_markups:null})}))(Hr,cg,wt),{constructMeteredFeature:mA}=((e,t,n,r)=>({constructMeteredFeature:({featureId:a,name:o,orgId:s,env:c,usageType:l,eventNames:u=[]})=>({internal_id:e("fe"),org_id:s,env:c,created_at:Date.now(),id:a,name:o||t(a),type:n.Metered,config:{filters:[{property:"event_name",operator:"eq",value:[]}],aggregate:{type:r.Sum,property:"value"},usage_type:l},archived:!1,event_names:u,model_markups:null})}))(Hr,cg,wt,TI),{ApiFeatureV0Schema:pA}=((e,t)=>({ApiFeatureV0Schema:e.object({id:e.string().meta({description:"The ID of the feature, used to refer to it in other API calls like /track or /check."}),name:e.string().nullish().meta({description:"The name of the feature."}),type:e.enum(t).meta({description:"The type of the feature"}),display:e.object({singular:e.string().meta({description:"The singular display name for the feature."}),plural:e.string().meta({description:"The plural display name for the feature."})}).nullish().meta({description:"Singular and plural display names for the feature."}),credit_schema:e.array(e.object({metered_feature_id:e.string().meta({description:"The ID of the metered feature (should be a single_use feature)."}),credit_cost:e.number().meta({description:"The credit cost of the metered feature."})})).nullish().meta({description:"Credit cost schema for credit system features."}),archived:e.boolean().nullish().meta({description:"Whether or not the feature is archived."})})}))(Ie,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()})}))(Ie,Zc),{EntitlementExpirySchema:hA}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(Ie,FI),{CreditDimensionNameSchema:bA}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ie,UI,MI),{CreditDimensionBaseSchema:_A}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(Ie,mg),{graduatedCreditRateShape:Rg}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(Ie,BI),{ProviderMarkupsSchema:yA}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ie,fg),{isAnyCreditSystem:SA}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(wt,Jc),{findCreditTierViolations:xA}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(VI),{findAmbiguousCreditDimensions:vA}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),a=[];for(let[o,[s,c]]of i.entries())for(let[l,u]of i.slice(o+1))e(c,u)&&t(c.match,u.match)&&a.push({names:[s,l],example:{...c.match,...u.match}});return a}}))($I,gg),{validateMultipliersKeepRatesNonNegative:IA}=((e,t)=>({validateMultipliersKeepRatesNonNegative:({schemaItem:r,invalidCreditSystem:i})=>{let a=Object.values(r.multipliers??{}),o=[r,...Object.values(r.dimensions??{})],s=Math.min(...o.map(e));t({multipliers:a,cheapestRate:s}).lt(0)&&i(`Multipliers on ${r.metered_feature_id} can take a rate below zero.`)}}))(HI,WI),{buildFixedPriceCurrencies:AA}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:a}of n)r[e(i)]={amount:a};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()})}))(Ie,eu),{baseCurrenciesAreCompatible:wA}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:a})=>(n??null)===(r??null)||e(i)!==e(a)}))(JI),{tiersAreSame:Ng}=(e=>({tiersAreSame:(n,r)=>{if(n.length!==r.length)return!1;let i=e(n),a=e(r);return i.every((o,s)=>{let c=a[s];return o.amount===c?.amount&&o.flat_amount===c.flat_amount&&o.to===c.to})}}))(XI),{UsagePriceConfigSchema:CA}=((e,t,n,r,i,a)=>({UsagePriceConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish(),type:e.string(),bill_when:e.nativeEnum(t),billing_units:e.number().nullish(),internal_feature_id:e.string(),feature_id:e.string(),usage_tiers:e.array(n),interval:e.enum(r),interval_count:e.number().optional(),base_currency:e.string().nullish(),currencies:e.record(e.string(),i).nullish(),stripe_meter_id:e.string().nullish(),stripe_price_id:e.string().nullish(),stripe_empty_price_id:e.string().nullish(),stripe_product_id:e.string().nullish(),stripe_placeholder_price_id:e.string().nullish(),stripe_event_name:e.string().nullish(),stripe_prepaid_price_v2_id:e.string().nullish(),should_prorate:e.boolean().optional(),allocated_billing_behavior:e.enum(a).optional()})}))(Ie,Zi,eu,Pn,jg,Wn),{toFeature:PA}=((e,t,n,r,i,a,o)=>({toFeature:({item:c,orgId:l,internalFeatureId:u,internalProductId:d,isCustom:m,newVersion:g,feature:f,curEnt:h})=>{let x=f?.type===e.Boolean,I=t({item:c,feature:f}),S={id:c.entitlement_id||h?.id||n("ent"),org_id:l,created_at:c.created_at||Date.now(),is_custom:m,internal_product_id:d||null,internal_feature_id:u,feature_id:c.feature_id,allowance:c.included_usage===r?null:c.included_usage,allowance_type:x?null:c.included_usage===r?i.Unlimited:i.Fixed,interval:x?null:a({item:c}),interval_count:o({item:c}),carry_from_previous:!I,entity_feature_id:c.entity_feature_id,pooled:c.pooled??!1,usage_limit:null,rollover:c.config?.rollover,expiry_duration:c.config?.expiry?.duration,expiry_length:c.config?.expiry?.length,feature_override:c.config?.feature_override};return(m||g)&&(S={...S,id:n("ent"),created_at:Date.now()}),{price:null,ent:S}}}))(wt,bg,Hr,Qi,Ao,Po,Oo),{creditDimensionRulesEqual:OA}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(tu),{markupRecordsAreSame:EA}=(e=>({markupRecordsAreSame:(n,r)=>[...new Set([...Object.keys(n??{}),...Object.keys(r??{})])].every(i=>e.every(a=>(n?.[i]?.[a]??null)===(r?.[i]?.[a]??null)))}))(a1),{itemToUsageType:kA}=((e,t,n)=>({itemToUsageType:({item:i,features:a})=>{let o=e({item:i,features:a});return!o||!o.config?null:o.type===t.Boolean?n.Static:o.type===t.CreditSystem?n.SingleUse:o.config.usage_type}}))(yg,wt,On),{itemToUsageType:TA}=((e,t,n)=>({itemToUsageType:({item:i,features:a})=>{let o=e({item:i,features:a});return o?o.type==t.Boolean?n.Static:o.type==t.CreditSystem?n.SingleUse:o.config.usage_type:null}}))(u1,wt,On),{isPreviewStripeId:RA}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(p1,f1),{findPairedEntitlement:jA}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(au),{isConsumablePrice:NA}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(iu,Qr),{validateLicenseLink:GU}=((e,t,n)=>({validateLicenseLink:({parentProduct:i,licenseProduct:a,prepaidOnly:o,licensePlanId:s})=>{if(o!==void 0&&e({prepaidOnly:o}),s&&a.archived)throw new t({message:`License plan ${s} is archived and cannot be linked.`,code:n.InvalidRequest,statusCode:400});if(a.base_internal_product_id)throw new t({message:`A variant cannot be used as a plan license (${s??a.id}).`,code:n.InvalidRequest});if(i&&a.id===i.id)throw new t({message:`A plan cannot be linked as a license to itself (${s??a.id}).`,code:n.InvalidRequest,statusCode:400})}}))(S1,Dt,Vt),{evaluateCatalogItemIdentity:DA}=(e=>({evaluateCatalogItemIdentity:({item:n,recipe:r=e})=>{let i=[];for(let a of r.components){let o;for(let c of a.paths){o=n;for(let l of c.split("."))o=o!==null&&typeof o=="object"?o[l]:void 0;if(o!=null)break}let s=a.defaultWhen&&i[a.defaultWhen.component]?a.defaultWhen.value:a.default;if(o!=null&&typeof o!="string"&&typeof o!="number")throw new Error("Catalog identity components must be strings or numbers");i.push(o??s)}return i}}))(v1),{removeItems:FA}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(a=>e({item:i,filter:a})))}))(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)})}))(C1,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)),a=new Map((r.upsert_licenses??[]).map(s=>[s.license_plan_id,s])),o=[];for(let s of n.licenses??[]){if(i.has(s.license_plan_id))continue;let c=a.get(s.license_plan_id);if(c){o.push(e({existing:s,upsert:c})),a.delete(s.license_plan_id);continue}o.push(s)}for(let s of r.upsert_licenses??[])a.has(s.license_plan_id)&&o.push(e({upsert:s}));return o}}))(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)}))(nu),{itemPricesEqual:BA}=((e,t,n)=>({itemPricesEqual:(i,a)=>{if(i==null&&a==null)return!0;if(i==null||a==null)return!1;let o=i.tiers?.length?i.tier_behavior??e.Graduated:null,s=a.tiers?.length?a.tier_behavior??e.Graduated:null;return(i.amount??null)===(a.amount??null)&&t(i.additional_currencies,a.additional_currencies)&&n(i.tiers,a.tiers)&&o===s&&i.interval===a.interval&&(i.interval_count??1)===(a.interval_count??1)&&(i.billing_units??1)===(a.billing_units??1)&&i.billing_method===a.billing_method&&(i.max_purchase??null)===(a.max_purchase??null)}}))(wo,nu,T1),{featureOverridesEqual:LA}=((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,tu),{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)}))(B1),{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:KU}=((e,t)=>({getVariantSettingsPatch:({from:r,to:i})=>{let a={};for(let o of e)t(r[o],i[o])||(a[o]=i[o]);return a}}))(q1,V1),{isOneOffProductV2:HU}=((e,t,n,r)=>({isOneOffProductV2:({items:a})=>{let o=a.filter(s=>e(s)||t(s));return o.length>0&&o.every(s=>n({item:s})===r.OneOff)}}))(ko,ti,zn,Pn),{canonicalizeBillingControls:GA}=(e=>({canonicalizeBillingControls:n=>{let r=n??{},i={};for(let a of Object.keys(r)){let o=r[a];Array.isArray(o)&&o.length===0||(i[a]=Array.isArray(o)?[...o].sort((s,c)=>String(s?.feature_id??"").localeCompare(String(c?.feature_id??""))):o)}return JSON.stringify(e(i))}}))(vg),{ProductConfigSchema:KA}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(Ie,K1),{shouldApplyVariantUpdates:WU}=(e=>({shouldApplyVariantUpdates:({oldBase:n,latestBase:r,propagateToVariants:i,variantUpdates:a,updates:o})=>i.length>0||a.length>0||n.internal_id!==r.internal_id?!0:e.some(s=>o[s]!==void 0)}))(H1),{resolveLicenseParentTargets:zU}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:a,childPlanId:o})=>{let s=new Map(i.map(u=>[e({planId:u.parent.id,version:u.parent.version}),u])),c=new Set,l=[];for(let u of a){let d=e({planId:u.plan_id,version:u.version});if(c.has(d))throw new t({message:`Parent plan target ${d} was selected more than once.`,code:n.InvalidPropagationTarget,statusCode:400});let m=s.get(d);if(!m)throw new t({message:`Plan ${u.plan_id} v${u.version} does not offer ${o} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),l.push(m)}return l}}))(W1,Dt,Vt),{stripeMinorUnitFactor:To}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(Ig,z1),{entIntervalsSame:HA}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),a=e(r.interval,r.intervalCount);return i.eq(a)}}))(Q1),{intervalsDifferent:WA}=((e,t)=>({intervalsDifferent:({intervalA:r,intervalB:i})=>{if(e(r)&&e(i))return!1;if(e(r)||e(i))return!0;let a=t(r.interval,r.intervalCount),o=t(i.interval,i.intervalCount);return a!==o}}))(Qt,Z1),{allocatedBillingBehaviorAreSame:zA}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),a=e(r);return i===a}}))(J1),{tiersAreSame:QA}=(e=>({tiersAreSame:(n,r)=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every((i,a)=>i.amount===r[a].amount&&i.to===r[a].to&&(i.flat_amount??null)===(r[a].flat_amount??null)&&e(i.additional_currencies,r[a].additional_currencies))}))(ru),{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(a=>({...a,amount:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:a.amount}):a.amount}))}:{price:r?e({periodEnd:r.end,periodStart:r.start,now:i,amount:n.tiers[0].amount}):n.tiers[0].amount,tiers:void 0}}}))(tA),{normalizeBillingControls:YA}=((e,t,n)=>({normalizeBillingControls:i=>{let a=e(i);return JSON.stringify(t.flatMap(o=>{let s=a?.[o];return s?.length?[[o,n(s)]]:[]}))}}))(aA,Io,oA),{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."})})}))(Ie,lA),{toFeatureItem:XA}=((e,t,n,r)=>({toFeatureItem:({ent:a})=>{if(a.feature.type===e.Boolean)return{feature_id:a.feature.id,entity_feature_id:a.entity_feature_id,entitlement_id:a.id};let o=a.rollover||a.feature_override?{rollover:a.rollover??void 0,feature_override:a.feature_override??void 0}:void 0;return{feature_id:a.feature.id,included_usage:a.allowance_type===t.Unlimited?n:a.allowance,interval:r({entInterval:a.interval}),interval_count:a.interval_count??1,entity_feature_id:a.entity_feature_id,pooled:a.pooled??!1,reset_usage_when_enabled:!a.carry_from_previous,config:o,entitlement_id:a.id,created_at:a.created_at}}}))(wt,Ao,Qi,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}}}))(Og,PI),{isPayPerUsePrice:Fg}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(iu,Qr),{createFeaturesFromItems:tw}=((e,t,n,r,i,a,o,s,c,l)=>({createFeaturesFromItems:({items:d,curFeatures:m,orgId:g,env:f})=>{let h=[];for(let x of d){if(!x.feature_id)continue;let I=m.find(S=>S.id===x.feature_id);if(I){if(e(x.feature_type))continue;if(x.feature_type===t.Static){if(x.feature_type===t.Static&&I.type!==n.Boolean)throw new r({message:`Feature ${x.feature_id} already exists but is not a static feature`,code:i.InvalidRequest,statusCode:400})}else if(x.feature_type!==I.config?.usage_type)throw new r({message:`Feature ${x.feature_id} already exists but is not a ${x.feature_type} feature`,code:i.InvalidRequest,statusCode:400});continue}if(a(x.feature_id),o(x)){let S=s({featureId:x.feature_id,orgId:g,env:f});h.push(S)}else{if(!x.feature_type)throw new r({message:`Feature type is required for ${x.feature_id}. Either 'continuous_use' or 'single_use'`,code:i.InvalidRequest,statusCode:400});let S=c({featureId:x.feature_id,orgId:g,env:f,usageType:x.feature_type===t.ContinuousUse?l.Continuous:l.Single});h.push(S)}}return{allFeatures:[...m,...h],newFeatures:h}}}))(Yr,On,wt,Dt,Vt,kI,Tg,dA,mA,Hn),{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)])}))(Ie,_A,pg,Rg),{FeatureMarkupsOverrideSchema:iw}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(Ie,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 a=n.tiers??[];for(let s of a){let c=Number(s.credit_amount);(!Number.isFinite(c)||c<0)&&r("Tier credit costs must be zero or greater."),s.credit_amount=c,s.to!=="inf"&&(s.to=Number(s.to))}let[o]=e(a.map(s=>s.to));o&&r(o.message);return}let i=Number(n.credit_amount);(!Number.isFinite(i)||i<0)&&r("Credit cost must be zero or greater."),n.credit_amount=i}}))(xA),{validateDimensionsAreSeparable:aw}=((e,t)=>({validateDimensionsAreSeparable:({dimensions:r,invalidCreditSystem:i})=>{let[a]=e(r);if(!a)return;let[o,s]=a.names;i(`Dimensions "${o}" and "${s}" can both match the same event (${t(a.example)}). Give one more match keys or a priority.`)}}))(vA,GI),{validateCreditMultipliers:ow}=((e,t)=>({validateCreditMultipliers:({schemaItem:r,invalidCreditSystem:i})=>{for(let[a,o]of Object.entries(r.multipliers??{}))e({name:a,multiplier:o,invalidCreditSystem:i});t({schemaItem:r,invalidCreditSystem:i})}}))(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})}))(Ie,Pn,jg,eu,YI),{currenciesAreCompatible:cw}=(e=>({currenciesAreCompatible:(n,r)=>{let i=n??{},a=r??{};for(let o of Object.keys(i)){let s=a[o];if(!s)continue;let c=i[o];if((c?.amount??null)!==(s.amount??null)||!e(c?.usage_tiers??[],s.usage_tiers??[]))return!1}return!0}}))(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,a)=>i.to===r.tiers?.[a]?.to&&i.credit_amount==r.tiers?.[a]?.credit_amount)}))(OA),{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:a,curPrice:o})=>{if(e(a.config?.allocated_billing_behavior))return a.config.allocated_billing_behavior;if(e(a.config?.on_increase)||e(a.config?.on_decrease))return t.Prorated;if(o&&n({price:o})){let c=o.config;return e(c.allocated_billing_behavior)?c.allocated_billing_behavior:r(o)?t.Prorated:t.Arrear}return t.Arrear}}))(hr,Wn,Fg,kg),{itemCanBeProrated:mw}=((e,t,n)=>({itemCanBeProrated:({item:i,features:a})=>{let o=e({item:i,features:a});return o===t.SingleUse&&i.usage_model===n.Prepaid?!0:o===t.ContinuousUse}}))(TA,On,Zr),{priceHasPreviewStripeId:pw}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(a=>t({stripeId:i[a]}))}}))(m1,RA),{buildPlanItemKey:fw}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let a=t({item:r});return i===e.FeatureCadence&&a.splice(1,1),a.join("|")}}))(x1,DA),{itemsEqual:Mg}=((e,t,n,r)=>({itemsEqual:(a,o)=>a.feature_id===o.feature_id&&(a.entity_feature_id??null)===(o.entity_feature_id??null)&&(a.pooled??!1)===(o.pooled??!1)&&(a.included??0)===(o.included??0)&&(a.unlimited??!1)===(o.unlimited??!1)&&(a.reset?.interval??null)===(o.reset?.interval??null)&&(a.reset?.interval_count??1)===(o.reset?.interval_count??1)&&e(a.price,o.price)&&t(a.rollover,o.rollover)&&n(a.proration,o.proration)&&r(a.feature_override,o.feature_override)}))(BA,R1,j1,LA),{licenseCustomizesAreSame:gw}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:a,right:o})=>{let s=a??{},c=o??{},l={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(l).some(Boolean)}}))(Dg,M1,Mg,VA),{normalizeVariantSettingValue:hw}=((e,t,n)=>({normalizeVariantSettingValue:({field:i,value:a})=>{if(i==="group")return a||"";if(i==="description")return a||null;if(i==="billing_controls")return e(a);if(i==="config"){let o=t.safeParse(a??{});return JSON.stringify(n(o.success?o.data:a??{}))}return i==="metadata"?JSON.stringify(n(a??{})):a}}))(GA,KA,vg),{intervalsSame:bw}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(WA),{sanitizeItems:_w}=((e,t,n,r)=>({sanitizeItems:({items:a,features:o})=>a.map(s=>{let c=s.tiers?.length===1&&s.tiers[0].additional_currencies?.length?{price:void 0,tiers:s.tiers}:e({item:s}),l={...s,reset_usage_when_enabled:t({item:s,feature:o.find(u=>u.id===s.feature_id)}),...c};return l.config||(l.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),l})}))(ZA,nA,Xr,Yi),{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."})})}))(Ie,JA),{toFeaturePriceItem:xw}=((e,t,n,r,i,a,o,s,c,l,u)=>({toFeaturePriceItem:({ent:m,price:g})=>{let f=g.config,h=e(f.currencies,f.usage_tiers.length),x=f.usage_tiers.map((T,D)=>({amount:T.amount,to:T.to===-1?t:T.to,flat_amount:T.flat_amount,...h?.[D]?.length?{additional_currencies:h[D]}:{}})),I={};return g.proration_config&&(I={...g.proration_config}),n({feature:m.feature})&&r({price:g})&&(I.allocated_billing_behavior=f.allocated_billing_behavior??(i(g)?a.Prorated:a.Arrear)),m.rollover&&(I.rollover=m.rollover),m.expiry_duration&&m.expiry_length!=null&&(I.expiry={duration:m.expiry_duration,length:m.expiry_length}),m.feature_override&&(I.feature_override=m.feature_override),f.threshold_billing&&(I.threshold_billing=f.threshold_billing),{feature_id:m.feature.id,feature_type:m.feature.config?.usage_type||o.SingleUse,included_usage:m.allowance,interval:s({entInterval:m.interval}),interval_count:m.interval_count??1,price_interval:c({billingInterval:f.interval}),price_interval_count:f.interval_count??1,price:null,tiers:x,base_currency:f.base_currency??void 0,billing_units:f.billing_units,tier_behavior:g.tier_behavior??null,entity_feature_id:m.entity_feature_id,pooled:m.pooled??!1,reset_usage_when_enabled:!m.carry_from_previous,usage_model:f.bill_when===l.StartOfPeriod||f.bill_when===l.InAdvance?u.Prepaid:u.PayPerUse,created_at:m.created_at,entitlement_id:m.id,price_id:g.id,price_config:g.config,config:Object.keys(I).length>0?I:void 0,usage_limit:m.usage_limit}}}))(OI,zc,Eg,Fg,kg,Wn,On,Pg,Og,Zi,Zr),{isValidCurrencyCode:ou}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(nw),{CreditSchemaItemBaseSchema:Bg}=((e,t,n,r)=>({CreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string(),feature_amount:e.number().optional(),dimensions:e.record(t,n).optional(),multipliers:e.record(t,r).optional()})}))(Ie,bA,rw,LI),{GraduatedCreditSchemaItemSchema:vw}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(Bg,Rg),{validateCreditDimensionRules:Iw}=((e,t,n)=>({validateCreditDimensionRules:({schemaItem:i,invalidCreditSystem:a})=>{let o=i.dimensions??{};for(let[s,c]of Object.entries(o))c.priority!==void 0&&!Number.isInteger(c.priority)&&a(`Dimension "${s}" priority must be an integer.`),e({rate:c,invalidCreditSystem:a});t({dimensions:o,invalidCreditSystem:a}),n({schemaItem:i,invalidCreditSystem:a})}}))(Ug,aw,ow),{pricesAreSame:Ro}=((e,t,n,r,i,a,o,s)=>({pricesAreSame:(l,u,d=!1)=>{let m=l.config,g=u.config;if(m.type!==g.type)return!1;if(m.type===e.Fixed){let D=t.parse(m),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(m),h=i.parse(g),x={shouldProrate:(f.should_prorate??!1)!==(h.should_prorate??!1),allocatedBillingBehavior:a(f)!==a(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:!o(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:l.proration_config?.on_increase!=u.proration_config?.on_increase,onDecrease:l.proration_config?.on_decrease!=u.proration_config?.on_decrease,tierBehavior:!I&&(l.tier_behavior??s.Graduated)!==(u.tier_behavior??s.Graduated)},T=Object.values(x).some(Boolean)||Object.values(S).some(Boolean);return T&&d&&console.log("Prices are different",{configDiffs:x,prorationDiffs:S}),!T}}))(zr,sw,wA,cw,CA,e1,Ng,wo),{creditSchemasAreSame:Aw}=(e=>({creditSchemasAreSame:({schema1:n,schema2:r})=>!n&&!r?!0:!n||!r||n.length!==r.length?!1:n.every(i=>{let a=r.find(o=>o.metered_feature_id===i.metered_feature_id);return a?e({left:i,right:a}):!1})}))(uw),{itemToAllocatedBillingBehavior:ww}=((e,t,n,r,i,a,o,s,c)=>({itemToAllocatedBillingBehavior:({item:u,features:d,curPrice:m})=>{if(!(e({item:u,features:d})===t.ContinuousUse&&n(u)&&u.usage_model!==r.Prepaid))return null;let h=i({item:u,curPrice:m});if(h===a.Arrear){if(o(u.config?.on_increase)||o(u.config?.on_decrease))throw new s({message:`on_increase / on_decrease are not supported for allocated arrear billing (feature: ${u.feature_id})`,code:c.InvalidProductItem,statusCode:400});if(o(u.config?.rollover))throw new s({message:`rollover is not supported for allocated arrear billing because the balance never resets (feature: ${u.feature_id})`,code:c.InvalidProductItem,statusCode:400})}return h}}))(kA,On,ti,Zr,dw,Wn,hr,Dt,s1),{composeMatchKey:Ji}=(e=>({composeMatchKey:n=>e({item:n})}))(fw),{applyItems:Cw}=((e,t,n,r)=>({applyItems:(a,o)=>{let s=[...a];if(o.remove_items&&(s=e(s,o.remove_items)),o.add_items){let c=new Set;for(let l of s)t(l)&&c.add(n(l));for(let l of o.add_items){let u=n(l);t(l)&&c.has(u)||(s.push(r(l)),t(l)&&c.add(u))}}return s}}))(FA,w1,Ji,UA),{dedupeItemsByMatchKey:Pw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(Ji),{planLicensesAreSame:Ow}=(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 a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(Ji),{validateVariantSettingsUpdate:QU}=((e,t,n,r)=>({validateVariantSettingsUpdate:({allowVariantSettingsUpdate:a,fullProduct:o,currentProduct:s,updates:c})=>{if(a||o.base_internal_product_id==null)return;let l=e.find(u=>c[u]===void 0?!1:t({field:u,value:c[u]})!==t({field:u,value:s[u]}));if(l)throw new n({message:`Cannot update ${l} directly on a variant plan.`,code:r.InvalidPropagationTarget,statusCode:400})}}))(G1,hw,Dt,Vt),{findSimilarItem:su}=((e,t,n,r,i,a,o,s,c)=>({findSimilarItem:({item:u,items:d})=>e(u)?d.find(m=>e(m)&&m.feature_id===u.feature_id&&m.entity_feature_id==u.entity_feature_id&&t({intervalA:{interval:n({item:m}),intervalCount:r({item:m})},intervalB:{interval:n({item:u}),intervalCount:r({item:u})}})):i(u)?d.find(m=>i(m)&&m.feature_id===u.feature_id&&m.entity_feature_id==u.entity_feature_id&&a({intervalA:{interval:o({item:m}),intervalCount:s({item:m})},intervalB:{interval:o({item:u}),intervalCount:s({item:u})}})&&u.usage_model==m.usage_model):c(u)?d.find(m=>c(m)&&m.price==u.price&&o({item:m})==o({item:u})&&s({item:m})==s({item:u})):null}))(Eo,HA,Po,Oo,ti,bw,zn,ei,ko),{stripAutoTopupCountsForStorage:kw}=(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:Lg}=((e,t,n,r)=>({toProductItem:({ent:a,price:o})=>e(o)?t({ent:a}):e(a)?n({price:o}):r({ent:a,price:o})}))(Qt,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')."})}))(Ie,ou),{AdditionalCurrencyPriceSchema:Tw}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(Ie,qg),{FlatCreditSchemaItemSchema:Rw}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(Bg,pg),{validateCreditSystem:jw}=((e,t,n,r,i,a,o,s)=>({validateCreditSystem:(l,u=e.CreditSystem)=>{let d=Array.isArray(l?.schema)?l.schema:[],m=S=>{throw new t({message:S,code:n.InvalidFeature,statusCode:r.BAD_REQUEST})};!i(u)&&d.length===0&&m("At least one metered feature is required for credit system"),i(u)&&d.length>0&&m("AI credit systems are leaf features and cannot define a schema. Model rates live in model_markups.");let g=d.map(S=>S.metered_feature_id),f=Array.from(new Set(g));g.length!==f.length&&m("Credit system contains multiple of the same metered_feature_id");let h={...l,schema:d,usage_type:a.Single},x=h.default_markup;if(x!=null){let S=Number(x);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,T]of Object.entries(I)){let D=Number(T?.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});T.markup=D}for(let S of h.schema){if(S.feature_amount!==void 0){let T=Number(S.feature_amount);(!Number.isFinite(T)||T<=0)&&m("Billing units must be greater than zero."),S.feature_amount=T}o({rate:S,invalidCreditSystem:m}),s({schemaItem:S,invalidCreditSystem:m})}return h}}))(wt,Dt,Vt,Kn,Jc,Hn,Ug,Iw),{stripePriceIdForInitializedPrice:Vg}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:a,newPrice:o})=>{if(!e(i)&&(!a||i!==t({price:a})||n(a,o)))return i}}))(Qt,ZI,Ro),{featureOverridesAreSame:cu}=((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:a,diff:o})=>{let s={price:e(a.price,o.price),items:t(a.items,o),free_trial:n(a.free_trial,o.free_trial)},c=r({base:a,diff:o});return c===void 0?s:{...s,licenses:c}}}))(I1,Cw,O1,MA),{diffPlanLicenses:Nw}=((e,t,n,r)=>({diffPlanLicenses:({from:a,to:o,includeAdds:s=!1,includeRemoves:c=!1})=>{let l=new Map((a??[]).map(g=>[g.license_plan_id,g])),u=new Map((o??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of u.values()){let f=l.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 m=c?[...l.keys()].filter(g=>!u.has(g)).map(g=>({license_plan_id:g})):[];return{...d.length>0?{upsert_licenses:d.sort(r)}:{},...m.length>0?{remove_licenses:m.sort(r)}:{}}}}))(Ow,$A,xg,L1),{applyDiffToVariantPlan:ZU}=((e,t)=>({applyDiffToVariantPlan:({plan:r,diff:i,settingsPatch:a={}})=>{let o=e({base:r,diff:i});return{...r,...o,...a,items:t(o.items)}}}))($g,Ew),{mapToProductItems:Gg}=((e,t,n,r)=>({mapToProductItems:({prices:a,entitlements:o,features:s})=>{let c=[];a??=[],o??=[];for(let l of o){let u=e({ent:l,prices:a}),d=t({ent:l,price:u});c.push(d)}for(let l of a)n({price:l,entitlements:o})||c.push(t({price:l}));for(let l of c)s.find(d=>d.id===l.feature_id)&&(l.feature_type=r({item:l,features:s}));return c}}))(ag,Lg,au,og),{featureItemsAreSame:Dw}=((e,t,n)=>({featureItemsAreSame:({item1:i,item2:a,logDifferences:o=!1})=>{let s={feature_id:{condition:i.feature_id===a.feature_id,message:`Feature ID different: ${i.feature_id} != ${a.feature_id}`},included_usage:{condition:e(i.included_usage)==e(a.included_usage),message:`Included usage different: ${i.included_usage} != ${a.included_usage}`},interval:{condition:i.interval==a.interval,message:`Interval different: ${i.interval} != ${a.interval}`},interval_count:{condition:(i.interval_count||1)==(a.interval_count||1),message:`Interval count different: ${i.interval_count} != ${a.interval_count}`},entity_feature_id:{condition:i.entity_feature_id==a.entity_feature_id,message:`Entity feature ID different: ${i.entity_feature_id} != ${a.entity_feature_id}`},pooled:{condition:(i.pooled??!1)===(a.pooled??!1),message:`Pooled different: ${i.pooled} != ${a.pooled}`},reset_usage_when_enabled:{condition:(i.reset_usage_when_enabled??!1)===(a.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${i.reset_usage_when_enabled} !== ${a.reset_usage_when_enabled}`},rollover_config:{condition:t({rollover1:i.config?.rollover||void 0,rollover2:a.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(i.config?.rollover)} !== ${JSON.stringify(a.config?.rollover)}`},feature_override:{condition:n({override1:i.config?.feature_override,override2:a.config?.feature_override}),message:`Feature override different: ${JSON.stringify(i.config?.feature_override)} !== ${JSON.stringify(a.config?.feature_override)}`},threshold_billing:{condition:(i.config?.threshold_billing?.threshold??null)===(a.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(i.config?.threshold_billing)} !== ${JSON.stringify(a.config?.threshold_billing)}`}},c=Object.values(s).every(l=>l.condition);return!c&&o&&console.log("Feature items different:",Object.values(s).filter(l=>!l.condition).map(l=>l.message)),c}}))(wg,Cg,cu),{featurePriceItemsAreSame:Fw}=((e,t,n,r,i,a,o,s,c,l)=>({featurePriceItemsAreSame:({item1:d,item2:m,logDifferences:g=!1})=>{let f={included_usage:{condition:e(d.included_usage)==e(m.included_usage),message:`Included usage different: ${d.included_usage} != ${m.included_usage}`},usage_limit:{condition:d.usage_limit==m.usage_limit,message:`Usage limit different: ${d.usage_limit} !== ${m.usage_limit}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(m.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${m.reset_usage_when_enabled}`},proration_config:{condition:t({config1:d.config||void 0,config2:m.config||void 0}),message:`Proration config different: ${JSON.stringify(d.config)} !== ${JSON.stringify(m.config)}`},allocated_billing_behavior:{condition:n({item1:d,item2:m}),message:`Allocated billing behavior different: ${d.config?.allocated_billing_behavior} !== ${m.config?.allocated_billing_behavior}`},rollover_config:{condition:r({rollover1:d.config?.rollover||void 0,rollover2:m.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(d.config?.rollover)} !== ${JSON.stringify(m.config?.rollover)}`},feature_override:{condition:i({override1:d.config?.feature_override,override2:m.config?.feature_override}),message:`Feature override different: ${JSON.stringify(d.config?.feature_override)} !== ${JSON.stringify(m.config?.feature_override)}`},threshold_billing:{condition:(d.config?.threshold_billing?.threshold??null)===(m.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(d.config?.threshold_billing)} !== ${JSON.stringify(m.config?.threshold_billing)}`},entity_feature_id:{condition:d.entity_feature_id==m.entity_feature_id,message:`Entity feature ID different: ${d.entity_feature_id} != ${m.entity_feature_id}`},pooled:{condition:(d.pooled??!1)===(m.pooled??!1),message:`Pooled different: ${d.pooled} != ${m.pooled}`}},h={feature_id:{condition:d.feature_id===m.feature_id,message:`Feature ID different: ${d.feature_id} != ${m.feature_id}`},interval:{condition:a({item:d})==a({item:m}),message:`Billing interval different: ${a({item:d})} != ${a({item:m})}`},interval_count:{condition:o({item:d})==o({item:m}),message:`Billing interval count different: ${o({item:d})} != ${o({item:m})}`},usage_model:{condition:d.usage_model===m.usage_model,message:`Usage model different: ${d.usage_model} != ${m.usage_model}`},pricing:{condition:s(c(d),c(m)),message:`Pricing different: ${JSON.stringify(c(d))} != ${JSON.stringify(c(m))}`},additional_currencies:{condition:l(d.additional_currencies,m.additional_currencies),message:"Additional currencies different"},tier_behavior:{condition:(c(d)?.length??0)<=1&&(c(m)?.length??0)<=1?!0:d.tier_behavior==m.tier_behavior,message:`Tiers type different: ${d.tier_behavior} != ${m.tier_behavior}`},billing_units:{condition:d.billing_units==m.billing_units,message:`Billing units different: ${d.billing_units} !== ${m.billing_units}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(m.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${m.reset_usage_when_enabled}`}},x=Object.values(h).every(S=>S.condition)&&Object.values(f).every(S=>S.condition),I=Object.values(h).some(S=>!S.condition);return!x&&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:x,pricesChanged:I}}}))(wg,Y1,zA,Cg,cu,zn,ei,QA,X1,ru),{pickBillingControlColumns:Uw}=((e,t)=>({pickBillingControlColumns:r=>{if(!r)return{};let i=Object.fromEntries(e.flatMap(a=>r[a]===void 0?[]:[[a,r[a]]]));return i.auto_topups!==void 0&&(i.auto_topups=t(i.auto_topups)),i}}))(Io,kw),{mapToProductV2:YU}=((e,t,n,r,i)=>({mapToProductV2:({product:o,features:s})=>{let c=[];for(let u of o.entitlements){let d=e({ent:u,prices:o.prices});c.push(t({ent:u,price:d}))}for(let u of o.prices)n({price:u,entitlements:o.entitlements})||c.push(t({price:u}));s||(s=o.entitlements.map(u=>u.feature));for(let u of c)u.feature_type=r({item:u,features:s});return{internal_id:o.internal_id,id:o.id,name:o.name,description:o.description??null,is_add_on:o.is_add_on,is_default:o.is_default,version:o.version,version_slug:o.version_slug??null,active:o.active??!1,group:o.group||null,free_trial:o.free_trial,created_at:o.created_at,env:o.env,items:c,stripe_id:o.processor?.id||null,archived:o.archived||!1,config:o.config??void 0,billing_controls:i(o),metadata:o.metadata??{}}}}))(ag,Lg,au,og,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"]})}))(Ie,qg),{AdditionalCurrencyPriceArraySchema:Bw}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ie,Tw,lg,dg),{CreditSchemaItemSchema:Lw}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(Ie,Rw,vw),{validateItemFeatureOverride:qw}=((e,t,n,r,i,a,o,s,c)=>({validateItemFeatureOverride:({item:u,feature:d,features:m})=>{let g=u.config?.feature_override;if(!g)return;let f=x=>{throw new e({message:`${x} (feature: ${u.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&&!a(d.type)&&f("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let h={schema:g.schema,usage_type:o.Single};s(h,d.type),c({config:h,allFeatures:m});for(let x of g.schema)if(!m.find(S=>S.id===x.metered_feature_id))throw new e({message:`feature_override on ${d.id} references unknown feature ${x.metered_feature_id}`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})}}))(Dt,Vt,Kn,SA,wt,Jc,Hn,jw,zI),{toPrice:Vw}=((e,t,n,r,i,a,o)=>({toPrice:({item:c,orgId:l,internalProductId:u,isCustom:d,newVersion:m,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 x=c.base_currency??(h?g?.config?.base_currency:void 0);x&&(f.base_currency=x);let I={id:c.price_id||g?.id||a("pr"),created_at:c.created_at||Date.now(),org_id:l,internal_product_id:u,is_custom:d,config:f,proration_config:null};return(d||m)&&(I={...I,id:a("pr"),created_at:Date.now()}),f.stripe_price_id=o({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:I}),{price:I,ent:null}}}))(zr,Jr,zn,ei,AA,Hr,Vg),{entsAreSame:uu}=((e,t,n,r,i,a,o)=>({entsAreSame:(c,l)=>{if(c.internal_feature_id!==l.internal_feature_id||e(c)!==e(l))return!1;let u=e(c),d={interval:t(c)!==t(l),intervalCount:n(c)!==n(l),allowance:!u&&c.allowance!=l.allowance,carryFromPrevious:(c.carry_from_previous??!1)!==(l.carry_from_previous??!1),entityFeatureId:r(c.entity_feature_id)!==r(l.entity_feature_id),pooled:(c.pooled??!1)!==(l.pooled??!1),usageLimit:c.usage_limit!=l.usage_limit,rollover:!i({rollover1:c.rollover,rollover2:l.rollover}),featureOverride:!a({override1:c.feature_override,override2:l.feature_override}),expiry:!o(c,l)};return!Object.values(d).some(Boolean)}}))(t1,_g,n1,r1,i1,cu,o1),{toFeatureAndPrice:$w}=((e,t,n,r,i,a,o,s,c,l,u,d,m,g,f,h,x,I,S,T,D,P,be,nt,We,Ne,ce,V)=>({toFeatureAndPrice:({item:Q,orgId:dt,internalFeatureId:pe,internalProductId:se,isCustom:$t,curPrice:ze,curEnt:Gt,newVersion:En,features:Zt})=>{let Wg=e({item:Q,feature:Zt.find(Ot=>Ot.id===Q.feature_id)}),jo=t({item:Q,features:Zt,curPrice:ze}),mu=jo===n.Arrear,br={id:Q.entitlement_id||Gt?.id||r("ent"),org_id:dt,created_at:Q.created_at||Date.now(),is_custom:$t,internal_product_id:se,internal_feature_id:pe,feature_id:Q.feature_id,allowance:Q.included_usage||0,allowance_type:i.Fixed,interval:a({item:Q}),interval_count:o({item:Q}),carry_from_previous:!Wg,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};(!Gt||$t&&!s(Gt,br)||En)&&(br={...br,id:r("ent"),created_at:Date.now()});let zg=a({item:Q}),ni={type:c.Usage,bill_when:Q.usage_model===l.Prepaid?u.StartOfPeriod:u.EndOfPeriod,billing_units:Q.billing_units||1,...Q.config?.threshold_billing?{threshold_billing:Q.config.threshold_billing}:{},should_prorate:zg===d.Lifetime&&!mu,...jo?{allocated_billing_behavior:jo}:{},internal_feature_id:pe,feature_id:Q.feature_id,usage_tiers:m(Q.price)?[{amount:Q.price,to:g}]:Q.tiers?.map(Ot=>({to:Ot.to,amount:Ot.amount??0,...Ot.flat_amount!=null?{flat_amount:Ot.flat_amount}:{}})),interval:f({item:Q}),interval_count:h({item:Q}),stripe_price_id:void 0},pu=x({baseTiers:ni.usage_tiers,itemTiers:Q.tiers,flatCurrencies:Q.additional_currencies});pu&&(ni.currencies=pu,ni.base_currency=Q.base_currency??ze?.config?.base_currency??void 0);let Qg=I({item:Q,features:Zt})&&!mu,fu=null;if(Qg){let Ot=Q.config?.on_increase||S.ProrateImmediately,Qn=Q.config?.on_decrease||T.Prorate;(D(Qn)||Qn===T.Prorate)&&(Qn=Ot===S.ProrateImmediately||Ot===S.BillImmediately?T.ProrateImmediately:T.ProrateNextCycle),fu={on_increase:Ot,on_decrease:Qn}}let _n={id:Q.price_id||ze?.id||r("pr"),created_at:Q.created_at||Date.now(),org_id:dt,internal_product_id:se,is_custom:$t,config:ni,entitlement_id:br.id,proration_config:fu,tier_behavior:Q.tier_behavior??null},gu=P(_n.config);if((gu===be.UsageInArrear||gu===be.InArrearProrated)&&_n.config.interval===nt.OneOff)throw new We({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${Q.feature_id})`,code:Ne.InvalidPrice,statusCode:400});let Zg=ze&&!ce(ze,_n,!0)||Gt&&!s(Gt,br);if(ze&&(Zg||En)){let Ot=_n.config,Qn=ze.config;Ot.stripe_meter_id=Qn.stripe_meter_id,Ot.stripe_product_id=Qn.stripe_product_id,_n.config=Ot}return($t||En)&&(_n={..._n,id:r("pr"),created_at:Date.now()}),ni.stripe_price_id=V({requestedStripePriceId:Q.stripe_price_id,currentPrice:ze,newPrice:_n}),{price:_n,ent:br}}}))(bg,ww,Wn,Hr,Ao,Po,Oo,uu,zr,Zr,Zi,Wr,Jr,zc,zn,ei,c1,mw,Xr,Yi,l1,d1,Qr,Pn,Dt,Vt,Ro,Vg),{getPriceStripeReuseLevel:Gw}=((e,t,n,r,i,a)=>({getPriceStripeReuseLevel:({newPrice:s,candidatePrice:c,newEntitlements:l,candidateEntitlements:u})=>{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:l}),x=r({price:c,entitlements:u});if(!h&&!x)return"full";if(!h||!x)return"none";if(i(x,h))return"full"}if(s.config?.type!==n.Usage)return"none";let d=s.config,m=c.config;if(d.feature_id!==m.feature_id)return"none";let g=r({price:s,entitlements:l}),f=r({price:c,entitlements:u});return!g&&!f?"stripeProductOnly":!g||!f||a(g.entity_feature_id)!==a(f.entity_feature_id)?"none":"stripeProductOnly"}}))(pw,Ro,zr,jA,uu,g1),{applyLicenseCustomizeToBasePlan:JU}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:a})=>{let o=new Set((a.add_items??[]).map(l=>e(l))),s={...i,items:i.items.filter(l=>!o.has(e(l)))},c=t({base:s,diff:a});return{...s,...c,items:n(c.items)}}}))(Ji,$g,Pw),{diffPlanV1:Kw}=((e,t,n,r,i,a,o,s,c)=>({diffPlanV1:({from:u,to:d,includeAdds:m=!1,includeRemoves:g=!1,filterPrecision:f=e.Identity})=>{let h={};t(u.price,d.price)||(h.price=d.price===null?null:n(d.price));let x=new Map(u.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=x.get(r(D));(!P||!i(P,D))&&S.push(a(D))}S.length>0&&(h.add_items=S);let T=[];for(let D of u.items){let P=I.get(r(D));(!P||!i(D,P))&&T.push(o({item:D,filterPrecision:f}))}if(T.length>0&&(h.remove_items=T),!s(u.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:u.licenses,to:d.licenses,includeAdds:m,includeRemoves:g})),h}}))(Sg,Dg,k1,Ji,Mg,D1,F1,qA,Nw),{currentItemsOf:Kg}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))(Gg),{itemsAreSame:Hg}=((e,t,n,r,i,a,o,s)=>({itemsAreSame:({item1:l,item2:u,features:d,logDifferences:m=!1})=>{let g=!1,f=!1;if(e(l)){if(!e(u))return{same:!1,pricesChanged:!0};g=t({item1:l,item2:u,logDifferences:m}),f=!1}if(n(l)){if(!n(u))return{same:!1,pricesChanged:!0};let{same:h,pricesChanged:x}=r({item1:l,item2:u,logDifferences:m});g=h,i({item:l,features:d||[]})?.config?.usage_type===a.Continuous?f=!0:f=x}return o(l)&&(g=s({item1:l,item2:u,logDifferences:m}),g||(f=!0)),{same:g,pricesChanged:!g&&f}}}))(Eo,Dw,ti,Fw,yg,Hn,ko,eA),{productsAreSame:XU}=((e,t,n,r,i,a,o,s,c,l,u,d,m)=>({productsAreSame:({newProductV1:f,newProductV2:h,curProductV1:x,curProductV2:I,features:S})=>{if(!f&&!h)throw new Error("productsAreSame error: product1 not provided");if(!x&&!I)throw new Error("productsAreSame error: product2 not provided");let T=h?.items||e({prices:f?.prices||[],entitlements:f?.entitlements||[],features:S}),D=I?.items||e({prices:x?.prices||[],entitlements:x?.entitlements||[],features:S});T=t({items:T,features:S}),D=t({items:D,features:S});let P=!0,be=!1,nt=!0,We=!0,Ne=!0,ce=[],V=[];nt=n({newProductV2:h,curProductV2:I}),We=r({newConfig:h?.config,curConfig:I?.config}),Ne=i({newBillingControls:h?.billing_controls??(f?a(f):void 0),curBillingControls:I?.billing_controls??(x?a(x):void 0)});let Fe=o({newMetadata:h?.metadata,curMetadata:I?.metadata});T.length!==D.length&&(P=!1),T.length!==D.length&&(P=!1);for(let ze of T){let Gt=s({item:ze,items:D});if(!Gt){(c(ze)||l(ze))&&(be=!0),P=!1,ce.push(ze);continue}let{same:En,pricesChanged:Zt}=u({item1:ze,item2:Gt,features:S,logDifferences:!1});En||(P=!1,ce.push(ze)),Zt&&(be=!0)}for(let ze of D)s({item:ze,items:T})||(P=!1,(c(ze)||l(ze))&&(be=!0),V.push(ze));let Q=x?.free_trial||I?.free_trial,dt=f?.free_trial||h?.free_trial,pe=d({ft1:Q,ft2:dt}),se=m({curProduct:I||x,newProduct:h||f});return{itemsSame:P,freeTrialsSame:pe,onlyEntsChanged:!be,newItems:ce,removedItems:V,detailsSame:nt,optionsSame:se,configSame:We,billingControlsSame:Ne,metadataSame:Fe,same:P&&nt&&pe&&We&&Fe&&Ne}}}))(Gg,_w,rA,iA,yw,sg,sA,su,ti,ko,Hg,cA,uA),{constructProduct:eM}=((e,t)=>({constructProduct:({productData:r,version:i=1,orgId:a,env:o,processor:s,baseInternalProductId:c})=>({id:r.id,name:r.name,description:r.description??null,is_add_on:r.is_add_on,is_default:r.is_default,version:i,version_slug:`v${i}`,active:!0,group:r.group||"",env:o,internal_id:e("prod"),org_id:a,created_at:Date.now(),processor:s,base_variant_id:null,base_internal_product_id:c??r.base_internal_product_id??null,archived:r.archived??!1,deleted_at:null,previous_version_slug:null,config:{...r.config,ignore_past_due:r.config?.ignore_past_due??!1},...t(r.billing_controls),metadata:r.metadata??{}})}))(Hr,Uw),{AdditionalCurrencyTierArraySchema:Hw}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ie,Mw,lg,dg),{FeatureConfigOverrideSchema:Ww}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(Ie,Lw,iw),{itemToPriceAndEnt:zw}=((e,t,n,r,i,a,o,s,c,l)=>({itemToPriceAndEnt:({item:d,orgId:m,internalProductId:g,feature:f,curPrice:h,curEnt:x,isCustom:I,newVersion:S,features:T})=>{let D=null,P=null,be=null,nt=null,We=null,Ne=null;if(e(d)){let{price:ce}=t({item:d,orgId:m,internalProductId:g,isCustom:I,newVersion:S,curPrice:h});!h||S?D=ce:n(h,ce,!0)?We=h:be=ce}else if(r(d)){if(!f)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let ce=f?.type===o.Boolean,{ent:V}=s({item:d,orgId:m,internalFeatureId:f.internal_id,internalProductId:g,isCustom:I,newVersion:S,feature:f,curEnt:x});!x||S?P=V:c(x,V)?Ne=x:nt=V}else{if(!f)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let{price:ce,ent:V}=l({item:d,orgId:m,internalFeatureId:f.internal_id,internalProductId:g,isCustom:I,curPrice:h,curEnt:x,newVersion:S,features:T}),Fe=x&&c(x,V);!h||S?D=ce:!Fe||!n(h,ce,!1)?be=ce:We=h,!x||S?P=V:Fe?Ne=x:nt=V}return{newPrice:D,newEnt:P,updatedPrice:be,updatedEnt:nt,samePrice:We,sameEnt:Ne}}}))(Xc,Vw,Ro,Co,Dt,Vt,wt,PA,uu,$w),{copyStripeResourcesToMatchingPrice:Qw}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:o,candidatePrices:s,targetEntitlements:c,candidateEntitlements:l})=>{let u=s.map(I=>({candidatePrice:I,level:e({newPrice:o,candidatePrice:I,newEntitlements:c,candidateEntitlements:l})})),d=u.find(I=>I.level==="full"),g=(d??u.find(I=>I.level==="stripeProductOnly"))?.candidatePrice,f=d?.candidatePrice,h=o.config,x=[];if(g){let I=g.config;for(let S of t)S==="stripe_meter_id"&&(!n(o)||!n(g))||r({fromConfig:I,toConfig:h,field:S})&&x.push(S)}if(f){let I=f.config;for(let S of i)t.includes(S)||r({fromConfig:I,toConfig:h,field:S})&&x.push(S)}return{copiedFields:x}}}))(Gw,h1,NA,b1,_1),{getApiPlanDiff:tM}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(Kw),{backfillExistingItemIds:Zw}=((e,t)=>({backfillExistingItemIds:({items:r,currentFullProduct:i,features:a})=>{let o=e({currentFullProduct:i,features:a});return r.map(s=>{if(s.entitlement_id||s.price_id)return s;let c=t({item:s,items:o});return c?{...s,...c.entitlement_id?{entitlement_id:c.entitlement_id}:{},...c.price_id?{price_id:c.price_id}:{}}:s})}}))(Kg,su),{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}))}))(Ie,zc,Hw),{ProductItemConfigSchema:Jw}=((e,t,n,r,i,a,o)=>({ProductItemConfigSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),allocated_billing_behavior:e.enum(t).nullish(),on_increase:e.enum(n).nullish(),on_decrease:e.enum(r).nullish(),rollover:i.nullish(),expiry:a.nullish(),feature_override:o.nullish()})}))(Ie,Wn,Xr,Yi,gA,hA,Ww),{carryForwardStripeResources:Xw}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:a})=>{for(let o of n)e({targetPrice:o,candidatePrices:i,targetEntitlements:r,candidateEntitlements:a})}}))(Qw),{resolveInPlaceEdit:nM}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:a,items:o,currentFullProduct:s,features:c})=>{let l=e({items:o,currentFullProduct:s,features:c}),u=t({currentFullProduct:s,features:c}),d=[],m=[];for(let h of u){let x=n({item:h,items:l}),I=!x,S=x&&!r({item1:x,item2:h,features:c}).same;(I||S)&&(h.entitlement_id&&d.push(h.entitlement_id),h.price_id&&m.push(h.price_id))}let g=new Set([...d,...m]),f=l.map(h=>{let x=h.entitlement_id&&g.has(h.entitlement_id),I=h.price_id&&g.has(h.price_id);return x||I?{...h,entitlement_id:void 0,price_id:void 0}:h});return{retiredEntitlementIds:d,retiredPriceIds:m,items:f,curPrices:s.prices.filter(h=>!g.has(h.id)),curEnts:s.entitlements.filter(h=>!g.has(h.id))}}}))(Zw,Kg,su,Hg),{ProductItemSchema:eC}=((e,t,n,r,i,a,o,s,c,l,u)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(m=>{if(m==="")throw new Error("Interval cannot be empty.");return m},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(l).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:u.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(Ie,RI,On,pA,Qi,Qc,Zr,Yw,Bw,wo,Jw),{validateProductItem:tC}=((e,t,n,r,i,a,o,s,c,l,u,d,m,g,f,h,x,I,S,T)=>({validateProductItem:({item:P,features:be,multiCurrencyEnabled:nt,validateRollover:We})=>{P=e.parse(P);let Ne=be.find(pe=>pe.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 ce=P.pooled&&Ne?.type===a.Boolean,V=o(P)||s(P.included_usage)&&P.included_usage!==0||s(P.interval)||s(P.config?.rollover);if(ce&&V)throw new n({message:"Pooled boolean items cannot include balance or pricing fields",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(c({item:P,feature:Ne,features:be}),o(P)&&P.included_usage===l)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(P.pooled&&o(P)&&P.usage_model===u.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 Fe=(P.additional_currencies?.length??0)>0||(P.tiers?.some(pe=>(pe.additional_currencies?.length??0)>0)??!1);if(Fe&&!nt)throw new n({message:"Multi-currency is not enabled for this organization",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(Fe&&t(P.base_currency))throw new n({message:"'base_currency' is required when 'additional_currencies' are set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if((P.additional_currencies?.length??0)>0){if(s(P.tiers))throw new n({message:"Tiered items carry 'additional_currencies' on each tier, not at the item level",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(P.price)&&P.price<=0)throw new n({message:"'additional_currencies' require a non-zero 'price' \u2014 a plan that is free in the base currency is free in every currency",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST})}if(d(P)&&P.price&&P.price.toString().split(".")[1]?.length>2)throw new n({message:"One off prices can have at most 2 decimal places",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(P)||m(P)){if(typeof P.included_usage!="number"&&P.included_usage!==l&&s(P.included_usage))throw new n({message:`Included usage for feature ${P.feature_id} must be a number or '${l}'`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(t(P.included_usage)&&(P.included_usage=0),typeof P.included_usage=="number"&&P.included_usage<0)throw new n({message:"Included usage must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(P)||d(P)){let pe=g({item:P});if(String(pe)===f.Day||String(pe)===f.Minute||String(pe)===f.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(P)&&t(P.usage_model))throw new n({message:`Usage model is required for priced features. Please select one for the feature ${P.feature_id}`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(P)&&P.tiers){if(P.included_usage===l)throw new n({message:`Included usage can't be '${l}' 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!==u.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(se=>se.flat_amount!=null&&se.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(se=>se.flat_amount!=null&&se.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===u.Prepaid&&P.config?.on_increase===x.BillImmediately)throw new n({message:"Bill immediately is not supported for prepaid just yet, contact us at hey@useautumn.com if you're interested!",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(P.config?.expiry&&Ne&&(Ne.type===a.Boolean||I({feature:Ne})))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),!We)return;if(P.included_usage===l)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let dt=T({rollover:Q});if(dt)throw new n({message:dt,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})}}))(eC,Qt,Dt,Vt,Kn,wt,Yc,hr,qw,Qi,Zr,Xc,Co,zn,Qc,wo,Xr,Eg,Zc,QI),{validateProductItems:nC}=((e,t,n,r,i,a,o,s,c,l,u,d,m,g,f)=>({validateProductItems:({newItems:x,features:I,orgId:S,env:T,multiCurrencyEnabled:D,validateRollover:P=!0})=>{let{allFeatures:be,newFeatures:nt}=e({items:x,curFeatures:I,orgId:S,env:T});I=be;for(let ce=0;ce<x.length;ce++){t({item:x[ce],features:I,multiCurrencyEnabled:D,validateRollover:P});let V=I.find(Fe=>Fe.id===x[ce].feature_id);V&&V.type===n.Metered&&(x[ce].feature_type=V.config?.usage_type)}for(let ce=0;ce<x.length;ce++){let V=x[ce],Fe=r({item:V}),Q=i({item:V});if(a(V)&&x.find((se,$t)=>se.feature_id===V.feature_id&&$t!==ce&&V.entity_feature_id===se.entity_feature_id))throw new o({message:`Feature ${V.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let dt=x.find((pe,se)=>pe.feature_id===V.feature_id&&se!==ce&&r({item:pe})===Fe&&i({item:pe})===Q&&pe.entity_feature_id===V.entity_feature_id);if(dt){if(l(dt)&&l(V))throw new o({message:`You're trying to create two items for the same feature (${V.feature_id}) with the same interval. Please make them into one item.`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(V.usage_model&&V.usage_model===dt?.usage_model)throw new o({message:`You're trying to add the same feature (${V.feature_id}), with the same reset interval. You should either change the reset interval of one of the items, or make one of them a prepaid quantity`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(u(V)&&x.find((se,$t)=>d({item:se})===d({item:V})&&m({item:se})===m({item:V})&&$t!==ce))throw new o({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let We=x.some(ce=>(u(ce)||g(ce))&&String(d({item:ce}))===f.Week),Ne=x.some(ce=>(u(ce)||g(ce))&&String(d({item:ce}))===f.Month);if(We&&Ne)throw new o({message:"Can't have both weekly and monthly price items in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(x.filter(u).length>1)throw new o({message:"Can't have more than one price item in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});return{allFeatures:be,newFeatures:nt}}}))(tw,tC,wt,Po,Oo,Tg,Dt,Vt,Kn,Co,Xc,zn,ei,Yc,Qc),{handleNewProductItems:rM}=((e,t,n,r,i)=>({handleNewProductItems:async({db:o,curPrices:s,curEnts:c,newItems:l,features:u,product:d,logger:m,isCustom:g,newVersion:f,saveToDb:h=!0,multiCurrencyEnabled:x})=>{if(!l)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:u};let{allFeatures:I,newFeatures:S}=e({newItems:l,features:u,orgId:d.org_id,env:d.env,multiCurrencyEnabled:x,validateRollover:!g});u=I;let T=[],D=[],P=[],be=[],nt=s.filter(V=>{let Fe=l.find(Q=>Q.price_id===V.id);return Fe?t(Fe):!0}),We=c.filter(V=>!l.some(Fe=>Fe.entitlement_id===V.id)),Ne=[],ce=[];for(let V of l){let Fe=u.find(Zt=>Zt.id===V.feature_id),Q=c.find(Zt=>Zt.id===V.entitlement_id),dt=s.find(Zt=>Zt.id===V.price_id),{newPrice:pe,newEnt:se,updatedPrice:$t,updatedEnt:ze,samePrice:Gt,sameEnt:En}=n({item:V,orgId:d.org_id,internalProductId:d.internal_id,feature:Fe,curPrice:dt,curEnt:Q,isCustom:g,newVersion:f,features:u});pe&&T.push(pe),se&&D.push(se),$t&&P.push($t),ze&&be.push(ze),Gt&&Ne.push(Gt),En&&ce.push(En)}return r({targetPrices:[...T,...P],targetEntitlements:[...D,...be,...ce],candidatePrices:s,candidateEntitlements:c}),(g||f)&&h?{...i({newPrices:T,newEnts:D,updatedPrices:P,updatedEnts:be,samePrices:Ne,sameEnts:ce,features:u}),samePrices:Ne,sameEnts:ce,newFeatures:S,retiredPriceIds:nt.map(V=>V.id),retiredEntitlementIds:We.map(V=>V.id)}:{prices:[...T,...P],entitlements:[...D,...be].map(V=>({...V,feature:u.find(Fe=>Fe.id===V.feature_id)})),customPrices:[],customEnts:[],features:u,samePrices:Ne,sameEnts:ce,newFeatures:S,retiredPriceIds:nt.map(V=>V.id),retiredEntitlementIds:We.map(V=>V.id)}}}))(nC,Eo,zw,Xw,y1);var rC=un.clone({precision:40});function lu(e){if(!ou(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function du(e){let t=new rC(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function sM(e,t){let n=lu(t),i=du(e).toDecimalPlaces(Ag(n),un.ROUND_HALF_CEIL).mul(To(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 cM(e,t){let n=lu(t),r=du(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(To(n)).toString()}function uM(e,t){let n=du(e).mul(To(lu(t)));if(n.isNegative())throw new Error("Usage unit price must be nonnegative");if(n.decimalPlaces()>12||n.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Usage unit amount cannot be represented exactly by the provider");return n.toFixed()}export{zb as a,pl as b,es as c,hl as d,ma as e,Yb as f,ts as g,Jb as h,bl as i,ns as j,IC as k,Xb as l,_l as m,AC as n,yl as o,wC as p,ci as q,is as r,pa as s,Tn as t,z as u,Zn as v,kC as w,TC as x,xl as y,DC as z,vl as A,n_ as B,r_ as C,FC as D,as as E,ct as F,Y as G,fa as H,Yt as I,Ye as J,Pl as K,a_ as L,o_ as M,s_ as N,$C as O,ss as P,cs as Q,us as R,c_ as S,u_ as T,Ol as U,l_ as V,ZC as W,ds as X,Ue as Y,dn as Z,oP as _,El as $,sP as aa,kl as ba,d_ as ca,Tl as da,cP as ea,uP as fa,m_ as ga,Rl as ha,ms as ia,lP as ja,dP as ka,Yn as la,Vl as ma,Ft as na,Kl as oa,Hl as pa,Oe as qa,Jt as ra,yt as sa,Sa as ta,mi as ua,k_ as va,R_ as wa,j_ as xa,Xl as ya,N_ as za,vr as Aa,MP as Ba,ed as Ca,BP as Da,D_ as Ea,F_ as Fa,U_ as Ga,LP as Ha,qP as Ia,xn as Ja,Xn as Ka,xa as La,L_ as Ma,GP as Na,zP as Oa,q_ as Pa,V_ as Qa,id as Ra,eO as Sa,Ir as Ta,Xt as Ua,ad as Va,$_ as Wa,od as Xa,tO as Ya,nO as Za,rO as _a,iO as $a,aO as ab,oO as bb,ks as cb,va as db,dd as eb,pi as fb,Ar as gb,K_ as hb,H_ as ib,W_ as jb,z_ as kb,jn as lb,md as mb,pd as nb,fd as ob,gd as pb,Ia as qb,hd as rb,bd as sb,_d as tb,yd as ub,Z_ as vb,Sd as wb,Y_ as xb,J_ as yb,X_ as zb,xd as Ab,Ts as Bb,ey as Cb,gi as Db,vd as Eb,Id as Fb,Ad as Gb,ty as Hb,wd as Ib,Cd as Jb,bi as Kb,_i as Lb,tr as Mb,Aa as Nb,js as Ob,ny as Pb,Od as Qb,Ed as Rb,yi as Sb,wa as Tb,kd as Ub,wO as Vb,CO as Wb,PO as Xb,OO as Yb,ry as Zb,EO as _b,kO as $b,Ds as ac,NO as bc,DO as cc,iy as dc,ay as ec,oy as fc,sy as gc,BO as hc,LO as ic,qO as jc,Td as kc,Fs as lc,QO as mc,ZO as nc,cy as oc,eE as pc,tE as qc,Ca as rc,Ii as sc,Us as tc,rr as uc,Dd as vc,Pa as wc,Fd as xc,Ai as yc,uy as zc,Bd as Ac,Ms as Bc,Ld as Cc,qd as Dc,Vd as Ec,ly as Fc,$d as Gc,Bs as Hc,Gd as Ic,bE as Jc,Kd as Kc,_E as Lc,yE as Mc,Oa as Nc,Hd as Oc,wi as Pc,Qe as Qc,Wd as Rc,zd as Sc,Ea as Tc,Qd as Uc,gy as Vc,Zd as Wc,Jd as Xc,Xd as Yc,Vs as Zc,hy as _c,em as $c,jE as ad,tm as bd,nm as cd,FE as dd,UE as ed,by as fd,_y as gd,Fn as hd,rm as id,yy as jd,Sy as kd,$s as ld,om as md,or as nd,vy as od,Iy as pd,cm as qd,Oi as rd,Pr as sd,ka as td,um as ud,lm as vd,Ks as wd,Ay as xd,wy as yd,Cy as zd,dm as Ad,Hs as Bd,mm as Cd,pm as Dd,fm as Ed,Ta as Fd,ek as Gd,tk as Hd,gm as Id,Ra as Jd,Py as Kd,ki as Ld,ja as Md,hm as Nd,Ey as Od,zs as Pd,sk as Qd,_m as Rd,ym as Sd,ky as Td,Qs as Ud,xm as Vd,vm as Wd,Da as Xd,Fa as Yd,Ty as Zd,Ry as _d,jy as $d,Im as ae,Am as be,wm as ce,Cm as de,Pm as ee,Om as fe,Em as ge,km as he,Or as ie,Un as je,Tm as ke,Dy as le,Ys as me,sr as ne,Ok as oe,ec as pe,Fy as qe,Uy as re,Ti as se,My as te,Ly as ue,qy as ve,Ri as we,Tk as xe,Ua as ye,Xs as ze,Vy as Ae,jm as Be,Nm as Ce,$y as De,Rk as Ee,jk as Fe,Dm as Ge,Gy as He,Nk as Ie,Ky as Je,Er as Ke,Ba as Le,La as Me,Um as Ne,$k as Oe,Mm as Pe,Tr as Qe,Bm as Re,Hy as Se,tc as Te,Lm as Ue,qa as Ve,Va as We,$a as Xe,Qk as Ye,Zk as Ze,Wy as _e,qm as $e,Vm as af,Qy as bf,Gm as cf,eT as df,Km as ef,nc as ff,Hm as gf,rT as hf,Zy as if,rn as jf,Ni as kf,Be as lf,Yy as mf,Jy as nf,ic as of,Wm as pf,Di as qf,zm as rf,Xy as sf,eS as tf,Zm as uf,tS as vf,nS as wf,rS as xf,iS as yf,aS as zf,cr as Af,oS as Bf,sS as Cf,cS as Df,uS as Ef,lS as Ff,dS as Gf,mS as Hf,pS as If,fS as Jf,gS as Kf,hS as Lf,bS as Mf,Ym as Nf,_S as Of,SS as Pf,xS as Qf,ac as Rf,mT as Sf,vS as Tf,pT as Uf,Ct as Vf,fT as Wf,kt as Xf,pn as Yf,oc as Zf,AS as _f,Rr as $f,gT as ag,PS as bg,sc as cg,hT as dg,OS as eg,Fi as fg,bT as gg,_T as hg,Jm as ig,An as jg,kS as kg,Ga as lg,Ka as mg,jS as ng,NS as og,DS as pg,ET as qg,kT as rg,TT as sg,Xm as tg,Ha as ug,tp as vg,cc as wg,np as xg,rp as yg,ip as zg,op as Ag,ap as Bg,uc as Cg,FS as Dg,zT as Eg,US as Fg,sp as Gg,MS as Hg,mr as Ig,cp as Jg,lp as Kg,dp as Lg,mp as Mg,pp as Ng,fp as Og,BS as Pg,gp as Qg,LS as Rg,qS as Sg,VS as Tg,$S as Ug,_p as Vg,mc as Wg,Sp as Xg,GS as Yg,KS as Zg,cR as _g,uR as $g,lR as ah,vp as bh,Ip as ch,Ap as dh,wp as eh,Cp as fh,Pp as gh,dR as hh,mR as ih,WS as jh,zS as kh,pR as lh,fR as mh,pc as nh,Nr as oh,Qa as ph,Ep as qh,Dr as rh,Fr as sh,pr as th,fr as uh,Ur as vh,kp as wh,QS as xh,ZS as yh,fc as zh,Tp as Ah,Rp as Bh,jp as Ch,YS as Dh,JR as Eh,B as Fh,JS as Gh,XS as Hh,e0 as Ih,XR as Jh,ej as Kh,M as Lh,tj as Mh,et as Nh,rj as Oh,Up as Ph,Fp as Qh,Ya as Rh,aj as Sh,Mp as Th,dj as Uh,n0 as Vh,r0 as Wh,mj as Xh,pj as Yh,Bp as Zh,i0 as _h,hj as $h,a0 as ai,Lp as bi,qp as ci,o0 as di,bj as ei,_j as fi,yj as gi,Sj as hi,s0 as ii,Ij as ji,Aj as ki,Pj as li,Oj as mi,$p as ni,Rj as oi,jj as pi,Br as qi,Gp as ri,hc as si,qi as ti,Xa as ui,Vi as vi,an as wi,Lj as xi,_c as yi,qj as zi,to as Ai,Sc as Bi,m0 as Ci,Hp as Di,Wp as Ei,Wj as Fi,zj as Gi,Qj as Hi,Zj as Ii,Yj as Ji,Jj as Ki,p0 as Li,Xj as Mi,xc as Ni,f0 as Oi,vc as Pi,a2 as Qi,o2 as Ri,s2 as Si,g0 as Ti,h0 as Ui,zp as Vi,p2 as Wi,S0 as Xi,Ic as Yi,Ac as Zi,Lr as _i,x0 as $i,v0 as aj,C2 as bj,Qp as cj,D2 as dj,Cc as ej,Pc as fj,F2 as gj,U2 as hj,M2 as ij,B2 as jj,I0 as kj,Zp as lj,Lt as mj,Xp as nj,ef as oj,Yp as pj,A0 as qj,w0 as rj,$i as sj,C0 as tj,Tc as uj,O0 as vj,uN as wj,lN as xj,dN as yj,Rc as zj,E0 as Aj,k0 as Bj,jc as Cj,tf as Dj,PN as Ej,nf as Fj,DN as Gj,FN as Hj,af as Ij,D0 as Jj,F0 as Kj,U0 as Lj,Gi as Mj,cf as Nj,M0 as Oj,B0 as Pj,ZN as Qj,lf as Rj,L0 as Sj,Dc as Tj,Fc as Uj,Uc as Vj,q0 as Wj,V0 as Xj,uD as Yj,lD as Zj,dD as _j,mD as $j,gD as ak,_D as bk,mf as ck,vD as dk,ID as ek,$0 as fk,G0 as gk,K0 as hk,H0 as ik,W0 as jk,z0 as kk,PD as lk,Q0 as mk,OD as nk,ED as ok,jD as pk,Z0 as qk,Y0 as rk,oo as sk,J0 as tk,X0 as uk,FD as vk,qD as wk,VD as xk,$D as yk,ex as zk,GD as Ak,zD as Bk,QD as Ck,gx as Dk,hx as Ek,bx as Fk,cF as Gk,wf as Hk,_x as Ik,dF as Jk,Cf as Kk,hF as Lk,bF as Mk,vF as Nk,IF as Ok,yx as Pk,PF as Qk,OF as Rk,Pf as Sk,Of as Tk,DF as Uk,FF as Vk,xx as Wk,KF as Xk,vx as Yk,HF as Zk,Ix as _k,zF as $k,kf as al,QF as bl,ZF as cl,Tf as dl,Rf as el,tU as fl,nU as gl,Nf as hl,Df as il,sU as jl,cU as kl,uU as ll,lU as ml,jf as nl,dU as ol,Ax as pl,fU as ql,bU as rl,Cx as sl,Uf as tl,_U as ul,SU as vl,xU as wl,sM as xl,cM as yl,uM as zl};
|