@tinkerlandai/indiana-sdk 0.6.0 → 0.6.2
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 +15 -1
- package/README.md +17 -11
- package/README.zh-CN.md +21 -16
- package/dist/{chunk-OK2Q6IJD.js → chunk-ET4NANGB.js} +1 -1
- package/dist/{chunk-5WY3AXSS.js → chunk-J7M7UH74.js} +1 -1
- package/dist/{chunk-PCVQHHEE.js → chunk-M3DG6ZCT.js} +1 -1
- package/dist/chunk-N6UIDDAX.js +4 -0
- package/dist/chunk-VMLGV5OS.js +11 -0
- package/dist/funnel-runtime-host-3STQUS6F.js +1 -0
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +2 -1
- package/dist/page.js +1 -1
- package/dist/{paywall-TCE5DE5T.js → paywall-LBDMGVWZ.js} +1 -1
- package/dist/popup.d.ts +10 -6
- package/dist/popup.js +176 -6
- package/dist/server.js +1 -1
- package/dist/src-X6KT6WIH.js +1 -0
- package/dist/visual.js +1 -1
- package/package.json +10 -9
- package/dist/chunk-4JBIKJMU.js +0 -4
- package/dist/chunk-HU2HIDVT.js +0 -11
- package/dist/funnel-runtime-host-L3WILUHK.js +0 -1
- package/dist/src-VGIVVM27.js +0 -1
package/dist/chunk-HU2HIDVT.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{$ as hu,Ca as Au,Db as Oo,Ea as wu,Gb as Cu,L as Yr,M as cu,N as uu,Pb as Ji,Q as lu,Qb as $n,R as Jr,Rb as qt,S as du,T as pu,Tb as Eo,U as Co,V as Tt,W as mu,Z as fu,a as Vn,b as ae,ba as gu,c as Vi,ea as Zi,f as ru,fa as ur,g as xt,ga as bu,h as ge,i as Ao,ia as _u,j as $i,ja as Xr,k as Zt,la as yu,ma as Su,oa as vu,pb as Pu,q as mn,r as Qi,s as su,sa as xu,ta as lr,tb as Lt,ua as Iu,vb as It,wb as zr,zb as Yi}from"./chunk-RMJJOSVZ.js";import{a as iu,b as je,c as Ou,d as Eu,g as Tu,h as nn}from"./chunk-OHDY27EI.js";import{B as Hi,d as Gi,e as Wi,g as Ki,i as au,j as wo,l as Ie,m as Bt,n as xn,o as Po,p as cr,t as ou,v as Zr}from"./chunk-S2MSIA57.js";import{z as Jt}from"zod";import{z as A}from"zod/v4";import{z as tg}from"zod/v4";var Ru=tg.registry();var{AppEnv:Xi}=(()=>{var e;return(function(t){t.Sandbox="sandbox",t.Live="live"})(e||(e={})),{AppEnv:e}})(),{IGNORE_PAST_DUE_DESCRIPTION:ju}={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:ng}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{SpendLimitType:rg}=(e=>({SpendLimitType:e.enum(["absolute","usage_percentage"])}))(A),{ResetInterval:ei}=(()=>{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:ig}={USAGE_LIMIT_ANCHORS:["billing_cycle","utc"]},{USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:ag}={USAGE_LIMIT_FILTER_MAX_KEY_LENGTH:64},{USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:og}={USAGE_LIMIT_FILTER_MAX_VALUE_LENGTH:128},{USAGE_LIMIT_FILTER_MAX_KEYS:sg}={USAGE_LIMIT_FILTER_MAX_KEYS:4},{UsageAlertThresholdType:cg}=(e=>({UsageAlertThresholdType:e.enum(["usage","usage_percentage","remaining","remaining_percentage"])}))(A),{BALANCE_BASES:ug}={BALANCE_BASES:["balance","included","recurring"]},{DEFAULT_USAGE_ALERT_BASIS:ku}={DEFAULT_USAGE_ALERT_BASIS:"balance"},{DbOverageAllowedSchema:To}=(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:dr}=(e=>({ProductMetadataSchema:e.record(e.string(),e.any())}))(A),{findDuplicate:lg}={findDuplicate:t=>{let n=new Set;for(let r of t){if(n.has(r))return r;n.add(r)}}},{BillingInterval:In}=(()=>{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:Ro}=(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:ti}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Ru),{COMMON:Du}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:dg}={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:pg}=(e=>({COMMON_SET:new Set(e)}))(Du),{hasNoDuplicateCurrencies:Nu}={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:Fu}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{IncludedUsageParamsSchema:jo}=(e=>({IncludedUsageParamsSchema:e.number().max(1e13,{error:"Included usage cannot exceed 10 trillion; use unlimited usage instead"})}))(A),{Infinite:zi}={Infinite:"inf"},{TierBehavior:ni}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:ea}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Uu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{PLAN_ITEM_PRICE_DESCRIPTION:mg}={PLAN_ITEM_PRICE_DESCRIPTION:"Pricing for usage beyond included units. Omit for free features."},{OnIncrease:ta}=(()=>{var e;return(function(t){t.BillImmediately="bill_immediately",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.BillNextCycle="bill_next_cycle"})(e||(e={})),{OnIncrease:e}})(),{OnDecrease:na}=(()=>{var e;return(function(t){t.Prorate="prorate",t.ProrateImmediately="prorate_immediately",t.ProrateNextCycle="prorate_next_cycle",t.None="none",t.NoProrations="no_prorations"})(e||(e={})),{OnDecrease:e}})(),{RolloverExpiryDurationType:ko}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:Mu}=(()=>{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:fg}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:hg}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Do}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(A),{ApiCreditTierSchema:Bu}=(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:gg}={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:Lu}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(A),{ModelMarkupsSchema:No}=((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,Lu),{additionalCurrencyPlanItemIssues:qu}={additionalCurrencyPlanItemIssues:t=>{if(!t)return[];let n=[];t.additional_currencies&&t.additional_currencies.length>0&&(typeof t.amount!="number"||(t.tiers?.length??0)>0)&&n.push("price.additional_currencies requires a flat 'amount'; tiered prices carry per-currency amounts on each tier.");let r=t.tiers;if(r&&r.length>0){let i=o=>(o.additional_currencies??[]).map(s=>s.currency.toLowerCase()),a=new Set(r.flatMap(i));a.size>0&&(r.every(s=>{let c=new Set(i(s));return c.size===a.size&&[...a].every(u=>c.has(u))})||n.push("Each additional currency must be present on every tier or none."))}return n}},{PlanItemFilterSchema:Fo}=((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,ea,In,ei,jo),{UpdatePlanItemParamsV1Schema:bg}=((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,Fo,ei),{FreeTrialDuration:ri}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{laneParam:_g}=((e,t)=>({laneParam:({schema:r,description:i})=>e({schema:t.array(r).optional(),defaultValue:[],description:i})}))(ti,A),{findDuplicateInControls:yg}={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:Sg}={featureIdIdentity:t=>t.feature_id||void 0},{usageLimitFilterKey:Vu}={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:vg}=((e,t)=>({usageAlertIdentity:r=>[r.feature_id??"",r.basis??e,t(r.filter),r.threshold_type,r.threshold].join("|")}))(ku,Vu),{RemovePlanLicenseSchema:xg}=(e=>({RemovePlanLicenseSchema:e.object({license_plan_id:e.string()})}))(A),{ApiStripePriceProcessorSchema:Ig}=(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:Ag}=(()=>{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:wg}=(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:Pg}=(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:ra}={TrialOnEnd:["bill","revert"]},{EligibilityStatus:Cg}=(()=>{var e;return(function(t){t.Active="active",t.Scheduled="scheduled"})(e||(e={})),{EligibilityStatus:e}})(),{AttachAction:Og}=(()=>{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:Eg}=(()=>{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:Tg}=(e=>({UsageWindowDimensionSchema:e.enum(["balance","metered_feature"])}))(A),{UsageWindowScopeSchema:Rg}=(e=>({UsageWindowScopeSchema:e.enum(["customer","entity"])}))(A),{EntInterval:$u}=(()=>{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:jg}=(()=>{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:kg}=(e=>({FeatureStripeMeterSchema:e.object({id:e.string(),event_name:e.string()})}))(A),{FreeTrialSchema:Dg}=((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,ri,ra),{BillingType:Ng}=(()=>{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:Uo}=((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,zi),{IgnoredFixedPriceMetadataSchema:Fg}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(A),{BillWhen:Ug}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Gu}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProrationConfigSchema:Mg}=((e,t,n)=>({ProrationConfigSchema:e.object({on_increase:e.nativeEnum(t).default(t.ProrateImmediately),on_decrease:e.nativeEnum(n).default(n.ProrateImmediately)})}))(A,ta,na),{AllowanceType:Bg}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{RolloverConfigSchema:Wu}=((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,ko),{CreditDimensionBaseSchema:Lg}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(A,Do),{flatCreditRateShape:Ku}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(A),{CreditTierSchema:qg}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(A),{CreditMultiplierSchema:Vg}=((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,Do),{idRegex:ia}={idRegex:/^[a-zA-Z0-9_-]+$/},{descriptions:Hu}={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:$g}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ProductItemFeatureType:Gg}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{ProductItemInterval:Wg}=(()=>{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:Kg}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{TierInfinite:Hg}={TierInfinite:"inf"},{CreateFreeTrialSchema:Qu}=((e,t,n)=>({CreateFreeTrialSchema:e.object({length:e.string().or(e.number()).transform(i=>Number(i)).refine(i=>i>0,{message:"Free trial length must be greater than 0"}),unique_fingerprint:e.boolean().default(!1),duration:e.enum(t).default(t.Day),card_required:e.boolean().default(!0),on_end:e.enum(n).nullish()})}))(A,ri,ra),{ProductConfigParamsSchema:Mo}=((e,t,n)=>({ProductConfigParamsSchema:e.object({ignore_past_due:t({schema:e.boolean().optional(),defaultValue:!1,description:n})})}))(A,ti,ju),{CREATE_PRODUCT_EXAMPLE:Qg}={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:Zg}=((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,ri,ra),{CreateProductSchema:uP}=(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:Yg}={isUsageLimitBasisAlert:t=>t.basis==="usage_limit"},{PromoCodeSchema:Zu}=(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:Yu}=(()=>{var e;return(function(t){t.PercentageDiscount="percentage_discount",t.FixedDiscount="fixed_discount",t.FreeProduct="free_product",t.InvoiceCredits="invoice_credits",t.FeatureGrant="feature_grant"})(e||(e={})),{RewardType:e}})(),{CouponDurationType:Ju}=(()=>{var e;return(function(t){t.OneOff="one_off",t.Months="months",t.Forever="forever"})(e||(e={})),{CouponDurationType:e}})(),{FreeProductConfigSchema:Xu}=((e,t)=>({FreeProductConfigSchema:e.object({duration_type:e.nativeEnum(t),duration_value:e.number()})}))(A,Ju),{RewardTriggerEvent:Jg}=(()=>{var e;return(function(t){t.CustomerCreation="customer_creation",t.Checkout="checkout"})(e||(e={})),{RewardTriggerEvent:e}})(),{RewardReceivedBy:Xg}=(()=>{var e;return(function(t){t.Referrer="referrer",t.All="all"})(e||(e={})),{RewardReceivedBy:e}})(),{ProductConfigSchema:aa}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(A,ju),{PurchaseLimitIntervalEnum:zg}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(A,ng),{DbSpendLimitSchema:Bo}=((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,rg),{USAGE_LIMIT_INTERVALS:eb}=(e=>({USAGE_LIMIT_INTERVALS:[e.Day,e.Week,e.Month,e.Year]}))(ei),{UsageLimitAnchorSchema:zu}=((e,t)=>({UsageLimitAnchorSchema:e.enum(t)}))(A,ig),{UsageLimitFilterValueSchema:tb}=((e,t)=>({UsageLimitFilterValueSchema:e.union([e.string().min(1).max(t),e.number(),e.boolean()]).transform(String).pipe(e.string())}))(A,og),{USAGE_ALERT_BASES:nb}=(e=>({USAGE_ALERT_BASES:[...e,"usage_limit"]}))(ug),{licensePatchIssues:rb}=(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"]}]}}))(lg),{BasePriceSchema:ib}=((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,In,Ro),{CURRENCY_CODES:ab}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Du,dg,pg),{AllocatedBillingFieldSchema:el}=((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,Uu),{EntitlementExpirySchema:oa}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(A,Mu),{CreditDimensionNameSchema:tl}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(A,fg,hg),{ApiCreditMatchSchema:nl}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Do),{findCreditTierViolations:ob}=(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}}))(gg),{ApiCreditMultiplierSchema:sb}=((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,nl),{ProviderMarkupsSchema:rl}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(A,Lu),{planItemParamsIssues:cb}=((e,t,n,r,i)=>({planItemParamsIssues:o=>{let s=[],c=o.reset?.interval,u=o.price?.interval,l=o.reset?.interval_count??1,d=o.price?.interval_count??1;if(c&&u&&(String(c)!==String(u)||l!==d)&&o.price?.billing_method!==e.Prepaid&&s.push({message:"reset.interval and price.interval can only differ for prepaid prices.",input:o}),o.threshold_billing&&(!o.price||o.unlimited)&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing}),o.expiry&&(o.price?.billing_method===e.Prepaid&&String(o.price.interval)===String(t.OneOff)||s.push({message:"expiry is only supported on one-off prepaid items. Recurring items are already bounded by their reset cadence.",input:o.expiry}),o.entity_feature_id&&s.push({message:"expiry is not supported on entity-scoped items; each entity's balance would have to expire on its own clock.",input:o.expiry}),o.pooled&&s.push({message:"expiry is not supported on pooled items; pooled balances have no per-purchase lifetime.",input:o.expiry}),o.expiry.length<=0&&s.push({message:"expiry.length must be greater than 0",input:o.expiry})),o.price){o.threshold_billing&&o.price.billing_method!==e.UsageBased&&s.push({message:"threshold_billing requires a finite usage-based price",input:o.threshold_billing});let{amount:g,tiers:m}=o.price;o.threshold_billing&&m?.length&&s.push({message:"threshold_billing currently requires a flat usage price",input:o.threshold_billing});let h=o.price.billing_method===e.UsageBased&&o.price.allocated_billing===n.ProratedLegacy;o.proration&&o.price.billing_method!==e.Prepaid&&!h&&s.push({message:"proration is only supported for prepaid or legacy allocated prices.",input:o.proration});let y=typeof g=="number",w=Array.isArray(m)&&m.length>0;y||w?y&&w&&s.push({message:"'amount' and 'tiers' cannot both be defined in 'price'.",input:o.price}):s.push({message:"If 'price' is present, either 'amount' or 'tiers' must be defined.",input:o.price})}if(o.price?.tiers){let g=o.price.tiers.some(m=>m.flat_amount&&m.flat_amount>0);g&&o.price.tier_behavior!==r.VolumeBased&&s.push({message:"flat_amount on tiers is only supported for volume-based pricing.",input:o.price}),g&&o.price.tiers.length<=1&&s.push({message:"flat_amount is not supported on single-tier pricing.",input:o.price}),o.price.tiers.some(m=>m.flat_amount!=null&&m.flat_amount<0)&&s.push({message:"flat_amount must be 0 or greater.",input:o.price}),o.price?.tier_behavior===r.VolumeBased&&o.price?.billing_method!==e.Prepaid&&s.push({message:"volume-based pricing is only supported for prepaid features.",input:o.price}),o.price?.tiers.length===0?s.push({message:"tiers cannot be empty.",input:o.price}):o.included&&typeof o.price?.tiers[0].to=="number"&&o.price?.tiers[0].to<=o.included&&s.push({message:"tiers[0].to must be greater than included.",input:o.price})}for(let g of i(o.price))s.push({message:g,input:o.price});return s}}))(ea,In,Uu,ni,qu),{FreeTrialParamsV1Schema:Lo}=((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,ri,ti),{duplicateCheck:ub}=(e=>({duplicateCheck:({controlKey:n,...r})=>i=>e({controlKey:n,controls:i[n]??[],rule:r})}))(yg),{usageLimitIdentity:qo}=(e=>({usageLimitIdentity:n=>`${n.feature_id}|${e(n.filter)}`}))(Vu),{ApiPriceProcessorsSchema:il}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(A,Ig),{ApiFeatureV0Schema:al}=((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,Ag),{ApiRevenueCatPlanProcessorSchema:lb}=((e,t)=>({ApiRevenueCatPlanProcessorSchema:e.object({products:e.array(t).meta({description:"Every RevenueCat product that maps to this plan. Replaces the current set."})})}))(A,Pg),{ApiFreeTrialV2Schema:db}=((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,ri,ra),{CustomerEligibilitySchema:pb}=((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,Cg,Og,Eg),{UsageWindowLimitSchema:lP}=((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,Tg,Rg,$u,zu),{FeatureSchema:mb}=((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,jg,No,kg),{PriceCurrencyConfigSchema:ol}=((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,Uo),{UsagePriceConfigSchema:fb}=((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,Ug,Uo,In,ol,Gu),{graduatedCreditRateShape:sl}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(A,qg),{FeatureMarkupsOverrideSchema:hb}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(A,rl,No),{usageAlertTargetLimitIdentity:gb}=(e=>({usageAlertTargetLimitIdentity:n=>e({feature_id:n.feature_id??"",filter:n.filter})}))(qo),{DiscountConfigSchema:cl}=((e,t)=>({DiscountConfigSchema:e.object({discount_value:e.number(),duration_type:e.nativeEnum(t),duration_value:e.number(),should_rollover:e.boolean().optional(),apply_to_all:e.boolean().optional(),price_ids:e.array(e.string()).optional(),product_ids:e.array(e.string()).optional()})}))(A,Ju),{RewardEntitlementSchema:ul}=((e,t)=>({RewardEntitlementSchema:e.object({internal_feature_id:e.string().min(1),allowance:e.number().nonnegative().optional(),expiry:t.optional()})}))(A,oa),{UpdateRewardSchema:dP}=((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,Zu,Yu,cl,Xu,ul),{CreateRewardProgram:pP}=((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,Jg,Xg),{AutoTopupPurchaseLimitSchema:ll}=((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,zg),{UsageLimitFilterSchema:dl}=((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,ag,tb,sg),{UsageAlertBasisSchema:bb}=((e,t)=>({UsageAlertBasisSchema:e.enum(t)}))(A,nb),{refineCustomizePlanV1Schema:pl}=(e=>({refineCustomizePlanV1Schema:(n,{includeItems:r=!0,includeFreeTrial:i=!0,includeUpdateItems:a=!0,includeLicenses:o=!0}={})=>{let s=["price",r&&"items","add_items","remove_items",a&&"update_items",i&&"free_trial","billing_controls",o&&"upsert_licenses",o&&"remove_licenses"].filter(Boolean),c=u=>u==="update_items"?"deprecated update_items":u;return n.refine(u=>s.some(l=>u[l]!==void 0),{message:`When using customize, at least one of ${s.map(c).join(", ")} must be provided`}).superRefine((u,l)=>{if(o)for(let d of e({upsertLicenses:u.upsert_licenses}))l.addIssue({code:"custom",...d})}).refine(u=>!(u.items!==void 0&&(u.add_items!==void 0||u.remove_items!==void 0||a&&u.update_items!==void 0)),{message:`customize.items (PUT-style) cannot be combined with ${["add_items","remove_items",a?"deprecated update_items":null].filter(Boolean).join(" / ")} (PATCH-style); pick one approach`})}}))(rb),{SUPPORTED_SET:_b}=(e=>({SUPPORTED_SET:new Set(e)}))(ab),{ApiCreditDimensionBaseSchema:yb}=((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,nl),{refineGraduatedTiers:ml}=(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"]})}}))(ob),{ApiFeatureMarkupsOverrideSchema:Sb}=((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,rl,No),{AutoTopupPurchaseLimitParamsSchema:vb}=((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."})})}))(ll,A),{DUPLICATE_CHECKS:xb}=((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"})]}))(ub,Sg,qo,vg),{ApiPlanProcessorsSchema:Ib}=((e,t,n)=>({ApiPlanProcessorsSchema:e.object({stripe:t.nullish(),revenuecat:n.nullish()}).meta({"x-atmn-mapping":!0})}))(A,wg,lb),{FixedPriceConfigSchema:Ab}=((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,In,ol,Uo,Fg),{CreditDimensionSchema:wb}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(A,Lg,Ku,sl),{filterUnresolvableUsageLimitAlerts:Pb}=((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}]:[])}}))(qo,Yg,gb),{CreateRewardSchema:mP}=((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,Zu,Yu,cl,Xu,ul),{AutoTopupSchema:Vo}=((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,ll),{DbUsageLimitSchema:$o}=((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,eb,zu,dl),{DbUsageAlertSchema:Go}=((e,t,n,r,i)=>({DbUsageAlertSchema:e.object({feature_id:e.string().optional().meta({description:"The feature ID this alert applies to."}),enabled:e.boolean().default(!0).meta({description:"Whether this usage alert is enabled."}),threshold:e.number().min(0).meta({description:"The threshold value that triggers the alert. For usage or remaining, this is an absolute count. For usage_percentage or remaining_percentage, this is a percentage (0-100)."}),threshold_type:t.meta({description:"Whether the threshold is an absolute count or a percentage of the usage allowance or remaining balance."}),basis:n.default(r).meta({description:"What 100% means. balance: every grant on the feature. included: the plan allowance only. recurring: grants that reset. usage_limit: the cap of the usage limit with the same feature and filter."}),filter:i.optional().meta({description:"Only valid with basis usage_limit. Points the alert at the usage limit carrying the same filter."}),name:e.string().optional().meta({description:"Optional user-defined label to distinguish multiple alerts on the same feature."})}).check(o=>{let{feature_id:s,threshold_type:c,threshold:u,basis:l,filter:d}=o.value;c==="remaining_percentage"&&u>100&&o.issues.push({code:"custom",input:u,path:["threshold"],message:"Threshold must be between 0 and 100 for remaining_percentage"}),l==="usage_limit"&&!s&&o.issues.push({code:"custom",input:s,path:["feature_id"],message:"feature_id is required when basis is usage_limit"}),d&&l!=="usage_limit"&&o.issues.push({code:"custom",input:d,path:["filter"],message:"filter is only valid when basis is usage_limit"})})}))(A,cg,bb,ku,dl),{isValidCurrencyCode:Cb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(_b),{ApiCreditDimensionSchema:Ob}=((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,yb,Bu,ml),{AutoTopupParamsSchema:Eb}=((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."})})}))(Vo,vb),{findDuplicateBillingControlIssue:Tb}=(e=>({findDuplicateBillingControlIssue:n=>{for(let r of e){let i=r(n);if(i)return i}}}))(xb),{CustomerBillingControlsSchema:Wo}=((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,Vo,Bo,$o,Go,To),{PriceSchema:Rb}=((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,Ng,ni,Ab,fb,Mg),{CreditSchemaItemBaseSchema:fl}=((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,tl,wb,Vg),{GraduatedCreditSchemaItemSchema:jb}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(fl,sl),{UpdateProductSchema:fP}=((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,aa,Wo),{DbBillingControlsSchema:kb}=((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,Vo,Bo,$o,Go,To),{CurrencyCodeSchema:hl}=((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,Cb),{AdditionalCurrencyTierSchema:Db}=((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,hl),{ApiCreditSchemaItemBaseSchema:gl}=((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,tl,Ob,sb),{ApiFlatCreditSchemaItemSchema:Nb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(gl,A),{rejectDuplicateBillingControls:Fb}=(e=>({rejectDuplicateBillingControls:n=>{let r=e(n.value);r&&n.issues.push(r)}}))(Tb),{FlatCreditSchemaItemSchema:Ub}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(fl,Ku),{ProductSchema:Mb}=((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,aa,kb,dr),{AdditionalCurrencyPriceSchema:Bb}=((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,hl),{AdditionalCurrencyTierArraySchema:bl}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(A,Db,Nu,Fu),{ApiGraduatedCreditSchemaItemSchema:Lb}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(gl,A,Bu,ml),{CustomerBillingControlsParamsSchema:sa}=((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,_g,Eb,Bo,$o,Go,To,Fb),{CreditSchemaItemSchema:qb}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(A,Ub,jb),{PriceTierSchema:Vb}=((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,Hg,bl),{PlanBillingControlsParamsSchema:$b}=((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"]})})}))(sa,Pb),{AdditionalCurrencyPriceArraySchema:ii}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(A,Bb,Nu,Fu),{ApiUsageTierWithCurrenciesSchema:_l}=((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,zi,bl),{ApiCreditSchemaItemSchema:Gb}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(A,Lb,Nb),{FeatureConfigOverrideSchema:yl}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(A,qb,hb),{ProductItemConfigSchema:Wb}=((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,Gu,ta,na,Wu,oa,yl),{BasePriceParamsSchema:ca}=((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."})}))(ib,ti,A,ii),{PlanItemPriceParamsSchema:Kb}=((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,ii,_l,ni,In,ea,el),{ApiFeatureOverrideSchema:Sl}=((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,Gb,Sb),{ApiPlanItemV1Schema:Hb}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m,h,y)=>({ApiPlanItemV1Schema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature this item configures."}),feature:t.optional().meta({description:"The full feature object if expanded."}),included:e.number().meta({description:"Number of free units included. For consumable features, balance resets to this number each interval."}),unlimited:e.boolean().meta({description:"Whether the customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"The interval at which the feature balance resets (e.g. 'month', 'year'). For consumable features, usage resets to 0 and included units are restored."}),interval_count:e.number().optional().meta({description:"Number of intervals between resets. Defaults to 1."})}).nullable().meta({description:"Reset configuration for consumable features. Null for non-consumable features like seats where usage persists across billing cycles."}),price:e.object({amount:e.number().optional().meta({description:"Price per billing_units after included usage is consumed. Mutually exclusive with tiers."}),additional_currencies:r.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers' (tiered prices carry per-currency amounts on each tier)."}),tiers:e.array(i).optional().meta({description:"Tiered pricing configuration. Each tier's 'to' INCLUDES the included amount. Either 'tiers' or 'amount' is required."}),tier_behavior:e.enum(a).optional(),interval:e.enum(o).meta({description:"Billing interval for this price. For consumable features, should match reset.interval."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().meta({description:"Number of units per price increment. Usage is rounded UP to the nearest billing_units when billed (e.g. billing_units=100 means 101 usage rounds to 200)."}),billing_method:e.enum(s).meta({description:"'prepaid' for features like seats where customers pay upfront, 'usage_based' for pay-as-you-go after included usage."}),allocated_billing:c,max_purchase:e.number().nullable().meta({description:"Maximum units a customer can purchase beyond included. E.g. if included=100 and max_purchase=300, customer can use up to 400 total before usage is capped. Null for no limit."}),processors:u.optional().meta({description:"Payment processors this item price is connected to. Omitted when unset."})}).nullable().meta({description:"Pricing configuration for usage beyond included units. Null if feature is entirely free."}),display:l.optional().meta({description:"Display text for showing this item in pricing pages."}),rollover:e.object({max:e.number().nullable().meta({description:"Maximum rollover units. Null for unlimited rollover."}),max_percentage:e.number().nullable().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(d).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover configuration for unused units. If set, unused included units roll over to the next period."}),proration:e.object({on_increase:e.enum(p).optional().meta({description:"How to handle billing when quantity increases mid-cycle."}),on_decrease:e.enum(g).optional().meta({description:"How to handle credits when quantity decreases mid-cycle."})}).optional().meta({internal:!0}),expiry:m.nullish().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:h.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),mapping_identity:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})}).check(x=>{let k=x.value.reset?.interval,I=x.value.price?.interval,v=x.value.reset?.interval_count??1,K=x.value.price?.interval_count??1;if(k&&I&&(String(k)!==String(I)||v!==K)&&x.value.price?.billing_method!==s.Prepaid&&x.issues.push({code:"custom",message:"reset.interval and price.interval can only differ for prepaid prices.",input:x.value}),x.value!==void 0&&x.value.price!==void 0&&x.value.price!==null){x.value.price.amount&&x.value.price.tiers&&x.value.price.tiers.length>0&&x.issues.push({code:"custom",message:"Price amount and tiers are mutually exclusive.",input:x.value});for(let we of y(x.value.price))x.issues.push({code:"custom",message:we,input:x.value.price})}})}))(A,al,ei,ii,_l,ni,In,ea,el,il,Ro,ko,ta,na,oa,Sl,qu),{EntitlementSchema:Qb}=((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,Bg,$u,Mu,Wu,yl),{ProductItemSchema:vl}=((e,t,n,r,i,a,o,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(A,$g,Gg,al,zi,Wg,Kg,Vb,ii,ni,Wb),{ProductV2Schema:xl}=((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,Zg,vl,aa,Wo,dr),{PlanItemParamsObjectSchema:Zb}=((e,t,n,r,i,a,o,s,c,u,l)=>({PlanItemParamsObjectSchema:e.object({threshold_billing:e.object({threshold:e.number().finite().positive()}).nullish().meta({description:"Bills this many feature units when outstanding overage reaches it."}),feature_id:e.string().meta({description:"The ID of the feature to configure."}),included:t.optional().meta({description:"Number of free units included. Balance resets to this each interval for consumable features."}),unlimited:e.boolean().optional().meta({description:"If true, customer has unlimited access to this feature."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),reset:e.object({interval:e.enum(n).meta({description:"Interval at which balance resets (e.g. 'month', 'year'). For consumable features only."}),interval_count:r({schema:e.number().optional(),defaultValue:1,description:"Number of intervals between resets. Defaults to 1."})}).optional().meta({description:"Reset configuration for consumable features. Omit for non-consumable features like seats."}),price:i.optional().meta({description:a}),proration:e.object({on_increase:e.enum(o).meta({description:"Billing behavior when quantity increases mid-cycle."}),on_decrease:e.enum(s).meta({description:"Credit behavior when quantity decreases mid-cycle."})}).optional().meta({description:"Proration settings for prepaid features. Controls mid-cycle quantity change billing."}),rollover:e.object({max:e.number().optional().meta({description:"Max rollover units. Omit for unlimited rollover."}),max_percentage:e.number().optional().meta({description:"Maximum rollover as a percentage (0-100) of included + prepaid grant. Mutually exclusive with max."}),expiry_duration_type:e.enum(c).meta({description:"When rolled over units expire."}),expiry_duration_length:e.number().optional().meta({description:"Number of periods before expiry."})}).optional().meta({description:"Rollover config for unused units. If set, unused included units carry over."}),expiry:u.optional().meta({description:"Purchased units expire this long after each purchase. One-off prepaid consumable items only."}),feature_override:l.optional().meta({description:"Overrides fields of this item's feature for customers on this plan (e.g. a credit system's credit_schema)."}),entity_feature_id:e.string().optional().meta({internal:!0}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0})})}))(A,jo,ei,ti,Kb,mg,ta,na,ko,oa,Sl),{FullProductWithoutLicensesSchema:hP}=((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()})}))(Mb,A,Rb,Qb,mb,Dg),{CreateProductItemParamsSchema:Il}=((e,t,n,r)=>({CreateProductItemParamsSchema:e.extend({included_usage:t.or(n.literal(r)).nullish()})}))(vl,jo,A,zi),{CreatePlanItemParamsV1Schema:Ko}=((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."})}))(Zb,cb),{LicenseCustomizeSchema:Al}=((e,t,n,r)=>({LicenseCustomizeSchema:e.object({price:t.nullable().optional(),add_items:e.array(n).optional(),remove_items:e.array(r).optional()})}))(A,ca,Ko,Fo),{PlanLicenseParamsSchema:Ho}=((e,t)=>({PlanLicenseParamsSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(A,Al),{UpdateProductV2ParamsSchema:gP}=((e,t,n,r,i,a,o,s,c)=>({UpdateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).optional().meta({description:n.id}),name:e.string().refine(l=>l.length>0,{message:"name must be a non-empty string"}).optional().meta({description:n.name}),is_add_on:e.boolean().optional().meta({description:n.is_add_on}),is_default:e.boolean().optional().meta({description:n.is_default}),base_plan_id:e.string().nonempty().regex(t).nullable().optional().meta({description:"The base plan this plan should be linked to as a variant. Set to null to detach it from its base plan."}),description:e.string().nullish().optional().meta({description:n.description}),group:e.string().nonempty().nullable().optional().meta({description:n.group}),archived:e.boolean().optional().meta({description:n.archived}),items:e.array(r).optional(),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata})})}))(A,ia,Hu,Il,Ho,Qu,Mo,sa,dr),{CreatePlanParamsV1Schema:Yb}=((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,ia,ca,Ko,Ho,Lo,Mo,$b,dr),{UpdatePlanParamsV1Schema:bP}=((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."})})}))(Yb,A,ca,Lo,ia),{CustomizePlanLicenseSchema:Qo}=((e,t)=>({CustomizePlanLicenseSchema:e.object({license_plan_id:e.string(),version_slug:e.string().optional(),included:e.number().int().min(0).optional(),prepaid_only:e.boolean().optional(),customize:t.nullish(),metadata:e.record(e.string(),e.unknown()).optional()})}))(A,Al),{CreateProductV2ParamsSchema:_P}=((e,t,n,r,i,a,o,s,c,u)=>({CreateProductV2ParamsSchema:e.object({id:e.string().nonempty().regex(t).meta({description:n.id}),name:e.string().refine(d=>d.length>0,{message:"name must be a non-empty string"}).meta({description:n.name}),description:e.string().nullish().meta({description:n.description}),is_add_on:e.boolean().default(!1).meta({description:n.is_add_on}),is_default:e.boolean().default(!1).meta({description:n.is_default}),group:e.string().nullable().default("").meta({description:n.group}),items:e.array(r).optional().meta({description:n.items}),licenses:e.array(i).optional().meta({internal:!0,description:"Plans offered as assignable licenses under this plan. The full set replaces existing links."}),free_trial:a.nullish().default(null).meta({description:n.free_trial}),config:o.optional().meta({description:"Miscellaneous product-level configuration flags."}),billing_controls:s.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:c.optional().meta({description:n.metadata}),create_in_stripe:e.boolean().optional().meta({internal:!0}),archived:e.boolean().optional().meta({internal:!0}),base_internal_product_id:e.string().nullable().optional().meta({internal:!0})}).meta({examples:[u]})}))(A,ia,Hu,Il,Ho,Qu,Mo,sa,dr,Qg),{CustomizePlanV1BaseSchema:wl}=((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,ca,Ko,Fo,bg,Lo,sa,Qo,xg),{VariantCustomizeSchema:Jb}=((e,t)=>({VariantCustomizeSchema:e(t.omit({items:!0}).strict(),{includeItems:!1,includeLicenses:!0})}))(pl,wl),{DiffedCustomizePlanV1Schema:yP}=((e,t)=>({DiffedCustomizePlanV1Schema:e(t.omit({items:!0}),{includeItems:!1,includeLicenses:!0})}))(pl,wl),{ApiPlanV1Schema:SP}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g)=>({ApiPlanV1Schema:e.object({id:e.string().meta({description:"Unique identifier for the plan."}),internal_id:e.string().nullable().optional().meta({description:"Stable row id. Survives renames of plan_id and version_slug, so config files address rows by it.",internal:!0}),name:e.string().meta({description:"Display name of the plan."}),description:e.string().nullable().meta({description:"Optional description of the plan."}),group:e.string().nullable().meta({description:"Group identifier for organizing related plans. Plans in the same group are mutually exclusive."}),version:e.number().meta({description:"Version number of the plan. Incremented when plan configuration changes."}),version_slug:e.string().nullable().optional().meta({description:"User-facing version identity. Defaults to v{n} when the version is minted."}),active:e.boolean().optional().meta({description:"Whether this is the active version of the plan. At most one version is active."}),add_on:e.boolean().meta({description:"Whether this is an add-on plan that can be attached alongside a main plan."}),auto_enable:e.boolean().meta({description:"If true, this plan is automatically attached when a customer is created. Used for free plans."}),price:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),additional_currencies:t.optional().meta({description:"Base price amounts in additional currencies. The base 'amount' is in the org's default currency."}),interval:e.enum(n).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),entitlement_id:e.string().optional().meta({internal:!0}),price_id:e.string().optional().meta({internal:!0}),display:r.optional().meta({description:"Display text for showing this price in pricing pages."}),processors:i.optional().meta({description:"Payment processors this base price is connected to. Omitted when unset."})}).nullable().meta({description:"Base recurring price for the plan. Null for free plans or usage-only plans."}),items:e.array(a).meta({description:"Feature configurations included in this plan. Each item defines included units, pricing, and reset behavior for a feature."}),processors:o.optional().meta({description:"Payment processors this plan is connected to. Omitted when unset."}),free_trial:s.optional().meta({description:"Free trial configuration. If set, new customers can try this plan before being charged."}),created_at:e.number().meta({description:"Unix timestamp (ms) when the plan was created."}),env:e.enum(c).meta({description:"Environment this plan belongs to ('sandbox' or 'live')."}),archived:e.boolean().meta({description:"Whether the plan is archived. Archived plans cannot be attached to new customers."}),config:u.meta({description:"Miscellaneous plan-level configuration flags."}),billing_controls:l.optional().meta({description:"Plan-level billing controls used as customer defaults."}),metadata:d.meta({description:"Arbitrary key-value metadata defined by you for your own use. Shared across all versions of the plan."}),customer_eligibility:p.optional(),base_variant_id:e.string().nullable().meta({description:"Deprecated. Use variant_details.base_plan_id instead. If this is a variant, the ID of the base plan it was created from.",deprecated:!0}),variant_details:e.object({base_plan_id:e.string().meta({description:"The ID of the base plan this variant was derived from."}),customize:g.optional().meta({description:"The customization that transforms the base plan into this variant."})}).optional().meta({description:"Details about how this variant relates to its latest base plan."})})}))(A,ii,In,Ro,il,Hb,Ib,db,Xi,aa,Wo,dr,pb,Jb);import{z as P}from"zod";var Xb=P.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Ol=P.enum(["single_use","continuous_use"]),Zo=P.record(P.string(),P.union([P.string(),P.number(),P.boolean()]).transform(String).pipe(P.string())),Pl=P.string().min(1).max(64).refine(e=>!e.includes("::")),El={credit_amount:P.number(),tier_behavior:P.never().optional(),tiers:P.never().optional()},Tl={credit_amount:P.never().optional(),tier_behavior:P.literal("graduated"),tiers:P.array(P.strictObject({to:P.union([P.number(),P.literal("inf")]),credit_amount:P.number()}))},zb=P.union([P.strictObject({match:Zo,priority:P.number().int().optional(),...El}),P.strictObject({match:Zo,priority:P.number().int().optional(),...Tl})]),e_=P.strictObject({match:Zo,factor:P.number().positive().optional(),add:P.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Cl={metered_feature_id:P.string(),feature_amount:P.number().optional(),dimensions:P.record(Pl,zb).optional(),multipliers:P.record(Pl,e_).optional()},Yo=P.union([P.strictObject({...Cl,...El}),P.strictObject({...Cl,...Tl})]),la=P.number().min(-100),Rl=P.record(P.string(),P.strictObject({markup:la})).nullish(),da=P.record(P.string().regex(/.+\/.+/),P.strictObject({markup:la.optional(),input_cost:P.number().min(0).optional(),output_cost:P.number().min(0).optional()})).nullish(),t_=P.strictObject({default_markup:la.optional(),provider_markups:Rl,model_markups:da}),Jo=P.strictObject({schema:P.array(Yo).optional(),markups:t_.optional()}),n_=P.strictObject({filters:P.array(P.strictObject({property:P.string(),operator:P.string(),value:P.array(P.string())})),aggregate:P.strictObject({type:P.string(),property:P.string().nullable()}),usage_type:Ol}),jl=P.strictObject({schema:P.array(Yo).min(1).refine(e=>new Set(e.map(t=>t.metered_feature_id)).size===e.length,"Credit rates must name each metered feature once"),invoice_credit:P.boolean().optional(),usage_type:Ol.default("single_use").overwrite(()=>"single_use"),default_markup:la.optional(),provider_markups:Rl}),Xo=jl.safeExtend({schema:P.array(Yo).length(0)}),ua={id:Xb,name:P.string().min(1),display:P.strictObject({singular:P.string().optional(),plural:P.string().optional()}).nullish(),event_names:P.array(P.string()).default([]),model_markups:da,stripe_meter:P.strictObject({id:P.string(),event_name:P.string()}).nullish(),stripe_product_id:P.string().nullish()},zo=e=>P.discriminatedUnion("type",[P.strictObject({...ua,...e,type:P.literal("boolean"),config:P.null()}),P.strictObject({...ua,...e,type:P.literal("metered"),config:n_}),P.strictObject({...ua,...e,type:P.literal("credit_system"),config:jl}),P.strictObject({...ua,...e,type:P.literal("ai_credit_system"),config:Xo})]),IP=zo({}),r_=P.strictObject({id:P.boolean(),type:P.boolean(),usage_type:P.boolean()}),i_={internal_id:P.uuid(),org_id:P.uuid(),created_at:P.number(),env:P.enum(["sandbox","live"]),archived:P.boolean(),project_id:P.uuid(),environment_id:P.uuid(),revision:P.number().int().nonnegative(),update_rules:r_},kl=zo(i_),AP=P.strictObject({rows:P.array(kl).max(200),nextCursor:P.uuid().nullable()}),Dl=P.strictObject({features:P.array(kl).max(500),limited:P.boolean()}),wP=P.union([zo({action:P.literal("save"),internal_id:P.uuid().nullable(),revision:P.number().int().nonnegative()}),P.strictObject({action:P.enum(["archive","restore","delete"]),internal_id:P.uuid(),revision:P.number().int().nonnegative()})]);import{z as pr}from"zod";var Nl=pr.number().int().min(0).max(1e8),ai=pr.strictObject({kind:pr.enum(["graduated","volume"]),tiers:pr.array(pr.strictObject({upTo:pr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Nl,flatAmountMinor:Nl.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function es(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?ai.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 es({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}import{z as R}from"zod";import{z as G}from"zod";import{z as rn}from"zod";import{z as fn}from"zod";var RP={plans:Vn,creditPacks:Vn,paidSeats:Vn,postpaid:Vn},Fl=fn.partialRecord(fn.enum(Vn),fn.number().int().min(1).max(1e8)),a_=fn.strictObject({currency:fn.enum(Vn),automaticTax:fn.boolean()}),o_=fn.strictObject({projectId:fn.uuid(),environmentId:fn.uuid()}),jP=o_.extend({settings:a_});var s_=rn.string().regex(/^[a-z][a-z0-9_]{0,63}$/),Ul=rn.number().int().min(0).max(1e4),ts=rn.object({key:s_,featureId:rn.uuid(),planVersionId:rn.uuid(),includedQuantity:Ul,maximumQuantity:Ul,unitAmountCents:rn.number().int().min(0).max(1e8),currency:ae,currencyOptions:Fl.optional(),stripePriceId:rn.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),pooledResources:rn.array(rn.string().regex(/^(?:[a-z][a-z0-9_]{0,63}|pool:[0-9a-f-]{36})$/)).max(100),requireAssignment:rn.boolean()}).strict().refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency),"Additional prices cannot repeat the default currency").refine(e=>e.maximumQuantity>=e.includedQuantity,"\u6700\u5927\u5E2D\u4F4D\u6570\u4E0D\u80FD\u5C0F\u4E8E\u5305\u542B\u5E2D\u4F4D\u6570").refine(e=>new Set(e.pooledResources).size===e.pooledResources.length,"\u5171\u4EAB\u6765\u6E90\u4E0D\u80FD\u91CD\u590D");import{z as Pe}from"zod";import{z as it}from"zod";var ns=it.object({days:it.number().int().min(1).max(730),cardRequired:it.boolean(),featureAllowances:it.record(it.uuid(),it.number().int().min(0).max(1e9)),creditAmounts:it.record(it.uuid(),ge)}).strict(),rs=it.object({id:it.uuid(),planVersionId:it.uuid(),slot:it.string(),cardRequired:it.boolean(),status:it.enum(["pending","active","converted","canceled","expired","failed"]),startsAt:it.iso.datetime().nullable(),endsAt:it.iso.datetime().nullable(),createdAt:it.iso.datetime()}).strict();var is=Pe.object({group:Pe.string().regex(/^[a-z][a-z0-9_]{0,63}$/).default("main"),kind:Pe.enum(["main","addon"]).default("main")}).strict(),c_=Pe.enum(["immediate","end_of_cycle"]),u_=Pe.enum(["attach","change","cancel","resume","cancel_change"]),Ml=Pe.object({id:Pe.uuid(),subscriptionId:Pe.uuid().nullable(),targetPlanVersionId:Pe.uuid().nullable(),action:u_,timing:c_,status:Pe.enum(["preparing","payment_pending","scheduled","completed","canceled","failed"]),effectiveAt:Pe.iso.datetime().nullable(),createdAt:Pe.iso.datetime()}),l_=Pe.object({id:Pe.uuid(),planVersionId:Pe.uuid(),planId:Pe.uuid(),basePlanId:Pe.uuid().nullable(),name:Pe.string(),group:Pe.string(),kind:Pe.enum(["main","addon"]),source:Pe.enum(["subscription","assignment","license","apple","google"]),status:Pe.string(),accessEnabled:Pe.boolean(),startsAt:Pe.iso.datetime().nullable(),endsAt:Pe.iso.datetime().nullable(),cancelAtPeriodEnd:Pe.boolean(),scheduledChange:Ml.nullable(),trial:rs.nullable().optional()}),$P=Pe.object({customerId:Pe.uuid(),evaluatedAt:Pe.iso.datetime(),holdings:Pe.array(l_),changes:Pe.array(Ml),trials:Pe.array(rs).optional()});var an=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"),JP=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"),Bl=G.object({key:an,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()}),XP=Bl.extend({...je.shape,id:G.string().min(1),archived:G.boolean(),createdAt:G.iso.datetime()}),Ll=G.object({amountCents:G.number().int().min(0).max(1e8),currency:ae,interval:G.enum(["free","month","year"]),currencyOptions:G.partialRecord(ae,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()}),ql=G.object({name:G.string().trim().min(1).max(80),description:G.string().trim().max(240),price:Ll,membership:is.optional(),trial:ns.nullable().optional(),licenses:G.array(ts).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")}),zP=G.object({key:an,config:ql}),eC=je.extend({id:G.string().min(1),key:an,draft:ql,status:G.enum(["draft","published","archived"]),publishedVersionId:G.string().nullable(),isDefault:G.boolean(),updatedAt:G.iso.datetime()}),p_=Bl.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"),Vl=je.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:Ll,membership:is.optional(),trial:ns.nullable().optional(),licenses:G.array(ts).optional(),items:G.array(p_),publishedAt:G.iso.datetime()}).strict(),as=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"),tC=je.extend({id:G.string(),customerId:G.string(),planVersionId:G.string(),assignedAt:G.iso.datetime(),source:G.literal("demo"),validity:as.nullable().default(null),used:G.record(G.string(),G.number().int().min(0))}),nC=je.extend({id:G.string(),customerId:G.string(),at:G.iso.datetime(),message:G.string()});import{z as b}from"zod";import{z as ne}from"zod";var $l={"zh-Hans":{once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{once:"{discount} off your first payment",repeating:"{discount} off each month for the first {months} months",repeatingOne:"{discount} off the first month",forever:"{discount} off every payment"},ja:{once:"\u521D\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15",repeating:"\u6700\u521D\u306E {months} \u304B\u6708\u9593\u3001\u6BCE\u6708 {discount} \u5272\u5F15",forever:"\u6BCE\u56DE\u306E\u304A\u652F\u6255\u3044\u304C {discount} \u5272\u5F15"},ko:{once:"\uCCAB \uACB0\uC81C {discount} \uD560\uC778",repeating:"\uCCAB {months}\uAC1C\uC6D4 \uB3D9\uC548 \uB9E4\uC6D4 {discount} \uD560\uC778",forever:"\uB9E4 \uACB0\uC81C {discount} \uD560\uC778"},es:{once:"{discount} de descuento en el primer pago",repeating:"{discount} de descuento cada mes durante los primeros {months} meses",forever:"{discount} de descuento en cada pago",repeatingOne:"{discount} de descuento durante el primer mes"},fr:{once:"{discount} de r\xE9duction sur le premier paiement",repeating:"{discount} de r\xE9duction par mois pendant les {months} premiers mois",forever:"{discount} de r\xE9duction sur chaque paiement",repeatingOne:"{discount} de r\xE9duction pendant le premier mois"},de:{once:"{discount} Rabatt auf die erste Zahlung",repeating:"{discount} Rabatt pro Monat f\xFCr die ersten {months} Monate",forever:"{discount} Rabatt auf jede Zahlung",repeatingOne:"{discount} Rabatt im ersten Monat"},pt:{once:"{discount} de desconto no primeiro pagamento",repeating:"{discount} de desconto por m\xEAs nos primeiros {months} meses",forever:"{discount} de desconto em cada pagamento",repeatingOne:"{discount} de desconto no primeiro m\xEAs"},it:{once:"{discount} di sconto sul primo pagamento",repeating:"{discount} di sconto al mese per i primi {months} mesi",forever:"{discount} di sconto su ogni pagamento",repeatingOne:"{discount} di sconto per il primo mese"},ru:{once:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043F\u0435\u0440\u0432\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436",repeating:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043A\u0430\u0436\u0434\u044B\u0439 \u043C\u0435\u0441\u044F\u0446 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",repeatingOne:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u0432 \u043F\u0435\u0440\u0432\u044B\u0439 \u043C\u0435\u0441\u044F\u0446",forever:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u043A\u0430\u0436\u0434\u044B\u0439 \u043F\u043B\u0430\u0442\u0451\u0436"},vi:{once:"Gi\u1EA3m {discount} cho l\u1EA7n thanh to\xE1n \u0111\u1EA7u ti\xEAn",repeating:"Gi\u1EA3m {discount} m\u1ED7i th\xE1ng trong {months} th\xE1ng \u0111\u1EA7u",forever:"Gi\u1EA3m {discount} cho m\u1ED7i l\u1EA7n thanh to\xE1n"},th:{once:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E04\u0E23\u0E31\u0E49\u0E07\u0E41\u0E23\u0E01",repeating:"\u0E25\u0E14 {discount} \u0E15\u0E48\u0E2D\u0E40\u0E14\u0E37\u0E2D\u0E19\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",forever:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E01\u0E32\u0E23\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19\u0E17\u0E38\u0E01\u0E04\u0E23\u0E31\u0E49\u0E07"},id:{once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{once:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u062F\u0641\u0639\u0629 \u0627\u0644\u0623\u0648\u0644\u0649",repeating:"\u062E\u0635\u0645 {discount} \u0634\u0647\u0631\u064A\u064B\u0627 \u0644\u0645\u062F\u0629 {period}",forever:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0643\u0644 \u062F\u0641\u0639\u0629"}},oC=["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=Qi(e)??"en",n=t.split("-"),r=n[0]==="zh"?n.includes("Hans")?"zh-Hans":n.includes("Hant")||n.some(a=>["TW","HK","MO"].includes(a))?"zh-Hant":"zh-Hans":n[0]??"en",i=$l[r];return i?{locale:t,copy:i}:{locale:"en",copy:$l.en}}function m_(e,t,n="zh-CN"){let r=Vi(t);return ru(e,t,os(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function f_(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):m_(e.amountOffCents,e.currency,n)}var Gl={zh:"\u524D {months} \u4E2A\u6708\u5185\u5F00\u51FA\u7684\u8D26\u5355\u51CF {discount}","zh-Hant":"\u524D {months} \u500B\u6708\u5167\u958B\u51FA\u7684\u5E33\u55AE\u6E1B {discount}",en:"{discount} off invoices issued within the first {months} months",ja:"\u6700\u521D\u306E {months} \u304B\u6708\u4EE5\u5185\u306E\u8ACB\u6C42\u304C {discount} \u5272\u5F15",ko:"\uCCAB {months}\uAC1C\uC6D4 \uB0B4 \uCCAD\uAD6C\uC11C {discount} \uD560\uC778",es:"{discount} de descuento en facturas emitidas durante los primeros {months} meses",fr:"{discount} de r\xE9duction sur les factures \xE9mises pendant les {months} premiers mois",de:"{discount} Rabatt auf Rechnungen innerhalb der ersten {months} Monate",pt:"{discount} de desconto nas faturas emitidas nos primeiros {months} meses",it:"{discount} di sconto sulle fatture emesse nei primi {months} mesi",ru:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \u043D\u0430 \u0441\u0447\u0435\u0442\u0430 \u0432 \u0442\u0435\u0447\u0435\u043D\u0438\u0435 \u043F\u0435\u0440\u0432\u044B\u0445 {months} \u043C\u0435\u0441.",vi:"Gi\u1EA3m {discount} cho h\xF3a \u0111\u01A1n trong {months} th\xE1ng \u0111\u1EA7u",th:"\u0E25\u0E14 {discount} \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A\u0E43\u0E1A\u0E41\u0E08\u0E49\u0E07\u0E2B\u0E19\u0E35\u0E49\u0E43\u0E19\u0E0A\u0E48\u0E27\u0E07 {months} \u0E40\u0E14\u0E37\u0E2D\u0E19\u0E41\u0E23\u0E01",id:"Diskon {discount} untuk tagihan dalam {months} bulan pertama",ar:"\u062E\u0635\u0645 {discount} \u0639\u0644\u0649 \u0627\u0644\u0641\u0648\u0627\u062A\u064A\u0631 \u0627\u0644\u0635\u0627\u062F\u0631\u0629 \u062E\u0644\u0627\u0644 \u0623\u0648\u0644 {period}"};function Wl(e,t="zh-CN",n="month"){let r=os(t),i=f_(e.discount,r.locale),a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",o=r.locale.split("-")[0]??"en",s=o==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":o,c=e.duration.type==="repeating"&&n!=="month"?Gl[s]??Gl.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],u=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return c.replace("{discount}",i).replace("{months}",a).replace("{period}",u)}var pC=ne.enum(["draft","active","paused","archived"]),mr=ne.discriminatedUnion("type",[ne.object({type:ne.literal("percent"),percentOff:ne.number().int().min(1).max(100)}).strict(),ne.object({type:ne.literal("amount"),amountOffCents:ne.number().int().min(1).max(1e8),currency:ae}).strict()]),Yt=ne.discriminatedUnion("type",[ne.object({type:ne.literal("once")}).strict(),ne.object({type:ne.literal("repeating"),months:ne.number().int().min(1).max(36)}).strict(),ne.object({type:ne.literal("forever")}).strict()]),Kl=ne.discriminatedUnion("type",[ne.object({type:ne.literal("all")}).strict(),ne.object({type:ne.literal("plans"),planIds:ne.array(ne.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()]),h_=ne.strictObject({firstPurchaseOnly:ne.boolean(),condition:xn}),Hl=ne.object({name:ne.string().trim().min(1).max(80),description:ne.string().max(500),discount:mr,duration:Yt,appliesTo:Kl,eligibility:h_,selfClaimEnabled:ne.boolean().default(!1),startsAt:ne.iso.datetime().nullable(),endsAt:ne.iso.datetime().nullable(),totalLimit:ne.number().int().min(1).max(1e6).nullable(),perCustomerLimit:ne.number().int().min(1).max(10),grantWindowHours:ne.number().int().min(1).max(2160)}).strict().refine(e=>!e.startsAt||!e.endsAt||Date.parse(e.endsAt)>Date.parse(e.startsAt),{message:"\u7ED3\u675F\u65F6\u95F4\u5FC5\u987B\u665A\u4E8E\u5F00\u59CB\u65F6\u95F4",path:["endsAt"]}),mC=ne.object({code:ne.string().trim().transform(e=>e.toUpperCase()).pipe(ne.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/,"\u4F18\u60E0\u7801\u53EA\u80FD\u7528 3\u201332 \u4F4D\u5B57\u6BCD\u3001\u6570\u5B57\u3001- \u548C _\uFF0C\u4EE5\u5B57\u6BCD\u6216\u6570\u5B57\u5F00\u5934")),maxRedemptions:ne.number().int().min(1).max(1e6).nullable(),expiresAt:ne.iso.datetime().nullable(),firstPurchaseOnly:ne.boolean(),minimumAmountCents:ne.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:ae.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");function fC(){return{name:"\u65B0\u4F18\u60E0\u5238",description:"",discount:{type:"percent",percentOff:20},duration:{type:"once"},appliesTo:{type:"all"},eligibility:{firstPurchaseOnly:!1,condition:{}},selfClaimEnabled:!1,startsAt:null,endsAt:null,totalLimit:null,perCustomerLimit:1,grantWindowHours:72}}var ss=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function hC(e,t,n){if(e==="draft")return[];if(e==="archived")return[{field:"name",reason:"archived"}];let r=[];return ss(t.discount,n.discount)||r.push({field:"discount",reason:"immutable"}),ss(t.duration,n.duration)||r.push({field:"duration",reason:"immutable"}),ss(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 gC(e,t="zh-CN"){return Wl(e,t)}function bC(e){return g_(e)}function _C(e,t){return e.startsAt&&Date.parse(e.startsAt)>t?"scheduled":e.endsAt&&Date.parse(e.endsAt)<=t?"ended":"open"}var oi=ne.object({id:ne.uuid(),couponId:ne.uuid(),status:ne.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:ne.iso.datetime(),expiresAt:ne.iso.datetime(),coupon:ne.object({name:ne.string(),discount:mr,duration:Yt,appliesTo:Kl}).strict()}).strict(),ma=ne.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Xl=b.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),cs=b.string().regex(/^(0|[1-9]\d{0,14})$/),fr=b.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),b_=b.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),si=b_,hn=ge.refine(e=>/[1-9]/.test(e)),mt=b.iso.datetime({offset:!0}),Gn=e=>{let[t,n=""]=e.split(".");if(t===void 0||t==="")throw new Error("Invalid decimal value");return BigInt(t)*1000000n+BigInt(n.padEnd(6,"0"))},__=b.array(b.object({upTo:hn.nullable(),unitAmountMinor:Xl,flatAmountMinor:b.number().int().min(0).max(1e8).optional()}).strict()).min(1).max(12).refine(e=>{try{return e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Gn(t.upTo)>Gn(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),y_=b.discriminatedUnion("kind",[b.object({kind:b.literal("flat"),units:hn,unitAmountMinor:Xl}).strict(),b.object({kind:b.enum(["graduated","volume"]),units:hn,tiers:__}).strict()]).refine(e=>e.kind==="flat"||!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers"),S_=b.strictObject({interval:b.enum(["month","year"]),count:b.number().int().min(1).max(12),anchor:b.enum(["membership","calendar"])}),An=b.object({currency:ae,pricing:y_,billingCycle:S_.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");function zl(e){return e.pricing.kind==="flat"&&Gn(e.pricing.units)>0n&&Gn(e.pricing.unitAmountMinor)===Gn(e.pricing.units)*BigInt(10**Vi(e.currency))}var Ql={requestId:b.uuid(),productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:ae},ed=b.strictObject({interval:b.enum(["hour","day","week","month"]),intervalCount:b.number().int().min(1).max(12),limit:b.number().int().min(1).max(1e6)}),td=b.discriminatedUnion("kind",[b.object({...Ql,kind:b.literal("auto_topup"),threshold:Ao,quantity:hn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:ed.optional()}).strict(),b.object({...Ql,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:si,maxOutstandingMinor:si}).strict()]),Zl={productVersionId:b.uuid(),internal_feature_id:b.uuid(),currency:ae},nd=b.discriminatedUnion("kind",[b.object({...Zl,kind:b.literal("auto_topup"),threshold:Ao,quantity:hn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:ed.optional(),purchaseAmountMinor:si,purchaseUnits:hn}).strict(),b.object({...Zl,kind:b.literal("postpaid"),maxAmountMinorPerPeriod:si,maxOutstandingMinor:si,cashPrice:An}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),fa=b.object({id:b.uuid(),terms:nd,status:b.enum(["prepared","active","revoked","blocked"]),createdAt:mt,acceptedAt:mt.nullable(),effectiveAt:mt.nullable(),revokedAt:mt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),rd=b.object({authorizationId:b.uuid(),terms:nd,setupUrl:b.url().nullable()}).strict(),id=b.object({authorizationId:b.uuid(),accepted:b.literal(!0)}).strict(),ad=b.object({authorizationId:b.uuid(),requestId:b.uuid()}).strict(),od=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),anchor:b.enum(["billing_cycle","utc"]).optional(),basis:b.enum(["usage","credits"]),filter:Zt.optional(),limit:ge.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(hn).max(8).optional()}).strict().refine(e=>e.thresholds.every((t,n)=>{let r=e.thresholds[n-1];return n===0||r!==void 0&&t>r})&&(e.includedThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&t>i})&&(e.absoluteThresholds??[]).every((t,n,r)=>{let i=r[n-1];return n===0||i!==void 0&&Gn(t)>Gn(i)}),"Notification thresholds must increase"),v_=od.safeExtend({requestId:b.uuid()}),Yl={control:b.literal("overage"),requestId:b.uuid(),internal_feature_id:b.uuid(),entityId:b.uuid().nullable()},x_=b.discriminatedUnion("action",[b.strictObject({...Yl,action:b.literal("set"),allowed:b.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:b.boolean()}),b.strictObject({...Yl,action:b.literal("remove")})]),sd=b.union([v_,x_]),I_=b.strictObject({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),allowed:b.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:b.boolean(),interval:b.enum(["day","week","month","year"]),startsAt:mt,endsAt:mt,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()}),A_=b.object({internal_feature_id:b.uuid(),entityId:b.uuid().nullable(),interval:b.enum(["day","week","month","year"]),anchor:b.enum(["billing_cycle","utc"]).optional(),basis:b.enum(["usage","credits"]),filter:Zt.optional(),startsAt:mt,endsAt:mt,used:xt,reserved:xt,limit:ge.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(hn).max(8).optional(),notifiedAbsoluteThresholds:b.array(hn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||ge.safeParse(e.used).success&&ge.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),w_=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:mt.nullable(),attemptCount:b.number().int().nonnegative(),failedAttemptCount:b.number().int().nonnegative(),suspendedAt:mt.nullable(),nextAttemptAt:mt.nullable(),failureReason:b.string().min(1).max(240).nullable()}).strict(),cd=b.object({internal_feature_id:b.uuid().optional(),entityId:b.uuid().optional()}).strict(),us=b.object({authorizations:b.array(fa).max(100),limits:b.array(od).max(100),overages:b.array(I_).max(100).optional(),windows:b.array(A_).max(200),autoTopups:b.array(w_).max(100),limited:b.boolean()}).strict(),P_=b.object({id:b.uuid(),internal_feature_id:b.uuid(),productVersionId:b.uuid(),authorizationId:b.uuid(),entityId:b.uuid().nullable(),units:ge,amountMinor:fr,cashPrice:An}).strict(),ci=b.object({id:b.uuid(),sourceKind:b.enum(["product","usage","manual"]),providerInvoiceId:b.string().min(1).max(240).nullable(),status:b.enum(["accruing","open","pending","paid","failed","void"]),currency:ae,startsAt:mt.nullable(),endsAt:mt.nullable(),amountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:b.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:cs,paidAmountMinor:cs,refundedAmountMinor:cs,createdAt:mt,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:mt.nullable()}).strict().nullable(),lines:b.array(P_).max(100),linesLimited:b.boolean()}).strict(),ud=b.object({invoiceId:b.uuid(),accepted:b.literal(!0)}).strict(),ld=b.object({after:b.uuid().nullable(),limit:b.number().int().min(1).max(100)}).strict(),dd=b.object({rows:b.array(ci).max(100),nextCursor:b.uuid().nullable()}).strict(),Jl=b.strictObject({id:b.string(),coupon:b.string(),start:b.number().nonnegative(),end:b.number().nullable()}),C_=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(Jl).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:Jl.optional()})).max(20)})).max(100)}),pd=b.strictObject({membershipId:b.uuid(),requestId:b.uuid(),grantIds:b.array(b.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),md=b.strictObject({membershipId:b.uuid(),operationId:b.uuid(),status:b.enum(["pending","effective"]),execution:C_.nullable(),grants:b.array(b.strictObject({id:b.uuid(),couponId:b.uuid(),name:b.string(),discount:mr,duration:Yt,startedAt:mt.nullable()})).max(20)});import{z as ui}from"zod";var li=ui.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),di=ui.number().int().min(1).max(1e3),Wn=ui.object({cap:ge.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:ui.number().positive().max(1e4).nullable(),cycles:ui.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var ls={key:an,name:R.string().trim().min(1).max(80),description:R.string().trim().max(240)},fd=ge.refine(e=>/[1-9]/.test(e)),ha=R.array(R.object({currency:ae,amountMinor:R.number().int().min(0).max(1e8)}).strict()).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique"),ds=R.strictObject({units:fd,prices:R.array(R.strictObject({currency:ae,amountMinor:R.number().int().min(0).max(1e8),pricing:ai.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:R.number().int().min(0).max(1e4),maximumQuantity:R.number().int().min(1).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&es({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit"),O_=R.discriminatedUnion("kind",[R.object({kind:R.literal("access"),internal_feature_id:R.uuid()}).strict(),R.object({kind:R.literal("metered"),internal_feature_id:R.uuid(),usageUnit:R.enum(["count","micro_usd"]),amount:ge.nullable(),reset:li,resetCount:di,pooled:R.boolean(),rollover:Wn.nullable().optional(),cashPrice:An.nullable().optional(),prepaidPrice:ds.optional(),feature_override:Jo.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 ms(e.amount,e.prepaidPrice.units,e.prepaidPrice.maximumQuantity),!0}catch{return!1}},"The maximum purchased allowance must fit the quantity ledger"),R.object({kind:R.literal("credit"),internal_feature_id:R.uuid(),amount:ge,reset:li,resetCount:di,rollover:Wn.nullable(),pooled:R.boolean(),feature_override:Jo.nullish(),cashPrice:An.nullable().optional()}).strict().refine(e=>!e.cashPrice||e.reset!=="lifetime"&&!e.rollover&&!e.pooled&&zl(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")]),ps=R.array(O_).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"An entitlement can be granted once per product"),hd=R.object({days:R.number().int().min(1).max(730),cardRequired:R.boolean(),allowances:ps}).strict().refine(e=>e.allowances.every(t=>t.kind==="access"||!t.cashPrice&&(t.kind!=="metered"||!t.prepaidPrice)),"Trial allowances do not charge cash overages or purchased quantities"),gd=R.object({key:an,internal_feature_id:R.uuid(),productVersionId:R.uuid(),includedQuantity:R.number().int().min(0).max(1e4),maximumQuantity:R.number().int().min(0).max(1e4),prices:ha,pooled_internal_feature_ids:R.array(R.uuid()).max(100),requireAssignment:R.boolean()}).strict().refine(e=>e.maximumQuantity>=e.includedQuantity,"Capacity cannot be less than included seats").refine(e=>new Set(e.pooled_internal_feature_ids).size===e.pooled_internal_feature_ids.length,"Shared entitlements must be unique"),pi=R.discriminatedUnion("kind",[R.object({...ls,kind:R.literal("membership"),groupId:R.uuid(),membershipType:R.enum(["main","addon"]),interval:R.enum(["free","week","month","year","one_time"]),intervalCount:R.number().int().min(1).max(156).optional(),prices:ha,allowances:ps,trial:hd.nullable(),licenses:R.array(gd).max(20).refine(e=>new Set(e.map(t=>t.key)).size===e.length,"License keys must be unique")}).strict().refine(e=>e.interval==="free"?e.prices.every(t=>t.amountMinor===0):e.prices.every(t=>e.interval==="one_time"?t.amountMinor>0||e.allowances.some(n=>n.kind==="metered"&&n.prepaidPrice?.prices.some(r=>r.currency===t.currency&&r.amountMinor>0)):t.amountMinor>=0),"Prices must match the billing interval").refine(e=>e.interval!=="one_time"||e.trial===null,"Lifetime plans cannot have a subscription trial").refine(e=>e.intervalCount===void 0||(e.interval==="week"||e.interval==="month"||e.interval==="year")&&e.intervalCount<=(e.interval==="year"?3:e.interval==="month"?36:156),"Recurring billing intervals cannot exceed three years").refine(e=>e.allowances.every(t=>t.kind!=="metered"||!t.prepaidPrice||e.interval!=="free"&&t.prepaidPrice.prices.length===e.prices.length&&t.prepaidPrice.prices.every(n=>e.prices.some(r=>r.currency===n.currency))),"Purchased features require a paid plan and all its published currencies"),R.object({...ls,kind:R.literal("topup"),interval:R.literal("one_time"),prices:ha,internal_feature_id:R.uuid(),amount:fd,expiresDays:R.number().int().min(1).max(3660).nullable()}).strict().refine(e=>e.prices.every(t=>t.amountMinor>0),"A topup must have a positive price")]),ga=R.object({interval:R.enum(["free","week","month","year","one_time"]).optional(),intervalCount:R.number().int().min(1).max(156).nullable().optional(),prices:ha.optional(),allowances:R.object({upsert:ps,remove:R.array(R.uuid()).max(100)}).strict().refine(e=>new Set(e.remove).size===e.remove.length&&e.upsert.every(t=>!e.remove.includes(t.internal_feature_id)),"An allowance cannot be removed and replaced together").optional(),trial:hd.nullable().optional(),licenses:R.array(gd).max(20).optional()}).strict(),bd=R.object({...ls,kind:R.literal("variant"),baseProductVersionId:R.uuid(),overrides:ga}).strict(),UC=R.union([pi,bd]);function MC(e,t){let n=bd.parse(t);if(e.kind!=="membership")throw new Error("A variant requires a membership base");let{allowances:r,intervalCount:i,...a}=n.overrides,o=new Map(e.allowances.map(c=>[c.internal_feature_id,c]));for(let c of r?.remove??[])if(!o.delete(c))throw new Error("Removed allowance is absent from the base");for(let c of r?.upsert??[])o.delete(c.internal_feature_id);for(let c of r?.upsert??[])o.set(c.internal_feature_id,c);let s={...structuredClone(e),...structuredClone(a),key:n.key,name:n.name,description:n.description,allowances:structuredClone([...o.values()])};return i===null?delete s.intervalCount:i!==void 0&&(s.intervalCount=i),pi.parse(s)}function BC(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}),ga.parse(n)}var LC=R.object({products:R.array(R.object({id:R.uuid(),productId:R.string().min(1),name:R.string(),kind:R.enum(["membership","topup"]),version:R.number().int().positive()}).strict()).max(500),limited:R.boolean()}).strict(),E_=xl.and(R.object({internal_id:R.uuid(),revision:R.number().int().nonnegative(),licenses:R.array(Qo)})),qC=R.strictObject({rows:R.array(E_).max(200),nextCursor:R.uuid().nullable()}),VC=R.object({groups:R.array(R.object({id:R.uuid(),name:R.string(),defaultProductVersionId:R.uuid().nullable()}).strict()).max(500),features:Dl.shape.features,products:R.array(R.object({id:R.uuid(),productId:R.uuid(),version:R.number().int().positive(),configuration:pi,baseProductVersionId:R.uuid().nullable()}).strict()).max(500),limited:R.boolean()}).strict();function ms(e,t,n){let r=o=>{if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(o))throw new Error("Invalid quantity");let[s,c=""]=o.split(".");if(s===void 0||s==="")throw new Error("Invalid decimal value");return BigInt(s)*1000000n+BigInt(c.padEnd(6,"0"))};if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let i=r(e)+r(t)*BigInt(n);if(i>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let a=(i%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(i/1000000n).toString()+(a?"."+a:"")}var KC=Jt.object({requestId:Jt.uuid(),baseProductVersionId:Jt.uuid(),name:Jt.string().trim().min(1).max(80),description:Jt.string().trim().max(240),overrides:ga}).strict(),HC=Jt.object({productId:Jt.uuid(),productVersionId:Jt.uuid(),bindingStatus:Jt.enum(["ready","requires_binding"]),missingCurrencies:Jt.array(Jt.string().regex(/^[A-Z]{3}$/)).max(20)}).strict();var yd="X-Indiana-Protocol",T_="X-Indiana-SDK-Version",ZC="X-Indiana-Supported-Protocols",_d={stableSupportMonths:12,retirementNoticeDays:180,documentation:"/docs/release-notes#support-policy"},R_={current:"0.6",unversioned:"0.2",releases:[{protocol:"0.2",firstReleasedAt:"2026-10-16T04:05:43.170Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.2.0",integrity:"sha512-kyzHFrt+zuS2hfDZsknCE3AIA9EZXakCDhorO0Ayn2wTpITbm32GMaqVFyhlPufDhkjkV4C0UvXJMyLT5FWIoQ==",sha256:"7e20dd8df9c5e965f67bcdad6c95bf0d0aa5e61a372e5ece88173e32190a1c4c"}]},{protocol:"0.3",firstReleasedAt:"2026-10-16T16:18:04.572Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.3.0",integrity:"sha512-jrh4DH2DBYL5tRkr9BNBVIgD1ts0hUPx8+AhiNkkt2uWV27R8tXGRCW1HBLOw2bfomyuIsAXBAY6niJfjkazCg==",sha256:"33f7ca369d509c44df95c5c8b94775c2afe9d8e3a94163275fe59754739e6815"},{version:"0.3.1",integrity:"sha512-Ifp24kv236advquxa78jx49XKz9oKsg5zZZvFMkId4+KxsylsGxHS44fqYJL/b84PVHl3DLuc+Ru2btdLEctIw==",sha256:"4cc047fe94477e77c5403ce47afea0db2806bd4c3cb94a2dd48c453b4e942163"}]},{protocol:"0.4",firstReleasedAt:"2026-10-18T12:44:12.148Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.4.0",integrity:"sha512-QYuxMdw63RzPLkqmFRc7xv8VWYKYWG+KuKM+f5ZeRX879n6sKyr38bxkMiozFXT+kvH0lDfTF73uJPY2yQX1pQ==",sha256:"ef22d0f6a89897bfbaf71487c4e805997528c8dbad2921ab5c90ed3aa0c01244"}]},{protocol:"0.5",firstReleasedAt:"2026-10-19T08:12:17.954Z",noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[{version:"0.5.0",integrity:"sha512-tzdmoHdvaSoDIvGmg+JpmzE+o1kv7DXpSyvNUSuBj5rHX2pD1GDsMf7ioudUVT5MiKaBDVVtJVE+GpxMOBBLLA==",sha256:"d8b1909bebe1bca0c8c029a68b71477e06ba0c9317c3a2b4bf657951ae3449ca"}]},{protocol:"0.6",firstReleasedAt:null,noticePublishedAt:null,sunsetAt:null,noticeUrl:null,baselines:[]}]},Sd=/^(?:0\.(?:0|[1-9]\d*)|[1-9]\d*)$/,j_=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function vd(e){let t=j_.exec(e);return!t?.[1]||!t[2]?null:t[1]==="0"?`0.${t[2]}`:t[1]}var hs=e=>/^[1-9]\d*$/.test(e);function k_(e,t){let n=new Date(e),r=n.getUTCDate();n.setUTCDate(1),n.setUTCMonth(n.getUTCMonth()+t);let i=new Date(n.getTime());return i.setUTCMonth(i.getUTCMonth()+1,0),n.setUTCDate(Math.min(r,i.getUTCDate())),n.getTime()}var fs=e=>/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{3})?Z$/.test(e)&&Number.isFinite(Date.parse(e))&&new Date(e).toISOString().replace(".000Z","Z")===e.replace(".000Z","Z");function YC(e){let t=[],n=new Set;for(let r of e.releases){let i=r.protocol;(!Sd.test(i)||n.has(i))&&t.push(`Invalid/duplicate protocol ${i}`),n.add(i),(r.firstReleasedAt===null?i!==e.current:!fs(r.firstReleasedAt))&&t.push(`${i}: invalid first release date`),r.noticePublishedAt!==null&&!fs(r.noticePublishedAt)&&t.push(`${i}: invalid notice date`),r.sunsetAt!==null&&!fs(r.sunsetAt)&&t.push(`${i}: invalid sunset date`),r.noticePublishedAt&&(!r.firstReleasedAt||Date.parse(r.noticePublishedAt)<Date.parse(r.firstReleasedAt))&&t.push(`${i}: notice predates release`),r.noticeUrl!==null&&!/^(?:https:\/\/[^\s<>]+|\/docs\/[\w/#.-]+)$/.test(r.noticeUrl)&&t.push(`${i}: invalid notice URL`),r.firstReleasedAt&&!r.baselines.length&&t.push(`${i}: missing published SDK baseline`),!r.firstReleasedAt&&r.baselines.length&&t.push(`${i}: unpublished current protocol cannot claim published baselines`);let a=new Set;for(let o of r.baselines)(vd(o.version)!==i||a.has(o.version))&&t.push(`${i}: invalid/duplicate baseline ${o.version}`),a.add(o.version),(!/^sha512-[A-Za-z0-9+/]{86}==$/.test(o.integrity)||!/^[a-f0-9]{64}$/.test(o.sha256))&&t.push(`${i}: unpinned baseline ${o.version}`);if(hs(i)&&r.sunsetAt!==null){let o=e.releases.filter(s=>s.firstReleasedAt!==null&&hs(s.protocol)&&Number(s.protocol)>Number(i)).sort((s,c)=>Date.parse(s.firstReleasedAt)-Date.parse(c.firstReleasedAt))[0];o?Date.parse(r.sunsetAt)<k_(o.firstReleasedAt,_d.stableSupportMonths)&&t.push(`${i}: retirement violates 12 calendar months`):t.push(`${i}: retirement requires a released successor major`),!r.noticePublishedAt||!r.noticeUrl?t.push(`${i}: retirement requires a published notice`):Date.parse(r.sunsetAt)-Date.parse(r.noticePublishedAt)<_d.retirementNoticeDays*864e5&&t.push(`${i}: retirement violates 180 days notice`)}}return(!n.has(e.current)||!n.has(e.unversioned))&&t.push("Current/unversioned protocol is not registered"),e.releases.find(r=>r.protocol===e.current)?.sunsetAt!==null&&t.push("Current protocol cannot be scheduled for retirement"),t}var Kn=class extends Error{constructor(n,r,i=400){super(r);this.code=n;this.status=i}code;status};function JC(e,t=R_,n=Date.now()){let r=e.get(yd)??t.unversioned;if(!Sd.test(r))throw new Kn("INVALID_PROTOCOL_VERSION","Invalid Indiana protocol version");let i=t.releases.find(o=>o.protocol===r);if(!i)throw new Kn("UNSUPPORTED_PROTOCOL_VERSION","Indiana protocol version is not supported");if(!hs(r)&&r!==t.current)throw new Kn("UNSUPPORTED_PROTOCOL_VERSION","Only the current pre-1.0 Indiana protocol is supported");if(i.sunsetAt&&n>=Date.parse(i.sunsetAt))throw new Kn("PROTOCOL_RETIRED","Indiana protocol version has retired; follow the published migration notice",410);let a=e.get(T_);if(a!==null&&vd(a)!==r)throw new Kn("INVALID_PROTOCOL_VERSION","SDK version and protocol version do not match");return i}function XC(e,t=Date.now()){let n={[yd]:e.protocol};return e.noticePublishedAt&&Date.parse(e.noticePublishedAt)<=t&&(n.Deprecation=`@${Math.floor(Date.parse(e.noticePublishedAt)/1e3)}`,e.noticeUrl&&(n.Link=`<${e.noticeUrl}>; rel="deprecation"; type="text/html"`),e.sunsetAt&&(n.Sunset=new Date(e.sunsetAt).toUTCString())),n}import{z as $e}from"zod";var D_=$e.object({minAccountAgeDays:$e.number().int().min(0).max(3650),paymentStatus:$e.enum(["all","unpaid","paid"])}),N_=$e.object({percentOff:$e.number().int().min(1).max(100),redemptionWindowHours:$e.number().int().min(1).max(2160)}),F_=$e.object({title:$e.string().trim().min(1).max(80),description:$e.string().trim().min(1).max(240),buttonLabel:$e.string().trim().min(1).max(30)}),U_=$e.object({name:$e.string().trim().min(1).max(80),audience:D_,offer:N_,popup:F_}),nO=U_.extend({id:$e.string().min(1),projectId:$e.string().min(1),environment:iu,status:$e.enum(["draft","active","paused"]),updatedAt:$e.iso.datetime()}),rO=je.extend({id:$e.string().min(1),externalUserId:$e.string().min(1),name:$e.string().min(1),email:$e.union([$e.email(),$e.literal("")]),createdAt:$e.iso.datetime(),paymentStatus:$e.enum(["unpaid","paid"]),stripeCustomerId:$e.string().nullable()});import{z as wn}from"zod";var xd=wn.strictObject({itemKey:wn.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:wn.uuid(),includedAmount:wn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:wn.number().int().min(0).max(1e4),terms:ds,pricing:ai.optional(),unitAmountMinor:wn.number().int().min(0).max(1e8),productId:wn.string().min(1).max(255).nullable(),priceId:wn.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{ms(e.includedAmount,e.terms.units,e.quantity),pa({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as W}from"zod";var gs=W.object({id:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),productId:W.string().min(1).max(255),priceId:W.string().min(1).max(255),enabled:W.boolean()}).strict(),dO=W.object({productId:W.uuid(),name:W.string(),environment:W.enum(["sandbox","live"]),versions:W.array(W.object({id:W.uuid(),version:W.number().int().positive(),configuration:pi}).strict()),connections:W.array(W.object({id:W.uuid(),accountId:W.string()}).strict()),bindings:W.array(gs),seatBindings:W.array(gs.extend({key:W.string().regex(/^[a-z][a-z0-9_]{0,63}$/)}).strict()),featureBindings:W.array(gs.extend({internal_feature_id:W.uuid()}).strict()),limited:W.boolean()}).strict(),pO=W.discriminatedUnion("action",[W.strictObject({action:W.literal("bind_feature"),requestId:W.uuid(),productId:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),internal_feature_id:W.uuid(),priceId:W.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}),W.strictObject({action:W.literal("disable_feature"),productId:W.uuid(),bindingId:W.uuid()}),W.object({action:W.literal("bind_seat"),requestId:W.uuid(),productId:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),key:W.string().regex(/^[a-z][a-z0-9_]{0,63}$/),priceId:W.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),W.object({action:W.literal("disable_seat"),productId:W.uuid(),bindingId:W.uuid()}).strict(),W.object({action:W.literal("bind"),requestId:W.uuid(),productId:W.uuid(),productVersionId:W.uuid(),connectionId:W.uuid(),currency:W.string().regex(/^[A-Z]{3}$/),priceId:W.string().regex(/^price_[A-Za-z0-9]+$/).max(255)}).strict(),W.object({action:W.literal("disable"),productId:W.uuid(),bindingId:W.uuid()}).strict()]);import{z as me}from"zod";var Id=me.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Ad=me.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),mi=me.enum(["apple","google"]),M_=me.strictObject({id:me.uuid(),productVersionId:me.uuid(),priceId:me.uuid(),connectionId:mi,provider:mi,namespace:me.string().min(1).max(255),currency:ae,productId:Id,basePlanId:Ad.nullable(),enabled:me.boolean()}),gO=me.strictObject({productId:me.uuid(),publicId:me.string().min(1),name:me.string().min(1).max(80),environment:me.enum(["sandbox","live"]),versions:me.array(me.strictObject({id:me.uuid(),version:me.number().int().positive(),prices:me.array(me.strictObject({id:me.uuid(),currency:ae,amount:me.number().nonnegative(),interval:me.string().nullable()})).max(50),recurring:me.boolean()})).max(100),connections:me.array(me.strictObject({id:mi,provider:mi,applicationId:me.string().min(1).max(255)})).max(2),bindings:me.array(M_).max(500),limited:me.boolean()}),bO=me.discriminatedUnion("action",[me.strictObject({action:me.literal("bind"),requestId:me.uuid(),productId:me.uuid(),productVersionId:me.uuid(),priceId:me.uuid(),connectionId:mi,storeProductId:Id,basePlanId:Ad.nullable()}),me.strictObject({action:me.literal("disable"),productId:me.uuid(),bindingId:me.uuid()})]);import{z as be}from"zod";var Hn=be.iso.datetime({offset:!0}),wd=ge.refine(e=>/[1-9]/.test(e)),Pd=be.strictObject({interval:li.exclude(["lifetime"]),count:di}),B_=be.strictObject({action:be.literal("create"),requestId:be.uuid(),internal_feature_id:be.uuid(),entityId:be.uuid().nullable(),amount:wd.nullable(),expiresAt:Hn.nullable(),reset:Pd.nullable(),rollover:Wn.nullable(),nextResetAt:Hn.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"),Cd=be.discriminatedUnion("action",[B_,be.strictObject({action:be.literal("update"),requestId:be.uuid(),grantId:be.uuid(),revision:be.number().int().nonnegative(),amount:wd.nullable(),expiresAt:Hn.nullable(),rollover:Wn.nullable(),nextResetAt:Hn.nullable()}),be.strictObject({action:be.enum(["add","subtract","set_remaining"]),requestId:be.uuid(),grantId:be.uuid(),revision:be.number().int().nonnegative(),amount:ge}),be.strictObject({action:be.literal("revoke"),requestId:be.uuid(),grantId:be.uuid(),revision:be.number().int().nonnegative()})]),bs=be.strictObject({id:be.uuid(),internal_feature_id:be.uuid(),entityId:be.uuid().nullable(),amount:ge.nullable(),reset:Pd.nullable(),rollover:Wn.nullable(),nextResetAt:Hn.nullable(),startsAt:Hn,expiresAt:Hn.nullable(),revision:be.number().int().nonnegative(),revoked:be.boolean(),available:xt,held:xt,spent:xt}),Od=be.strictObject({customerId:be.uuid(),after:be.uuid().nullable(),limit:be.number().int().min(1).max(100)}),Ed=be.strictObject({rows:be.array(bs).max(100),nextCursor:be.uuid().nullable()});import{z as H}from"zod";var on=H.iso.datetime({offset:!0}),Td=H.strictObject({invoiceId:H.uuid(),after:H.string().min(1).max(180).nullable(),limit:H.number().int().min(1).max(100)}),L_=H.strictObject({kind:H.literal("product"),key:H.string(),productVersionId:H.uuid(),productName:H.string(),itemKey:H.string(),entityId:H.uuid().nullable(),quantity:H.number().int().positive(),subtotalMinor:H.string().regex(/^-?\d+$/),discountMinor:H.string().regex(/^\d+$/),taxMinor:H.string().regex(/^-?\d+$/).nullable(),totalMinor:H.string().regex(/^-?\d+$/),startsAt:on.nullable(),endsAt:on.nullable(),providerLineId:H.string().nullable(),providerItemId:H.string()}),Rd=H.strictObject({invoice:ci,items:H.array(H.discriminatedUnion("kind",[L_,H.strictObject({kind:H.literal("invoice_credit"),key:H.string(),internal_feature_id:H.uuid(),internal_credit_feature_id:H.uuid(),name:H.string(),units:ge,reserved:ge,amountMinor:fr,grossAmountMinor:fr,creditsAppliedMinor:fr,properties:Zt,cashPrice:An,providerItemId:H.string().nullable(),creditProviderItemId:H.string().nullable()}),H.strictObject({kind:H.literal("usage"),key:H.string(),internal_feature_id:H.uuid(),name:H.string(),units:ge,reserved:ge,amountMinor:fr,cashPrice:An})])).max(100),nextCursor:H.string().min(1).max(180).nullable()}),q_=H.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),_s=H.strictObject({from:on,to:on,entityId:H.uuid().optional(),snapshotAt:on.nullable(),after:H.strictObject({at:on,id:H.uuid(),position:H.number().int().nonnegative()}).nullable(),limit:H.number().int().min(1).max(100)}).refine(e=>Date.parse(e.from)<Date.parse(e.to)&&Date.parse(e.to)-Date.parse(e.from)<=366*864e5,"Statement range must be positive and at most 366 days").refine(e=>e.after===null||e.snapshotAt!==null,"A cursor requires the original snapshot time"),jd=H.strictObject({customerId:H.uuid(),entityId:H.uuid().nullable(),from:on,to:on,snapshotAt:on,totals:H.array(H.strictObject({internal_credit_feature_id:H.uuid(),name:H.string(),consumed:xt,refunded:xt,net:q_})).max(1e3),rows:H.array(H.strictObject({operationId:H.uuid(),position:H.number().int().nonnegative(),kind:H.enum(["consume","confirm","refund"]),originalId:H.uuid().nullable(),occurredAt:on,internal_feature_id:H.uuid(),entitlementName:H.string(),sourceId:H.uuid(),internal_credit_feature_id:H.uuid(),creditName:H.string(),units:uu,amount:xt,pricing:H.array(cu).max(12),properties:Zt})).max(100),nextCursor:_s.shape.after});import{z as Rt}from"zod";var TO=Rt.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=Rt.object({operationId:Rt.uuid(),windowId:Rt.uuid(),customerId:Rt.uuid(),entityId:Rt.uuid().nullable(),internal_feature_id:Rt.uuid(),entitlementKey:$i,basis:Rt.enum(["usage","credits"]),interval:Rt.enum(["day","week","month","year"]),filter:Zt,startsAt:Rt.iso.datetime({offset:!0}),endsAt:Rt.iso.datetime({offset:!0}),limit:ge.refine(e=>/[1-9]/.test(e)),used:xt,reserved:xt,threshold:Rt.number().positive().max(1)}).strict(),RO=kd.omit({threshold:!0,limit:!0}).extend({alertThreshold:ge.refine(e=>/[1-9]/.test(e)),limit:ge.nullable()}),jO=kd.omit({limit:!0}).extend({includedAllowance:Rt.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>/[1-9]/.test(e))});import{z as X}from"zod";var Nd=X.object({customerId:X.uuid()}).strict(),Fd=X.discriminatedUnion("action",[X.object({customerId:X.uuid(),requestId:X.uuid(),action:X.literal("assign"),poolId:X.uuid(),memberCustomerId:X.uuid()}).strict(),X.strictObject({customerId:X.uuid(),requestId:X.uuid(),action:X.literal("assign_entity"),poolId:X.uuid(),entityId:X.uuid()}),X.object({customerId:X.uuid(),requestId:X.uuid(),action:X.literal("release"),poolId:X.uuid(),slotId:X.uuid()}).strict()]),fi=X.number().int().nonnegative(),ys=X.iso.datetime({offset:!0}),Ss=X.strictObject({internalId:X.uuid(),id:X.string(),name:X.string().nullable(),version:X.number().int().positive()}),Dd=X.enum(["active","past_due"]),vs=X.strictObject({customerId:X.uuid(),licenses:X.array(X.strictObject({id:X.uuid(),linkId:X.uuid(),parent:X.strictObject({customerProductId:X.uuid(),status:Dd,product:Ss}),product:Ss,planLicense:X.strictObject({id:X.uuid(),prepaidOnly:X.boolean(),isCustom:X.boolean()}).nullable(),granted:fi,included:fi,paidQuantity:fi,usage:fi,remaining:fi,createdAt:ys}).refine(e=>e.granted===e.included+e.paidQuantity&&e.granted===e.usage+e.remaining,"Granted seats are included plus paid, and usage plus remaining")).max(2e3),assignments:X.array(X.strictObject({id:X.uuid(),linkId:X.uuid(),status:Dd,product:Ss,entity:X.strictObject({internalId:X.uuid(),id:X.string().nullable(),name:X.string().nullable()}).nullable(),beneficiary:X.strictObject({internalId:X.uuid(),id:X.string().nullable(),name:X.string().nullable()}).nullable(),startedAt:ys.nullable(),endedAt:ys.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:X.boolean()});import{z as Pn}from"zod";var V_=Pn.object({name:Pn.string().trim().min(1,"\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0").max(80),slug:Pn.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")}),Ud=Pn.object({description:Pn.string().trim().max(240)}),UO=Pn.object({project:V_.extend({id:Pn.string().min(1)}),environments:Pn.object({sandbox:Ud,live:Ud})});import{z as Md}from"zod";var hr={funnelId:Md.uuid().optional(),funnelVersionId:Md.uuid().optional()};import{z as qe}from"zod";import{z as Ce}from"zod";import{z as Ne}from"zod";var $_=Ne.discriminatedUnion("action",[Ne.strictObject({action:Ne.literal("create"),couponId:Ne.uuid(),productBindingId:Ne.uuid(),storeOfferId:Ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ne.enum(["introductory","promotional"])}),Ne.strictObject({action:Ne.literal("set_enabled"),id:Ne.uuid(),revision:Ne.number().int().nonnegative(),enabled:Ne.boolean()})]),G_=Ne.array(Ne.strictObject({id:Ne.uuid(),couponId:Ne.uuid(),productBindingId:Ne.uuid(),storeOfferId:Ne.string().min(1).max(255).nullable(),storeOfferType:Ne.enum(["introductory","promotional"]),enabled:Ne.boolean(),revision:Ne.number().int().nonnegative()})).max(500),Cn=Ne.strictObject({offerKind:Ne.enum(["none","introductory","promotional"]),offerId:Ne.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ne.number().int().min(0).max(1e8),trialDays:Ne.number().int().min(1).max(730).nullable()}).superRefine((e,t)=>{(e.offerKind==="none"&&(e.offerId!==null||e.discountMinor!==0||e.trialDays!==null)||e.trialDays!==null&&e.discountMinor!==0)&&t.addIssue({code:"custom",message:"Select one store purchase option with its exact terms"})}),Bd=Ne.record(Ne.uuid(),Cn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");function W_(e,t){if(e.nativeOffers!==void 0)return Bd.parse(e.nativeOffers)[t]}function K_(e,t,n,r){return Cn.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 xs=Ce.object({type:Ce.literal("native_purchase"),receiptId:Ce.uuid(),orderId:Ce.uuid(),productVersionId:Ce.uuid(),provider:Ce.enum(["apple","google"]),productId:Ce.string().min(1).max(255),productKind:gu,replacement:Ce.strictObject({sourceOrderId:Ce.uuid(),sourceProductId:Ce.string().min(1).max(255),policy:Ce.enum(["apple_store","google_full_price"]),sourceAccountTokens:Ce.array(Ce.uuid()).max(50)}).nullable(),appAccountToken:Ce.uuid().optional(),obfuscatedAccountId:Ce.string().min(1).max(64).optional(),obfuscatedProfileId:Ce.uuid().optional(),basePlanId:Ce.string().min(1).max(255).optional(),offerId:Ce.string().min(1).max(255).optional(),offerKind:Ce.enum(["none","introductory","promotional"]),currency:ae,catalogAmountMinor:Ce.number().int().nonnegative().max(1e8),discountMinor:Ce.number().int().nonnegative().max(1e8),trialDays:Ce.number().int().min(1).max(730).nullable(),seatBundle:Ce.array(Ce.strictObject({key:Ce.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Ce.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Ce.strictObject({offerId:Ce.string().min(1).max(255),keyId:Ce.string().min(1).max(255),nonce:Ce.uuid(),signature:Ce.string().min(1).max(1024),timestamp:Ce.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as f}from"zod";import{z as ue}from"zod/v4";import{z as H_}from"zod/v4";var Q_=H_.registry(),{BillingInterval:Ld}=(()=>{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:Z_}=(e=>({DisplaySchema:e.object({primary_text:e.string().meta({description:"Main display text (e.g. '$10' or '100 messages')."}),secondary_text:e.string().optional().meta({description:"Secondary display text (e.g. 'per month' or 'then $0.5 per 100')."})})}))(ue),{withSpecDefault:Y_}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Q_),{COMMON:qd}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:J_}={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:X_}=(e=>({COMMON_SET:new Set(e)}))(qd),{hasNoDuplicateCurrencies:Vd}={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:$d}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:z_}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(ue),{Infinite:ey}={Infinite:"inf"},{TierBehavior:ty}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Gd}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:ny}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:ry}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:iy}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:ay}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(ue),{ApiCreditTierSchema:Wd}=(e=>({ApiCreditTierSchema:e.object({to:e.union([e.number().positive(),e.enum(["inf"])]).meta({description:"Inclusive upper usage boundary for this graduated tier. The final tier must be 'inf'."}),credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group within this tier."})})}))(ue),{VIOLATION_MESSAGES:oy}={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:Kd}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(ue),{ModelMarkupsSchema:sy}=((e,t)=>({ModelMarkupsSchema:e.record(e.string().regex(/.+\/.+/,'Model keys are "<provider>/<model>", e.g. "openai/gpt-4o" or "custom/my-model".'),t.extend({markup:e.number().min(-100).optional(),input_cost:e.number().min(0).optional(),output_cost:e.number().min(0).optional()})).nullish()}))(ue,Kd),{InvoiceUsageEntrySchema:cy}=(e=>({InvoiceUsageEntrySchema:e.object({feature_id:e.string().meta({description:"The metered feature whose units are being converted."}),quantity:e.number().nonnegative().meta({description:"Billable units of the metered feature. Converted to the credit-system feature through its rate card."}),properties:e.record(e.string(),e.unknown()).optional().meta({description:"Event properties used to pick the rate card dimension and multipliers."})}).strict()}))(ue),{AttachDiscountSchema:Hd}=(e=>({AttachDiscountSchema:e.object({reward_id:e.string().optional().meta({description:"The ID of the reward to apply as a discount."}),promotion_code:e.string().optional().meta({description:"The promotion code to apply as a discount."})}).refine(n=>n.reward_id||n.promotion_code,{message:"Either reward_id or promotion_code must be provided."}).meta({title:"AttachDiscount",description:"A discount to apply. Can be either a reward ID or a promotion code."})}))(ue),{CustomLineItemSchema:uy}=(e=>({CustomLineItemSchema:e.object({amount:e.number().meta({description:"Amount in dollars for this line item (e.g. 10.50). Can be negative for credits."}),description:e.string().meta({description:"Description for the line item."})})}))(ue),{UnixMsTimestampSchema:ly}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(ue),{CreateInvoicePreviewLineSchema:dy}=(e=>({CreateInvoicePreviewLineSchema:e.object({plan_id:e.string().nullable(),feature_id:e.string().nullable(),description:e.string(),amount:e.number(),amount_after_discounts:e.number(),quantity:e.number().nullable(),prorated:e.boolean(),period_start:e.number().nullable(),period_end:e.number().nullable()})}))(ue),{ReissueInvoiceParamsSchema:Is}=(e=>({ReissueInvoiceParamsSchema:e.object({invoice_id:e.string().meta({description:"The Autumn invoice ID to void and replace.",example:"inv_2b3c4d5e6f7g8h"}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer and memo are applied to the replacement invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the replacement invoice. Defaults to the original invoice's due date; required when that date has already passed."}),update_customer_email:e.email().optional().meta({description:"Updates the customer's billing email before the replacement is issued, so Stripe sends the new invoice to this address."})})}))(ue),{InvoiceModeParamsSchema:On}=(e=>({InvoiceModeParamsSchema:e.object({enabled:e.boolean().meta({description:"When true, creates an invoice and sends it to the customer instead of charging their card immediately. Uses Stripe's send_invoice collection method."}),enable_plan_immediately:e.boolean().default(!1).meta({description:"If true, enables the plan immediately even though the invoice is not paid yet."}),finalize:e.boolean().default(!0).meta({description:"If true, finalizes the invoice so it can be sent to the customer. If false, keeps it as a draft for manual review."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template (configured in billing settings) whose footer (e.g. bank details) is applied to the invoice."}),net_terms_days:e.number().int().positive().optional().meta({description:"Number of days the customer has to pay the invoice before it is due (Stripe days_until_due)."})}).meta({title:"InvoiceMode",description:"Invoice mode configuration. Creates an invoice instead of charging the card immediately."})}))(ue),{InvoiceTemplateSchema:py}=(e=>({InvoiceTemplateSchema:e.object({id:e.string().meta({description:"Unique identifier for the invoice template."}),name:e.string().meta({description:"User-defined name to distinguish this template when sending an invoice."}),footer:e.string().optional().meta({description:"Footer text rendered on the invoice, typically bank details so customers can pay directly."}),memo:e.string().optional().meta({description:"Memo shown near the top of the invoice (Stripe invoice description), e.g. a contact line for payment questions."}),net_terms_days:e.number().int().positive().optional().meta({description:"Default number of days the customer has to pay before the invoice is due. Overridable when sending."}),created_at:e.number().optional().meta({description:"Timestamp (ms) when the template was created."})})}))(ue),{BasePriceSchema:my}=((e,t,n)=>({BasePriceSchema:e.object({amount:e.number().meta({description:"Base price amount for the plan, in major currency units (e.g. dollars)."}),interval:e.enum(t).meta({description:"Billing interval (e.g. 'month', 'year')."}),interval_count:e.number().optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),display:n.optional().meta({description:"Display text for showing this price in pricing pages."})})}))(ue,Ld,Z_),{CURRENCY_CODES:fy}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(qd,J_,X_),{ApiPriceProcessorsSchema:Qd}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(ue,z_),{AllocatedBillingFieldSchema:hy}=((e,t)=>({AllocatedBillingFieldSchema:e.enum(t).optional().meta({internal:!0,description:"How an allocated usage_based price bills mid-cycle quantity changes. 'arrear' (default) bills at period end. 'prorated_legacy' is only returned for prices still on the legacy immediate-proration behavior; omit it to migrate the price to 'arrear'."})}))(ue,ny),{CreditDimensionNameSchema:gy}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(ue,ry,iy),{ApiCreditMatchSchema:Zd}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(ay),{findCreditTierViolations:by}=(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}}))(oy),{ApiCreditMultiplierSchema:_y}=((e,t)=>({ApiCreditMultiplierSchema:e.object({match:t,factor:e.number().positive().optional().meta({description:"Multiplies the matched rate. All matching multipliers stack."}),add:e.number().optional().meta({description:"Added to the rate after every factor is applied, in credits per billing-unit group."})}).strict().refine(r=>r.factor!==void 0||r.add!==void 0,{message:"A multiplier needs a factor or an add."})}))(ue,Zd),{ProviderMarkupsSchema:yy}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(ue,Kd),{InvoiceFeatureQuantitySchema:Yd}=((e,t,n)=>({InvoiceFeatureQuantitySchema:e.object({feature_id:e.string().meta({description:"The feature to bill."}),billing_behavior:e.enum(t).meta({description:"Which of the feature's prices to use: 'prepaid' or 'usage_based'."}),quantity:e.number().nonnegative().optional().meta({description:"Billable feature units in total, exclusive of any included usage. Not per seat or per entity. For a credit-system feature this is the number of credits."}),usage:e.array(n).optional().meta({description:"For credit-system features: billable units of the source features, converted through the credit rate card. Mutually exclusive with quantity."}),prorate:e.boolean().optional().meta({description:"Whether to prorate this line against period_start / period_end. Defaults to true for prepaid and false for usage-based."})}).strict().refine(i=>i.quantity!==void 0!=(i.usage!==void 0),{message:"Provide exactly one of quantity or usage."})}))(ue,Gd,cy),{CreateInvoicePreviewSchema:As}=((e,t)=>({CreateInvoicePreviewSchema:e.object({currency:e.string(),lines:e.array(t),subtotal:e.number(),discount_total:e.number(),tax:e.object({total:e.number(),amount_inclusive:e.number(),amount_exclusive:e.number(),status:e.enum(["complete","incomplete"])}).nullable(),total:e.number(),due_date:e.number().nullable()})}))(ue,dy),{SUPPORTED_SET:Sy}=(e=>({SUPPORTED_SET:new Set(e)}))(fy),{ApiCreditDimensionBaseSchema:vy}=((e,t)=>({ApiCreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional().meta({description:"Breaks ties between dimensions that match the same number of keys. Higher wins."})})}))(ue,Zd),{refineGraduatedTiers:Jd}=(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"]})}}))(by),{ApiFeatureMarkupsOverrideSchema:xy}=((e,t,n)=>({ApiFeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional().meta({description:"Default percentage markup for customers on this plan. Use -100 to make usage free."}),provider_markups:t.meta({description:"Per-provider markup percentages for customers on this plan."}),model_markups:n.meta({description:"Per-model markup overrides for customers on this plan."})})}))(ue,yy,sy),{isValidCurrencyCode:Iy}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Sy),{ApiCreditDimensionSchema:Ay}=((e,t,n,r)=>({ApiCreditDimensionSchema:e.union([t.extend({tier_behavior:e.literal("graduated"),tiers:e.array(n).min(1)}).strict().superRefine(r),t.extend({credit_cost:e.number().min(0).meta({description:"Credits consumed per billing-unit group when this dimension matches."})}).strict()])}))(ue,vy,Wd,Jd),{CurrencyCodeSchema:Xd}=((e,t)=>({CurrencyCodeSchema:e.string().refine(t,"must be a Stripe-supported currency code").meta({description:"Three-letter Stripe-supported currency code (e.g. 'eur', 'gbp')."})}))(ue,Iy),{AdditionalCurrencyTierSchema:wy}=((e,t)=>({AdditionalCurrencyTierSchema:e.object({currency:t,amount:e.number().optional().meta({description:"Per-unit amount for this tier in this currency."}),flat_amount:e.number().optional().meta({description:"Flat amount for this tier in this currency, if the tier uses one."})}).refine(r=>r.amount!==void 0||r.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]})}))(ue,Xd),{ApiCreditSchemaItemBaseSchema:zd}=((e,t,n,r)=>({ApiCreditSchemaItemBaseSchema:e.object({metered_feature_id:e.string().nonempty().meta({description:"ID of the metered feature that draws from this credit system."}),billing_units:e.number().positive().optional().meta({description:"Number of metered-feature units priced together. Defaults to one when omitted."}),dimensions:e.record(t,n).optional().meta({description:"Named rates chosen by event properties. The most specific match sets the rate; with no match the item's own rate applies."}),multipliers:e.record(t,r).optional().meta({description:"Named adjustments chosen by event properties. Every match applies: factors multiply, then adds are summed."})})}))(ue,gy,Ay,_y),{ApiFlatCreditSchemaItemSchema:Py}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(zd,ue),{AdditionalCurrencyPriceSchema:Cy}=((e,t)=>({AdditionalCurrencyPriceSchema:e.object({currency:t,amount:e.number().meta({description:"Price amount in this currency. Set explicitly per currency, not converted from the base amount."})})}))(ue,Xd),{AdditionalCurrencyTierArraySchema:Oy}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(ue,wy,Vd,$d),{ApiGraduatedCreditSchemaItemSchema:Ey}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(zd,ue,Wd,Jd),{AdditionalCurrencyPriceArraySchema:ep}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(ue,Cy,Vd,$d),{ApiUsageTierWithCurrenciesSchema:Ty}=((e,t,n)=>({ApiUsageTierWithCurrenciesSchema:e.object({to:e.number().or(e.literal(t)),amount:e.number().optional(),flat_amount:e.number().optional(),additional_currencies:n.optional().meta({description:"Per-currency amounts for this tier. Tier boundaries ('to') are shared across all currencies."})}).refine(i=>i.amount!==void 0||i.flat_amount!==void 0,{message:"Either amount or flat_amount, or both must be defined",path:["amount","flat_amount"]}).transform(i=>({...i,amount:i.amount??0})).pipe(e.object({to:e.number().or(e.literal(t)),amount:e.number(),flat_amount:e.number().optional(),additional_currencies:n.optional()}))}))(ue,ey,Oy),{ApiCreditSchemaItemSchema:Ry}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(ue,Ey,Py),{BasePriceParamsSchema:jy}=((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."})}))(my,Y_,ue,ep),{PlanItemPriceParamsSchema:ky}=((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."})})}))(ue,ep,Ty,ty,Ld,Gd,hy),{ApiFeatureOverrideSchema:Dy}=((e,t,n)=>({ApiFeatureOverrideSchema:e.strictObject({credit_schema:e.array(t).optional().meta({description:"For credit system features: replaces the feature's credit_schema entirely for customers on this plan."}),markups:n.optional().meta({description:"For AI credit system features: replaces the feature's markup chain entirely for customers on this plan. An unset level means no markup at that level rather than inheriting the feature's."})})}))(ue,Ry,xy),{InvoiceBasePriceParamsSchema:tp}=((e,t)=>({InvoiceBasePriceParamsSchema:e.pick({amount:!0,interval:!0,interval_count:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(jy,Qd),{InvoiceItemPriceParamsSchema:Ny}=((e,t)=>({InvoiceItemPriceParamsSchema:e.pick({amount:!0,tiers:!0,tier_behavior:!0,interval:!0,interval_count:!0,billing_units:!0,billing_method:!0}).extend({processors:t.optional().meta({description:"Bill this line under an existing Stripe price instead of an inline one."})}).strict()}))(ky,Qd),{InvoiceLicenseQuantitySchema:Fy}=((e,t,n)=>({InvoiceLicenseQuantitySchema:e.object({license_plan_id:e.string().meta({description:"The license plan linked to the parent plan."}),quantity:e.number().int().nonnegative().meta({description:"Billable seats, exclusive of any included seats."}),customize:e.object({price:t.nullable().optional()}).strict().optional().meta({description:"Override the license's per-seat price on this invoice."}),feature_quantities:e.array(n).optional().meta({description:"Feature charges priced through the license plan."}),prorate:e.boolean().optional().meta({description:"Whether to prorate seat charges against period_start / period_end. Defaults to true."})}).strict()}))(ue,tp,Yd),{InvoiceCustomizeItemSchema:Uy}=((e,t,n)=>({InvoiceCustomizeItemSchema:e.object({feature_id:e.string().meta({description:"The feature whose pricing is overridden on this invoice."}),price:t.optional().meta({description:"Pricing to use for this feature on this invoice."}),feature_override:n.pick({credit_schema:!0}).strict().optional().meta({description:"For credit-system features: a credit rate card to use when converting `usage` on this invoice."})}).strict()}))(ue,Ny,Dy),{InvoiceCustomizeSchema:My}=((e,t,n)=>({InvoiceCustomizeSchema:e.object({price:t.nullable().optional().meta({description:"Override the plan's base price for this invoice. Pass null or an amount of 0 to omit the base price line."}),items:e.array(n).optional().meta({description:"Override feature pricing for this invoice. Only pricing fields are accepted; grants, resets and rollovers are not part of an invoice."})}).strict().meta({title:"InvoiceCustomize",description:"Pricing overrides applied to this invoice only. The catalog and the customer's plan are not changed."})}))(ue,tp,Uy),{InvoicePlanParamsSchema:By}=((e,t,n,r,i)=>({InvoicePlanParamsSchema:e.object({plan_id:e.string().meta({description:"The catalog plan (or variant) whose pricing to use."}),version:e.number().optional().meta({description:"Plan version. Defaults to the active version."}),customize:t.optional(),feature_quantities:e.array(n).optional(),license_quantities:e.array(r).optional(),discounts:e.array(i).optional().meta({description:"Discounts applied only to this plan's lines."}),prorate:e.boolean().optional().meta({description:"Whether to prorate the base price against period_start / period_end. Defaults to true."})}).strict()}))(ue,My,Yd,Fy,Hd),{CreateInvoiceParamsSchema:gr}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(ue,By,uy,Hd,ly);var ip=f.strictObject({requestId:f.uuid(),predecessorOperationId:f.uuid().optional(),invoiceMode:On.optional(),entityId:f.uuid().optional(),billingSubscriptionId:f.uuid().optional(),newBillingSubscription:f.literal(!0).optional(),offerId:f.uuid().optional(),nativeOffer:Cn.optional(),plans:f.array(f.strictObject({productVersionId:f.uuid(),seatQuantities:f.record(an,f.number().int().min(0).max(1e4)).optional(),featureQuantities:f.record(f.uuid(),f.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:f.enum(["stripe","apple","google"]),currency:ae}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(e.provider==="stripe"||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||e.provider!=="stripe"&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||e.provider==="stripe"&&!e.billingSubscriptionId,"A new billing subscription requires Stripe and no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),Zn=f.strictObject({operationId:f.uuid()}),et=f.number().int().min(0).max(1e8),Ly=f.strictObject({lineId:f.uuid(),productVersionId:f.uuid(),productName:f.string().min(1).max(80),interval:f.enum(["free","week","month","year","one_time"]),intervalCount:f.number().int().min(1).max(156).optional(),baseAmountMinor:et,seats:f.array(f.strictObject({key:an,quantity:f.number().int().min(0).max(1e4),includedQuantity:f.number().int().min(0).max(1e4),maximumQuantity:f.number().int().min(0).max(1e4),unitAmountMinor:et})).max(20),prepaid:f.array(xd).max(100).optional(),catalogAmountMinor:et,trial:f.strictObject({days:f.number().int().min(1).max(730),cardRequired:f.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+pa({quantity:n.quantity,unitAmountMinor:n.unitAmountMinor,...n.pricing===void 0?{}:{pricing:n.pricing}}),0)===e.catalogAmountMinor,"Quote must retain its published base price and component quantities"),ap=f.string().regex(/^[A-Za-z0-9_-]{1,200}$/),qy=f.strictObject({id:ap,name:f.string().min(1).max(40),percent_off:f.number().gt(0).max(100).optional(),amount_off:f.number().int().positive().optional(),currency:f.string().regex(/^[a-z]{3}$/).optional(),duration:f.enum(["once","repeating","forever"]),duration_in_months:f.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Vy=f.strictObject({subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:f.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:f.array(f.strictObject({id:f.string(),price_id:f.string(),quantity:f.number().int().nonnegative(),discounts:f.array(f.strictObject({id:f.string(),coupon:f.string(),start:f.number(),end:f.number().nullable()})).optional()})).min(1).max(100),prorationDate:f.number().int().nonnegative(),amountMinor:f.number().int().positive(),periodStartMs:f.number(),periodEndMs:f.number()}),op=f.strictObject({invoiceMode:On.optional(),append:Vy.optional(),provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),mode:f.enum(["payment","subscription"]),lineItems:f.array(f.strictObject({price:f.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:f.number().int().min(1).max(1e4),priceId:f.uuid(),productName:f.string().min(1).max(80),amountMinor:f.number().int().min(0).max(1e8),currency:f.string().regex(/^[a-z]{3}$/),interval:f.enum(["week","month","year","one_off"]),intervalCount:f.number().int().min(1).max(52),slot:f.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:f.strictObject({mode:f.enum(["graduated","volume"]),tiers:f.array(f.strictObject({upTo:f.number().int().min(1).max(1e6).nullable(),unitAmountMinor:f.number().int().min(0).max(1e8),flatAmountMinor:f.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:f.array(f.strictObject({coupon:ap,terms:qy})).max(1),trialPeriodDays:f.number().int().min(1).max(730).nullable(),metadata:f.strictObject({grooveCheckoutId:f.uuid(),grooveCustomerId:f.uuid()}),expiresAt:f.iso.datetime({offset:!0})}),hi=f.strictObject({operationId:f.uuid(),entityId:f.uuid().nullable(),billingSubscriptionId:f.uuid().nullable(),discount:f.strictObject({offerId:f.uuid(),couponId:f.uuid(),discount:mr,duration:Yt,amountMinor:et,allocations:f.array(f.strictObject({productVersionId:f.uuid(),amountMinor:et})).min(1).max(20),expiresAt:f.iso.datetime({offset:!0})}).nullable(),charge:f.strictObject({effectiveAt:f.iso.datetime({offset:!0}),periodEndsAt:f.iso.datetime({offset:!0}),debitMinor:et,discountMinor:et,taxMinor:et,totalMinor:et}).nullable(),expiresAt:f.iso.datetime({offset:!0}),provider:f.enum(["stripe","apple","google"]),nativeOffer:Cn.optional(),currency:ae,lines:f.array(Ly).min(1).max(20),catalogAmountMinor:et,automaticTax:f.boolean(),execution:op.nullable()}).refine(e=>e.provider==="stripe"?e.lines[0]?.trial?.cardRequired===!1&&!e.execution?.invoiceMode?.enabled?e.execution===null&&e.discount===null:e.execution!==null&&e.execution.metadata.grooveCheckoutId===e.operationId&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.mode===(e.lines.some(t=>!["one_time","free"].includes(t.interval))?"subscription":"payment")&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&(e.execution.executor==="indiana"||e.execution.lineItems.every(t=>t.price!==null))&&e.execution.discounts.every(t=>t.coupon===t.terms.id)&&e.execution.discounts.length===(e.discount?1:0)&&e.execution.discounts.every(t=>e.discount!==null&&(t.coupon===e.discount.couponId||e.discount.discount.type==="amount"&&t.coupon===`${e.discount.couponId}_credit_${e.discount.offerId}_${t.terms.amount_off}`&&t.terms.amount_off===e.discount.discount.amountOffCents&&t.terms.currency?.toUpperCase()===e.currency&&t.terms.duration==="once")):e.execution===null,"Stripe execution must carry the quote identity, expiry, mode, trial and held coupon").refine(e=>(!e.discount||!e.billingSubscriptionId&&(e.provider==="stripe"||e.discount.duration.type==="once")&&e.discount.amountMinor<=e.catalogAmountMinor&&e.discount.allocations.length===e.lines.length&&e.discount.allocations.every((t,n)=>{let r=e.lines[n];return r!==void 0&&t.productVersionId===r.productVersionId&&t.amountMinor<=r.catalogAmountMinor})&&e.discount.allocations.reduce((t,n)=>t+n.amountMinor,0)===e.discount.amountMinor)&&(e.provider==="stripe"?e.nativeOffer===void 0:e.nativeOffer!==void 0&&e.lines.length===1&&e.nativeOffer.discountMinor<=e.catalogAmountMinor&&e.nativeOffer.trialDays===(e.lines[0]?.trial?.days??null)&&(!e.discount||e.nativeOffer.discountMinor===e.discount.amountMinor))&&(!e.charge||e.billingSubscriptionId!==null&&e.charge.totalMinor===e.charge.debitMinor-e.charge.discountMinor+e.charge.taxMinor&&e.charge.discountMinor<=e.charge.debitMinor&&Date.parse(e.charge.periodEndsAt)>Date.parse(e.charge.effectiveAt))&&new Set(e.lines.map(t=>t.lineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.catalogAmountMinor,0)===e.catalogAmountMinor,"Quote lines must conserve the catalog amount"),br=f.strictObject({operationId:f.uuid(),orderId:f.uuid(),append:f.boolean().optional(),invoiceMode:f.boolean().optional(),status:f.enum(["pending","complete","cancelled","failed"]),executor:f.enum(["indiana","merchant"]),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:op.nullable(),currency:ae,catalogAmountMinor:et,taxMinor:et,totalMinor:f.number().int().min(0).max(2e8).nullable(),quoteFinalized:f.boolean(),nativePurchase:xs.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"),_a=f.strictObject({enabled:f.literal(!0),featureIds:f.array(f.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),sp=f.strictObject({requestId:f.uuid(),invoiceMode:On.optional(),membershipId:f.uuid(),carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),membershipIds:f.array(f.uuid()).min(1).max(20).optional(),prorationBehavior:f.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:f.enum(["immediate","renewal","store"]),change:f.discriminatedUnion("type",[f.strictObject({type:f.literal("plan"),productVersionId:f.uuid()}),f.strictObject({type:f.literal("seats"),licenseKey:an,quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("quantity"),internal_feature_id:f.uuid(),quantity:f.number().int().min(0).max(1e4)}),f.strictObject({type:f.literal("cancel")}),f.strictObject({type:f.literal("uncancel")}),f.strictObject({type:f.literal("billing_cycle"),billingCycleAnchor:f.union([f.literal("now"),f.number().int().positive().max(0xe677d21fdbff)])})])}).refine(e=>e.timing!=="store"||e.change.type==="plan","Store timing applies to a native plan replacement").refine(e=>e.change.type!=="billing_cycle"||e.timing===(e.change.billingCycleAnchor==="now"?"immediate":"renewal"),"Use immediate for now and renewal for a future millisecond anchor").refine(e=>!e.membershipIds||["cancel","uncancel"].includes(e.change.type)&&e.membershipIds.includes(e.membershipId)&&new Set(e.membershipIds).size===e.membershipIds.length,"Grouped actions require unique cancel/uncancel targets including the primary membership").refine(e=>!e.carryOverBalances&&!e.carryOverUsages||e.change.type==="plan"&&e.timing==="immediate","Carry applies only to immediate upgrades").refine(e=>!e.prorationBehavior||e.change.type==="quantity","prorationBehavior applies to prepaid quantity changes"),ba=f.string().regex(/^price_[A-Za-z0-9]+$/),np=f.strictObject({grooveUpdateId:f.uuid(),grooveCustomerId:f.uuid()}),rp=f.strictObject({price:ba.nullable(),priceId:f.uuid().optional(),quantity:f.number().int().min(0).max(1e4)}),cp=f.strictObject({provider:f.literal("stripe"),invoiceMode:On.optional(),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:f.string().regex(/^sub_[A-Za-z0-9]+$/),action:f.enum(["update","cancel","schedule","release"]),update:f.strictObject({items:f.array(rp).max(20),remove:f.array(ba).max(20),restoreItems:f.array(f.strictObject({price:ba,quantity:f.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:f.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:f.number().int().positive().optional(),paymentBehavior:f.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:f.boolean().optional(),clearCancelAt:f.literal(!0).optional(),billingCycleAnchorNow:f.literal(!0).optional(),metadata:np}).nullable(),cancel:f.strictObject({prorate:f.literal(!1),invoiceNow:f.literal(!1)}).nullable(),schedule:f.strictObject({currentItems:f.array(f.strictObject({price:ba,quantity:f.number().int().min(0).max(1e4)})).max(20),nextItems:f.array(rp).min(1).max(20),switchAt:f.number().int().positive(),interval:f.enum(["week","month","year"]),intervalCount:f.number().int().min(1).max(52),resetBillingCycleAnchor:f.literal(!0).optional(),metadata:np}).nullable(),release:f.strictObject({schedule:f.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:f.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),ws=f.strictObject({carryOverBalances:_a.optional(),carryOverUsages:_a.optional(),operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),expiresAt:f.iso.datetime({offset:!0}),currency:ae,creditMinor:et,debitMinor:et,discountMinor:et,taxMinor:et,totalMinor:et,retainedProductVersionIds:f.array(f.uuid()).max(19),execution:cp}),$y=f.strictObject({operationId:f.uuid(),invoiceMode:f.boolean().optional(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:f.enum(["immediate","renewal"]),effectiveAt:f.iso.datetime({offset:!0}),checkoutUrl:f.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:f.enum(["indiana","merchant"]),execution:cp.nullable()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Gy=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),timing:f.literal("store"),effectiveAt:f.null(),expiresAt:f.iso.datetime({offset:!0}),currency:ae,creditMinor:f.null(),debitMinor:f.null(),discountMinor:f.null(),taxMinor:f.null(),totalMinor:f.null(),retainedProductVersionIds:f.array(f.uuid()).max(19),store:f.strictObject({provider:f.enum(["apple","google"]),productId:f.string().min(1).max(255),catalogAmountMinor:et,policy:f.enum(["apple_store","google_full_price"])})}),Wy=f.strictObject({operationId:f.uuid(),membershipId:f.uuid(),productVersionId:f.uuid(),status:f.enum(["prepared","pending","effective","cancelled","failed"]),timing:f.literal("store"),effectiveAt:f.iso.datetime({offset:!0}).nullable(),checkoutUrl:f.null(),nativePurchase:xs.nullable()}),up=f.union([ws,Gy]),Ps=f.union([$y,Wy]),gi=f.number().int().positive().max(2e8),Qn=f.number().int().min(0).max(2e8),lp=f.strictObject({requestId:f.uuid(),invoiceId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:gi.optional(),entitlementAction:f.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),dp=f.strictObject({provider:f.literal("stripe"),executor:f.enum(["indiana","merchant"]),accountId:f.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:f.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:gi,currency:f.string().regex(/^[a-z]{3}$/),metadata:f.strictObject({indianaRefundId:f.uuid()}),idempotencyKey:f.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:f.array(f.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),pp=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().regex(/^in_[A-Za-z0-9]+$/),currency:ae,paidMinor:Qn,refundedMinor:Qn,pendingMinor:Qn,amountMinor:gi,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),revokes:f.strictObject({customerProductIds:f.array(f.uuid()).max(100),subscriptionIds:f.array(f.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),execution:dp,expiresAt:f.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&e.execution.invoice===e.providerInvoiceId&&e.execution.metadata.indianaRefundId===e.operationId&&e.execution.currency===e.currency.toLowerCase()&&(e.entitlementAction==="revoke"||e.revokes.customerProductIds.length===0&&e.revokes.subscriptionIds.length===0),"Refund quote must stay within the refundable amount and match its execution"),ya=f.strictObject({operationId:f.uuid(),invoiceId:f.uuid(),providerInvoiceId:f.string().regex(/^in_[A-Za-z0-9]+$/),status:f.enum(["quoted","pending","succeeded","failed","expired"]),executor:f.enum(["indiana","merchant"]),currency:ae,amountMinor:gi,mode:f.enum(["full","partial"]),entitlementAction:f.enum(["retain","revoke"]),refundId:f.string().regex(/^(re|pyr)_[A-Za-z0-9]+$/).nullable(),execution:dp.nullable(),failureReason:f.string().min(1).max(200).nullable(),createdAt:f.iso.datetime({offset:!0}),completedAt:f.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),oE=f.strictObject({invoiceId:f.uuid(),currency:ae,paidMinor:Qn,refundedMinor:Qn,pendingMinor:Qn,refundableMinor:Qn,executor:f.enum(["indiana","merchant"]).nullable(),canRefund:f.boolean(),operations:f.array(ya).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),sE=f.strictObject({requestId:f.uuid(),mode:f.enum(["full","partial"]),amountMinor:gi.optional(),entitlementAction:f.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var mp=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"),Sa=qe.strictObject({batchId:qe.uuid()}),Ky=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:ws.nullable(),managementUrl:qe.url().nullable(),failureCode:qe.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),bi=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(Ky).min(1).max(100)});import{z as he}from"zod";var Hy=he.string().trim().min(1).max(240),Cs={requestId:he.uuid(),reason:Hy},va=he.discriminatedUnion("action",[he.strictObject({...Cs,action:he.literal("start"),productVersionId:he.uuid(),entityId:he.uuid().optional(),days:he.number().int().min(1).max(730).optional()}),he.strictObject({...Cs,action:he.literal("extend"),membershipId:he.uuid(),days:he.number().int().min(1).max(730)}),he.strictObject({...Cs,action:he.literal("end"),membershipId:he.uuid()})]),fp=he.strictObject({operationId:he.uuid()}),hp=he.iso.datetime({offset:!0}),Qy=he.strictObject({provider:he.literal("stripe"),executor:he.enum(["indiana","merchant"]),accountId:he.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:he.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:he.union([he.literal("now"),hp]),prorationBehavior:he.literal("none")}),Os=he.strictObject({operationId:he.uuid(),action:he.enum(["start","extend","end"]),status:he.enum(["pending","effective"]),managedBy:he.enum(["indiana","stripe"]),membershipIds:he.array(he.uuid()).min(1).max(20),endsAt:hp.nullable(),execution:Qy.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"),mE=he.strictObject({groupId:he.uuid(),productVersionId:he.uuid(),enabled:he.boolean()});import{z as ke}from"zod";var gp=ke.strictObject({requestId:ke.uuid(),currency:ae,makeDefault:ke.boolean()}),bp=ke.strictObject({setupId:ke.uuid()}),Zy=ke.strictObject({provider:ke.literal("stripe"),executor:ke.literal("merchant"),accountId:ke.string().regex(/^acct_[A-Za-z0-9]+$/),mode:ke.literal("setup"),currency:ke.string().regex(/^[a-z]{3}$/),customer:ke.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:ke.uuid(),metadata:ke.strictObject({grooveProjectId:ke.uuid(),grooveEnvironmentId:ke.uuid(),grooveCustomerId:ke.uuid(),groovePaymentSetupId:ke.uuid()}),setDefaultPaymentMethod:ke.boolean(),expiresAt:ke.iso.datetime({offset:!0})}),Es=ke.strictObject({id:ke.uuid(),provider:ke.literal("stripe"),status:ke.enum(["prepared","complete","expired"]),currency:ae,makeDefault:ke.boolean(),url:ke.url().nullable(),createdAt:ke.iso.datetime({offset:!0}),expiresAt:ke.iso.datetime({offset:!0}),completedAt:ke.iso.datetime({offset:!0}).nullable(),execution:Zy.nullable()});import{z as tt}from"zod";var _p=tt.union([tt.string(),tt.number(),tt.boolean(),tt.null()]),yp=tt.strictObject({customerId:tt.uuid()}),Sp=tt.strictObject({customerId:tt.uuid(),provider:tt.literal("stripe"),checkedAt:tt.iso.datetime({offset:!0}),status:tt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:tt.number().int().nonnegative(),differences:tt.array(tt.strictObject({subscriptionId:tt.string().startsWith("sub_"),itemId:tt.string().nullable(),field:tt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:_p,actual:_p})).max(1e4)});import{z as ce}from"zod";var xa=ce.iso.datetime({offset:!0}),Ia=ce.strictObject({createdAt:xa,id:ce.uuid()}),Aa=ce.strictObject({customerId:ce.uuid().optional(),entityId:ce.uuid().optional(),productId:ce.string().min(1).max(256).optional(),provider:ce.enum(["stripe","apple","google","free"]).optional(),status:ce.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Ia.optional(),limit:ce.number().int().min(1).max(100).optional()}),Ts={id:ce.uuid(),customerId:ce.uuid(),entityId:ce.uuid().nullable(),productId:ce.string().min(1).max(256),productVersionId:ce.uuid(),name:ce.string().min(1).max(120),provider:ce.enum(["stripe","apple","google","free"]),createdAt:xa},Yy=ce.strictObject({...Ts,status:ce.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ce.boolean(),billingSubscriptionId:ce.uuid().nullable()}),Jy=ce.strictObject({...Ts,status:ce.enum(["active","ended","refunded"]),orderId:ce.uuid().nullable(),transactionId:ce.uuid().nullable(),currency:ae.nullable(),amountMinor:ce.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),Xy=ce.strictObject({...Ts,status:ce.enum(["blocked","resolved"]),conflict:ce.strictObject({detectedAt:xa,blockingMembershipIds:ce.array(ce.uuid()).min(1).max(100),transactionId:ce.uuid()}),resolvedAt:xa.nullable()}),vp=Aa.extend({status:ce.enum(["blocked","resolved"]).optional()}),xp=ce.strictObject({customerId:ce.uuid(),orderId:ce.uuid()}),Ip=ce.strictObject({orderId:ce.uuid(),status:ce.enum(["blocked","resolved"])}),Ap=ce.strictObject({items:ce.array(Yy).max(100),nextCursor:Ia.nullable()}),wp=ce.strictObject({items:ce.array(Jy).max(100),nextCursor:Ia.nullable()}),Pp=ce.strictObject({items:ce.array(Xy).max(100),nextCursor:Ia.nullable()});import{z as Ue}from"zod";var Cp=Ue.union([Ue.strictObject({intent:Ue.literal("read"),requestId:Ue.uuid(),purchaseIntentId:Ue.uuid()}),Ue.strictObject({requestId:Ue.uuid(),provider:Ue.literal("apple"),purchaseIntentId:Ue.uuid(),productId:Ue.string().min(1).max(255).optional(),signedTransaction:Ue.string().min(1).max(131072)}),Ue.strictObject({requestId:Ue.uuid(),provider:Ue.literal("google"),purchaseIntentId:Ue.uuid(),productId:Ue.string().min(1).max(255).optional(),purchaseToken:Ue.string().min(1).max(16384)})]),Op=Ue.strictObject({requestId:Ue.uuid(),orderId:Ue.uuid(),purchaseIntentId:Ue.uuid(),status:Ue.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:ae,refunded:Ue.boolean(),completion:Ue.strictObject({transactionIds:Ue.array(Ue.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ue.boolean()}).nullable()});import{z as T}from"zod";var ks=T.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),zy=T.record(T.string(),T.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),eS=3,_i=20,tS=eS*_i,Rs=T.strictObject({type:T.literal("product"),productId:ks}),Ep={type:T.literal("group"),key:T.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:T.string().trim().min(1).max(80)},nS=T.discriminatedUnion("type",[Rs,T.strictObject({...Ep,items:T.array(Rs).max(_i)})]),rS=T.discriminatedUnion("type",[Rs,T.strictObject({...Ep,items:T.array(nS).max(_i)})]),iS=T.array(rS).max(_i).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>_i||i>tS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function yi(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:yi(t))}function CE(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 wa=T.strictObject({lookupKey:T.string().trim().min(1).max(200),displayName:T.string().trim().min(1).max(1500),items:iS,metadata:zy}),js=wa.extend({paywallId:T.uuid().nullable()}),aS=T.strictObject({product:T.record(T.string(),T.json()),prices:T.array(T.record(T.string(),T.json())),entitlements:T.array(T.record(T.string(),T.json())),freeTrials:T.array(T.record(T.string(),T.json())),licenses:T.array(T.record(T.string(),T.json()))}),Tp=js.extend({id:T.uuid(),projectId:T.uuid(),environmentId:T.uuid(),state:T.enum(["active","archived"]),isCurrent:T.boolean(),revision:T.number().int().nonnegative(),publishedVersionId:T.uuid().nullable(),createdAt:T.number().nonnegative().nullable()}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Rp=T.strictObject({id:T.uuid(),offeringId:T.uuid(),projectId:T.uuid(),environmentId:T.uuid(),version:T.number().int().positive(),document:wa,productEvidence:T.record(ks,aS),createdAt:T.number().nonnegative().nullable()}).superRefine((e,t)=>{let n=yi(e.document);(!n.length||cS(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"})}),oS=T.strictObject({rows:T.array(Tp).max(200),versions:T.array(Rp).max(500)}),OE=T.discriminatedUnion("action",[T.strictObject({action:T.literal("create"),document:js}),T.strictObject({action:T.literal("save"),id:T.uuid(),revision:T.number().int().nonnegative(),document:js}),T.strictObject({action:T.enum(["publish","set_current","archive","restore"]),id:T.uuid(),revision:T.number().int().nonnegative()})]),EE=T.strictObject({record:Tp,version:Rp.nullable()}),jp=T.discriminatedUnion("type",[T.strictObject({type:T.literal("current")}),T.strictObject({type:T.literal("id"),id:T.uuid()}),T.strictObject({type:T.literal("lookup_key"),lookupKey:T.string().min(1).max(200)}),T.strictObject({type:T.literal("version"),versionId:T.uuid()})]),sS=T.strictObject({internalId:ks,id:T.string(),name:T.string().nullable(),version:T.number().int().positive(),archived:T.boolean()}),TE=oS.extend({products:T.array(sS).max(500),paywalls:T.array(T.strictObject({id:T.uuid(),name:T.string()})).max(200)});function cS(e){let t=[];yi(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 Pa}from"zod";var _r=Pa.strictObject({id:Pa.uuid(),offeringId:Pa.uuid(),version:Pa.number().int().positive(),document:wa});import{z as At}from"zod";import{z as ee}from"zod";import{z as yr}from"zod";var kp=yr.strictObject({items:yr.array(yr.strictObject({productVersionId:yr.string().min(1).max(200),label:yr.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:yr.string().min(1).max(200).nullable(),grouping:yu.optional()});function UE(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as Ye}from"zod";var uS=Ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Dp=Ye.discriminatedUnion("type",[Ye.object({type:Ye.literal("fixed"),productVersionId:Ye.string().min(1).max(200)}).strict(),Ye.object({type:Ye.literal("picker"),pickerId:uS,allowedProductVersionIds:Ye.array(Ye.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),gn=Ye.discriminatedUnion("type",[Ye.object({type:Ye.literal("modal"),size:Ye.enum(["sm","md","lg"])}).strict(),Ye.object({type:Ye.literal("sheet"),size:Ye.enum(["sm","md","lg"])}).strict(),Ye.object({type:Ye.literal("fullscreen")}).strict(),Ye.object({type:Ye.literal("inline")}).strict()]);var lS=ee.discriminatedUnion("type",[ee.strictObject({type:ee.literal("event"),event:ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),ee.strictObject({type:ee.literal("open_url"),url:ee.url().refine(e=>new URL(e).protocol==="https:")})]),dS=It,pS=ee.discriminatedUnion("type",[ee.object({type:ee.literal("checkout"),product:Dp}).strict(),ee.object({type:ee.literal("close")}).strict(),ee.object({type:ee.literal("action"),action:lS}).strict()]),Ca=ee.object({schemaVersion:ee.literal(3),kind:ee.literal("paywall"),name:ee.string().trim().min(1).max(80),presentation:gn,requirement:ur.optional(),products:kp,offeringVersionId:ee.uuid().nullable(),offeringId:ee.uuid().nullable(),screen:dS,buttons:ee.record(ee.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),pS)}).strict(),Oa=Ca.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 fS(e))t.addIssue({code:"custom",message:r});for(let r of mS(e))t.addIssue({code:"custom",message:r});Yi(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 mS(e){let t=e.products.items.map(a=>a.productVersionId),n=vu(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&&(!Su(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Lt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Lt(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 fS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),zr(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(p=>p.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let d=e.buttons[u];s.id!==n.id&&d&&d.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Np=ee.object({id:ee.uuid(),projectId:ee.uuid(),environmentId:ee.uuid(),revision:ee.number().int().nonnegative(),status:ee.enum(["draft","published","archived"]),publishedVersionId:ee.uuid().nullable(),updatedAt:ee.iso.datetime({offset:!0}),draft:Ca}).strict(),QE=ee.object({rows:ee.array(Np).max(200),nextCursor:ee.uuid().nullable()}).strict(),ZE=Np.omit({draft:!0}).extend({name:ee.string(),productCount:ee.number().int().nonnegative()}).strict(),YE=ee.discriminatedUnion("action",[ee.object({action:ee.literal("save"),id:ee.uuid().nullable(),revision:ee.number().int().nonnegative(),document:Ca}).strict(),ee.object({action:ee.enum(["publish","archive"]),id:ee.uuid(),revision:ee.number().int().nonnegative()}).strict()]),JE=ee.object({paywalls:ee.array(ee.object({id:ee.uuid(),paywallId:ee.uuid(),version:ee.number().int().positive(),name:ee.string().min(1).max(80),presentation:gn,buttons:Ca.shape.buttons}).strict()).max(500),limited:ee.boolean()}).strict();var Fp=At.strictObject({...hr,selector:At.discriminatedUnion("type",[At.strictObject({type:At.literal("paywall"),paywallId:At.uuid()}),At.strictObject({type:At.literal("version"),versionId:At.uuid()})]),customerId:At.uuid().optional(),commerce:Zi,locale:At.string().min(1).max(35),requirement:ur.optional()}),Ea=At.strictObject({id:At.uuid(),paywallId:At.uuid(),version:At.number().int().positive(),document:Oa,offering:_r,capabilities:lr,check:Xr.nullable()}).superRefine((e,t)=>{let n=new Set(yi(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 ft}from"zod";var Up={requestId:ft.uuid(),sourceId:ft.uuid(),expectedAvailable:Tt},Mp=ft.discriminatedUnion("action",[ft.strictObject({...Up,action:ft.enum(["add","subtract","set_remaining"]),amount:ge}),ft.strictObject({...Up,action:ft.literal("edit"),granted:ge,expiresAt:ft.iso.datetime({offset:!0}).nullable(),nextResetAt:ft.iso.datetime({offset:!0}).nullable(),expectedRevision:ft.number().int().nonnegative()})]),Ds=ft.strictObject({sourceId:ft.uuid(),available:Tt,held:Tt,spent:Tt,adjustmentGrantId:ft.uuid().nullable()}),Bp=Ds.extend({granted:Tt,expiresAt:ft.iso.datetime({offset:!0}).nullable(),nextResetAt:ft.iso.datetime({offset:!0}).nullable(),revision:ft.number().int().nonnegative()});import{z as jt}from"zod";var Lp=jt.discriminatedUnion("action",[jt.object({action:jt.literal("upsert"),externalId:jt.string().min(1).max(128),name:jt.string().trim().min(1).max(80)}).strict(),jt.object({action:jt.literal("archive"),entityId:jt.uuid()}).strict()]),qp=jt.object({id:jt.uuid(),externalId:jt.string().min(1).max(128),name:jt.string().min(1).max(80),archived:jt.boolean()}).strict();import{z as at}from"zod";import{z as Jn}from"zod";var $p=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Vp=Jn.string().regex(/.+\/.+/),Ns=Jn.number().min(-100),Yn=Jn.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),hS=Jn.strictObject({input:Yn,output:Yn,cache_read:Yn.optional(),cache_write:Yn.optional(),reasoning:Yn.optional(),input_audio:Yn.optional(),output_audio:Yn.optional()}),Fs=(e,t)=>Jn.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),hT=Jn.strictObject({defaultMarkup:Ns,providerMarkups:Fs(Jn.string().min(1),Ns),modelMarkups:Fs(Vp,Ns),customModels:Fs(Vp,hS.partial())});import{z as re}from"zod";var Xn=re.iso.datetime({offset:!0}),En=re.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),gS=re.discriminatedUnion("kind",[re.object({kind:re.literal("absolute"),from:Xn,to:Xn}).strict(),re.object({kind:re.literal("last_days"),days:re.union([re.literal(1),re.literal(7),re.literal(30),re.literal(90)])}).strict(),re.object({kind:re.literal("billing_cycles"),membershipId:re.uuid(),count:re.number().int().min(1).max(12),includeCurrent:re.boolean()}).strict()]),Gp=re.string().max(100).refine(e=>{if(e!=="UTC"&&!/^[A-Za-z_]+(?:\/[A-Za-z0-9_+\-]+)+$/.test(e))return!1;try{return new Intl.DateTimeFormat("en",{timeZone:e}),!0}catch{return!1}},"Use an IANA timezone"),bS=re.object({key:re.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:re.array(re.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),zn=re.object({range:gS,timezone:Gp,filterBy:re.array(bS).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:re.enum(["hour","day","week","month"]),internal_feature_id:re.uuid().nullable(),entityId:re.uuid().nullable(),topN:re.number().int().min(1).max(50).nullable(),groupBy:re.union([re.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),re.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:re.object({bucket:Xn,group:re.string().max(240),isOther:re.boolean(),internal_feature_id:re.uuid(),resourceId:re.uuid()}).strict().nullable(),limit:re.number().int().min(1).max(100)}).strict().superRefine((e,t)=>{if(e.range.kind!=="absolute"){e.interval==="hour"&&e.range.kind==="last_days"&&e.range.days>31&&t.addIssue({code:"custom",message:"Hourly reports are bounded to 31 days"});return}let n=Date.parse(e.range.to)-Date.parse(e.range.from);(n<=0||n>366*864e5||e.interval==="hour"&&n>31*864e5)&&t.addIssue({code:"custom",message:"Reporting range must be positive and bounded (31 days hourly, 366 days otherwise)"})}),Wp=re.object({from:Xn,to:Xn,interval:re.enum(["hour","day","week","month"]),timezone:Gp,rows:re.array(re.object({bucket:Xn,group:re.string().max(240),isOther:re.boolean(),internal_feature_id:re.uuid(),resourceId:re.uuid(),consumedUnits:En,refundedUnits:En,reservedUnits:En,charged:En,refunded:En,reserved:En,netUnits:En,netCharged:En}).strict()).max(100),nextCursor:re.object({bucket:Xn,group:re.string().max(240),isOther:re.boolean(),internal_feature_id:re.uuid(),resourceId:re.uuid()}).strict().nullable()}).strict();var Sr=at.string().regex(/^(0|[1-9]\d{0,29})$/),Kp=at.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),Us=at.strictObject({bucket:at.iso.datetime({offset:!0}),group:at.string().max(240),isOther:at.boolean(),internal_feature_id:at.uuid()}),Hp=at.strictObject({...zn.shape,groupBy:at.union([at.enum(["customer","entity","entitlement"]),at.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Us.nullable()}).superRefine((e,t)=>{let n=zn.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Qp=at.strictObject({from:at.iso.datetime({offset:!0}),to:at.iso.datetime({offset:!0}),interval:zn.shape.interval,timezone:zn.shape.timezone,rows:at.array(at.strictObject({...Us.shape,eventCount:Sr,units:Kp,tokenEventCount:Sr,tokens:at.strictObject(Object.fromEntries($p.map(e=>[e,Sr]))),totalTokens:Sr,providerCostEventCount:Sr,providerCostUsd:Kp,invalidTelemetryEventCount:Sr})).max(100),nextCursor:Us.nullable()});import{z as He}from"zod";var Zp=He.object({requestId:He.uuid(),items:He.array(He.object({customerId:He.uuid(),command:Yr.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"),Yp=He.object({batchId:He.uuid(),after:He.number().int().min(-1).max(999),limit:He.number().int().min(1).max(100)}).strict(),Jp=He.object({batchId:He.uuid(),status:He.enum(["queued","complete"]),total:He.number().int().min(1).max(1e3),processed:He.number().int().min(0).max(1e3),items:He.array(He.object({position:He.number().int().min(0).max(999),customerId:He.uuid(),idempotencyKey:He.string().min(1).max(120),status:He.enum(["queued","accepted","rejected","failed"]),receipt:Jr.nullable(),errorCode:He.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:He.number().int().min(0).max(999).nullable()}).strict();import{z as S}from"zod";var _S=S.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Xp=S.enum(["draft","active","paused","archived"]),zp=S.string().min(1).max(256),em=S.array(zp).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),yS=S.strictObject({duration:S.enum(["day","week","month","year"]),length:S.number().int().min(1).max(3660)}),SS=S.strictObject({internal_feature_id:S.uuid(),allowance:S.number().nonnegative().max(1e15).nullable(),expiry:yS.nullable()}),vS=S.discriminatedUnion("type",[S.strictObject({type:S.literal("feature_grant"),grants:S.array(SS).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),S.strictObject({type:S.literal("free_product"),productId:zp,duration:Yt}),S.strictObject({type:S.literal("invoice_credits"),amount:S.number().positive().max(1e8),duration:Yt,rollover:S.boolean(),productIds:em})]),xS=S.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),tm=S.object({key:xS,name:S.string().trim().min(1).max(80),configuration:vS}).strict(),nm=S.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),Ms=S.object({code:nm,maxUses:S.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:S.boolean()}).strict(),rm=S.object({key:S.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:S.string().trim().min(1).max(80),rewardId:S.uuid(),redeemOn:S.enum(["customer_creation","checkout"]),receivedBy:S.enum(["referrer","all"]),maxRedemptions:S.number().int().min(1).max(1e6).nullable(),productIds:em,excludeTrial:S.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),im={id:S.uuid(),projectId:S.uuid(),environmentId:S.uuid(),revision:S.number().int().nonnegative(),status:Xp,createdAt:S.iso.datetime({offset:!0}),updatedAt:S.iso.datetime({offset:!0})},IS=tm.extend(im).strict(),AS=rm.safeExtend(im).strict(),ET=S.strictObject({id:S.uuid(),key:S.string(),name:S.string(),type:_S,status:Xp}),TT=S.discriminatedUnion("action",[S.object({action:S.literal("save"),id:S.uuid().nullable(),revision:S.number().int().nonnegative(),input:tm}).strict(),S.object({action:S.enum(["activate","pause","resume","archive","delete"]),id:S.uuid(),revision:S.number().int().nonnegative()}).strict()]),RT=S.discriminatedUnion("action",[S.object({action:S.literal("save"),id:S.uuid().nullable(),revision:S.number().int().nonnegative(),input:rm}).strict(),S.object({action:S.enum(["activate","pause","resume","archive","delete"]),id:S.uuid(),revision:S.number().int().nonnegative()}).strict()]),am=S.object({id:S.uuid(),rewardId:S.uuid(),programId:S.uuid().nullable(),customerId:S.uuid(),referrerId:S.uuid().nullable(),status:S.enum(["pending","applied","unavailable"]),result:S.record(S.string(),S.unknown()).nullable(),createdAt:S.iso.datetime({offset:!0})}).strict(),om=S.object({code:nm,requestId:S.uuid()}).strict(),sm=S.strictObject({redemptionId:S.uuid(),currency:ae,requestId:S.uuid(),accepted:S.literal(!0)}),wS=S.strictObject({type:S.literal("checkout"),orderId:S.uuid(),productVersionId:S.uuid(),currency:ae,duration:Yt,renewalAmountMinor:S.number().int().positive().max(1e8),status:S.enum(["created","pending","trialing","paid","cancelled","failed"]),url:S.url().nullable()}),cm=S.discriminatedUnion("type",[wS,S.strictObject({type:S.literal("subscription"),operationId:S.uuid(),membershipId:S.uuid(),productVersionId:S.uuid(),currency:ae,duration:Yt,renewalAmountMinor:S.number().int().positive().max(1e8),status:S.enum(["pending","running","applied","failed"])})]),um=S.object({programId:S.uuid(),requestId:S.uuid()}).strict(),lm=S.object({id:S.uuid(),programId:S.uuid(),code:Ms.shape.code,createdAt:S.iso.datetime({offset:!0})}).strict(),jT=S.object({rows:S.array(IS).max(100),nextCursor:S.uuid().nullable()}).strict(),kT=S.object({rows:S.array(AS).max(100),nextCursor:S.uuid().nullable()}).strict(),PS=Ms.extend({id:S.uuid(),redemptions:S.number().int().nonnegative()}).strict(),CS=S.strictObject({id:S.uuid(),programId:S.uuid().nullable(),customerId:S.uuid().nullable(),referrerId:S.uuid().nullable(),code:S.string().nullable(),status:S.enum(["pending","triggered","applied"]),createdAt:S.iso.datetime({offset:!0})}),DT=S.object({codes:S.array(PS).max(100),redemptions:S.array(CS).max(100),customers:S.record(S.uuid(),S.string()),codesCursor:S.uuid().nullable(),redemptionsCursor:S.uuid().nullable()}).strict(),NT=S.discriminatedUnion("action",[S.object({action:S.literal("create"),rewardId:S.uuid(),revision:S.number().int().nonnegative(),input:Ms}).strict(),S.object({action:S.literal("remove"),rewardId:S.uuid(),revision:S.number().int().nonnegative(),codeId:S.uuid()}).strict()]);import{z as _}from"zod";import{z as F}from"zod";var sn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Si=e=>new Set(e).size===e.length,Bs=F.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),OS=F.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),vi=F.string().min(1).max(200).regex(/^[a-zA-Z0-9_./-]+$/).refine(e=>!e.includes("..")&&!e.endsWith(".")&&!e.split("/").some(t=>!t||t.startsWith(".")||t.endsWith(".lock"))),ES=F.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),dm=F.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),MT=["isOn","isOff","getFeatureValue","evalFeature","eval_feature"],pm=F.strictObject({id:F.uuid(),repo:OS,platform:F.enum(["github","gitlab","bitbucket"]),branches:F.array(vi).min(1).max(4).refine(Si),workflow:F.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:F.array(F.uuid()).min(1).max(4).refine(Si),include:F.array(dm).min(1).max(16),exclude:F.array(dm).max(16),methods:F.array(F.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Si),maxAgeHours:F.number().int().min(1).max(720)}),mm=pm.extend({revision:F.number().int().positive()}),BT=F.strictObject({repository:pm,expectedRevision:F.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),fm=F.strictObject({repositoryId:F.uuid(),branch:vi}),TS=F.array(Bs).max(sn.keys).refine(Si),hm=F.strictObject({repository:mm.omit({keyIds:!0}),branch:vi,keys:TS,keySetHash:F.string().regex(/^[a-f0-9]{64}$/)}),RS=F.strictObject({filePath:ES,startingLineNumber:F.number().int().min(1).max(1e7)}),Ls=F.strictObject({protocol:F.literal(1),repositoryId:F.uuid(),branch:vi,workflow:F.string().max(200),configurationRevision:F.number().int().positive(),keySetHash:F.string().regex(/^[a-f0-9]{64}$/),commit:F.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:F.uuid(),runNumber:F.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:F.number().int().min(1).max(1e4),scannerVersion:F.literal("1"),scannedAt:F.iso.datetime({offset:!0}),coverage:F.strictObject({complete:F.literal(!0),files:F.number().int().min(0).max(sn.files),sourceBytes:F.number().int().min(0).max(sn.sourceBytes),unresolvedCalls:F.number().int().min(0).max(1e6),unsupportedFiles:F.number().int().min(0).max(sn.files)}),features:F.array(F.strictObject({key:Bs,refs:F.array(RS).max(sn.referencesPerKey)})).max(sn.keys)}).superRefine((e,t)=>{Si(e.features.map(n=>n.key))||t.addIssue({code:"custom",path:["features"],message:"Duplicate feature"}),e.features.reduce((n,r)=>n+r.refs.length,0)>sn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),qs=F.strictObject({scanId:F.uuid(),commit:F.string(),receivedAt:F.string(),references:F.number().int().nonnegative(),removedReferences:F.number().int().nonnegative()}),jS=qs.extend({repositoryId:F.uuid(),branch:vi,workflow:F.string(),digest:F.string(),configurationRevision:F.number().int().positive(),runNumber:F.number().int().positive(),runAttempt:F.number().int().positive(),scannedAt:F.string(),keySetHash:F.string(),coverage:Ls.shape.coverage}),kS=F.strictObject({repositories:F.array(mm).max(sn.repositories),scans:F.array(jS).max(sn.repositories*sn.branches)}),DS=F.strictObject({key:Bs,references:F.number().int().nonnegative(),coveredTargets:F.number().int().nonnegative(),expiredTargets:F.number().int().nonnegative(),uncertainTargets:F.number().int().nonnegative()}),LT=F.strictObject({available:F.boolean().default(!0),settings:kS,expectedTargets:F.number().int().min(0).max(80),features:F.array(DS).max(2001),truncated:F.boolean()});import{z as Y}from"zod";var Vs=Y.array(Y.string().trim().min(1).max(40).refine(e=>!e.includes(","),"\u6807\u7B7E\u4E0D\u80FD\u5305\u542B\u9017\u53F7")).max(20).refine(e=>new Set(e).size===e.length,"\u6807\u7B7E\u4E0D\u80FD\u91CD\u590D"),vr=Y.intersection(Bt,Y.object({tags:Vs.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ta=Y.string().trim().max(80),Ra=Y.union([Y.email().max(254),Y.literal("")]),ja=Y.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),gm=Y.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),bm=Y.object({externalUserId:gm.optional(),name:Ta.default(""),email:Ra.default(""),attributes:vr.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),xr=Y.discriminatedUnion("type",[Y.strictObject({type:Y.literal("id"),value:Y.uuid()}),Y.strictObject({type:Y.literal("externalUserId"),value:gm})]),Ir=Y.strictObject({name:Ta.optional(),email:Ra.optional(),attributes:vr.optional(),fingerprint:ja.optional()}),er=e=>!e.customerData||e.customer?.type==="externalUserId",tr="customerData requires an externalUserId customer",Ar=Y.object({id:Y.uuid(),externalUserId:Y.string().min(1).max(255).nullable(),name:Ta,email:Ra,attributes:vr,createdAt:Y.iso.datetime()}).strict(),_m=Y.object({customer:Ar,changed:Y.boolean(),replayed:Y.boolean()}).strict(),NS=Y.discriminatedUnion("type",[Y.object({type:Y.literal("id"),value:Y.uuid()}).strict(),Y.object({type:Y.literal("externalUserId"),value:Y.string().trim().min(1).max(255)}).strict()]),FS=Y.object({name:Ta.optional(),email:Ra.optional(),attributes:vr.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:Y.array(Y.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:Y.strictObject({add:Vs,remove:Vs}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),$s=Y.object({lookup:NS}).strict(),ym=$s.extend({requestId:Y.uuid(),patch:FS}).strict(),Sm=Y.object({search:Y.string().trim().max(200).default(""),tag:Y.string().trim().max(40).default(""),planId:Y.string().max(200).default(""),versionId:Y.string().max(200).default(""),holdingStatus:Y.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:Y.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:Y.union([Y.iso.datetime(),Y.literal("")]).default(""),createdUntil:Y.union([Y.iso.datetime(),Y.literal("")]).default(""),offset:Y.coerce.number().int().min(0).max(1e5).default(0),limit:Y.coerce.number().int().min(1).max(100).default(50)}).strict(),vm=Y.object({customers:Ar.array(),hasMore:Y.boolean(),total:Y.number().int().nonnegative().nullable(),evaluatedAt:Y.iso.datetime()}).strict();import{z as Vt}from"zod";var Gs=Vt.strictObject({customerId:Vt.uuid(),eventId:Vt.string().trim().min(1).max(200),grantId:Vt.uuid(),productVersionId:Vt.uuid(),subscriptionId:Vt.string().trim().min(1).max(255),occurredAt:Vt.iso.datetime({offset:!0})}),xm=Gs.extend({id:Vt.uuid(),couponId:Vt.uuid(),status:Vt.literal("redeemed"),source:Vt.literal("merchant"),recordedAt:Vt.iso.datetime({offset:!0})});import{z as Re}from"zod";import{z as ka}from"zod";var Ws=ka.strictObject({eventsEnabled:ka.boolean(),experimentViewsEnabled:ka.boolean(),featureUsageEnabled:ka.boolean()}),QT=Object.freeze({eventsEnabled:!1,experimentViewsEnabled:!0,featureUsageEnabled:!1});function ZT(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var Ks=nn.extend({analyticsConfig:Ws,remoteFeatures:Re.array(Re.string().min(1).max(255)).max(500)}),US=Ks.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),Im=Re.strictObject({attributes:Bt,features:Re.array(Re.string().min(1).max(255)).min(1).max(500).optional(),customerId:Re.uuid().optional()}),MS=Re.strictObject({value:Ie,source:Re.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Re.boolean(),off:Re.boolean(),ruleId:Re.string(),experimentResult:Eu.optional()}),Am=Re.strictObject({generation:nn.shape.generation,evaluatedAt:nn.shape.evaluatedAt,expiresAt:nn.shape.expiresAt,features:Re.record(Re.string(),MS)}),wm=Re.strictObject({customerId:Re.uuid().optional(),events:Re.array(Re.strictObject({eventUuid:Re.uuid(),timestamp:Re.iso.datetime({offset:!0}),name:Re.string().min(1).max(255),properties:Re.record(Re.string(),Ie).default({}),deviceId:Re.string().min(1).max(255).optional(),sessionId:Re.string().min(1).max(255).optional()})).min(1).max(100)}),Pm=Re.strictObject({inserted:Re.number().int().nonnegative(),duplicates:Re.number().int().nonnegative(),rejected:Re.number().int().nonnegative(),skipped:Re.number().int().nonnegative(),analyticsConfig:Ws});import{z as Q}from"zod";var Hs=Q.strictObject({name:Q.string().trim().min(1).max(255),memo:Q.string().max(1e4).nullable().optional(),footer:Q.string().max(1e4).nullable().optional(),net_terms_days:Q.number().int().positive().nullable().optional()}),BS=Hs.extend({id:Q.string().min(1).max(255),created_at:Q.number().nullable()}),Cm=Q.strictObject({items:Q.array(BS).max(50),nextCursor:Q.string().nullable()}),iR=Q.discriminatedUnion("action",[Q.strictObject({action:Q.literal("create"),requestId:Q.uuid(),values:Hs}),Q.strictObject({action:Q.literal("update"),id:Q.string().min(1).max(255),values:Hs}),Q.strictObject({action:Q.literal("delete"),id:Q.string().min(1).max(255)})]),Om=Q.discriminatedUnion("action",[Q.strictObject({action:Q.literal("create"),requestId:Q.uuid(),params:gr}),Q.strictObject({action:Q.enum(["finalize","send","pay","void"]),requestId:Q.uuid(),invoiceId:Q.uuid()}),Q.strictObject({action:Q.literal("reissue"),requestId:Q.uuid(),invoiceId:Q.uuid(),params:Is})]),Qs=Q.strictObject({id:Q.uuid(),customerId:Q.uuid(),providerInvoiceId:Q.string().nullable(),status:Q.enum(["draft","open","paid","void","uncollectible"]),currency:Q.string(),totalMinor:Q.string().regex(/^-?\d+$/),paidMinor:Q.string().regex(/^\d+$/),refundedMinor:Q.string().regex(/^\d+$/),hostedInvoiceUrl:Q.url().nullable(),createdAt:Q.number(),collectionMethod:Q.enum(["send_invoice","charge_automatically"]).nullable()}),Em=Qs.extend({lines:Q.array(Q.strictObject({id:Q.uuid(),description:Q.string(),amountMinor:Q.string().regex(/^-?\d+$/),netAmountMinor:Q.string().regex(/^-?\d+$/),quantity:Q.number().nullable(),periodStart:Q.number().nullable(),periodEnd:Q.number().nullable()})).max(1e3)}),xi=Q.strictObject({taskId:Q.uuid(),status:Q.enum(["ready","running","done","dead"]),invoice:Qs.nullable(),errorCode:Q.string().nullable()}),Tm=Q.strictObject({items:Q.array(Qs).max(50),nextCursor:Q.uuid().nullable(),operations:Q.array(xi).max(50),operationsLimited:Q.boolean()}),aR=On;var LS=_.enum(["customers:read","customers:write","entitlements:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","code-references:read","code-references:write"]),Rm={scope:je,permissions:_.array(LS),expiresAt:_.iso.datetime().nullable()},KR=_.discriminatedUnion("kind",[_.object({...Rm,kind:_.literal("server"),keyId:_.string().min(1)}),_.object({...Rm,kind:_.literal("customer"),customerId:_.string().min(1),identityKind:_.enum(["identified","guest"]),expiresAt:_.iso.datetime()})]),D=_.object({requestId:_.uuid(),scope:je}).strict(),qS=bm.safeExtend({fingerprint:ja.optional()}).strict(),VS=D.extend({customer:Ar,created:_.boolean()}),$S=_.enum(["unassigned","unknown","scheduled","active","expired"]),HR=_.object({customerId:_.string().min(1),evaluatedAt:_.iso.datetime(),status:$S,validity:as.nullable(),planVersion:Vl.nullable(),holdings:_.array(_.object({id:_.uuid(),planVersionId:_.uuid(),source:_.enum(["subscription","assignment","license","license_pool","entity_pool"])})).optional(),entitlements:_.array(_.object({featureId:_.string(),featureKey:_.string(),featureName:_.string(),type:_.enum(["boolean","metered"]),allowance:_.number().int().nonnegative().nullable(),used:_.number().finite().nonnegative(),remaining:_.number().finite().nonnegative().nullable(),allowed:_.boolean(),sources:_.array(_.object({holdingId:_.uuid(),planVersionId:_.uuid(),group:_.string(),kind:_.enum(["main","addon"]),allowance:_.number().nullable()})).optional()}))});function jm(){return D.extend({offer:oi.nullable(),reason:ma.nullable()})}var j={listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:_.strictObject({cursor:_.uuid().optional()}),response:D.extend({templates:Cm})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),params:gr}),response:D.extend({preview:As})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),requestId:_.uuid(),params:gr}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:xi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Om}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:D.extend({operation:xi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),taskId:_.uuid()}),response:D.extend({operation:xi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),cursor:_.uuid().optional()}),response:D.extend({invoices:Tm})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:_.strictObject({customerId:_.uuid(),invoiceId:_.uuid()}),response:D.extend({invoice:Em})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:fm,response:D.extend({config:hm})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:Ls,response:D.extend({receipt:qs})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:_.strictObject({}),response:D.extend({payload:Ks})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Im,response:D.merge(Am)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:wm,response:D.merge(Pm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),sourceId:_.uuid()}),response:D.extend({balance:Bp})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Mp}),response:D.extend({balance:Ds})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:_.strictObject({internal_feature_id:_.uuid(),customerId:_.uuid().optional(),entityId:_.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:D.extend({internal_feature_id:_.uuid(),config:Xo,model_markups:da})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid(),query:du}),response:D.extend({usage:Co})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:pu}),response:D.extend({usage:Co})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:_.strictObject({customerId:_.uuid(),command:Cd}),response:D.extend({grant:bs})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Od,response:D.extend({grants:Ed})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:_.union(Cp.options.map(e=>e.extend({customerId:_.uuid().optional(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/).optional()}))),response:D.extend({operation:Op})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:gp.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Es})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:bp.extend({customerId:_.uuid().optional()}),response:D.extend({setup:Es})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:mp.safeExtend({customerId:_.uuid()}),response:D.extend({batch:bi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Sa.extend({customerId:_.uuid()}),response:D.extend({batch:bi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Sa.extend({customerId:_.uuid()}),response:D.extend({batch:bi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Sa.extend({customerId:_.uuid()}),response:D.extend({batch:bi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:_.discriminatedUnion("action",[va.options[0].extend({customerId:_.uuid()}),va.options[1].extend({customerId:_.uuid()}),va.options[2].extend({customerId:_.uuid()})]),response:D.extend({trial:Os})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:fp.extend({customerId:_.uuid()}),response:D.extend({trial:Os})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Aa,response:D.extend({subscriptions:Ap})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Aa,response:D.extend({purchases:wp})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:vp,response:D.extend({conflicts:Pp})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:xp,response:D.extend({resolution:Ip})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:yp,response:D.extend({verification:Sp})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:ip.safeExtend({...hr,customerId:_.uuid().optional()}),response:D.extend({quote:hi})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Zn.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:br})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Zn.extend({customerId:_.uuid().optional()}),response:D.extend({operation:br})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:sp.safeExtend({customerId:_.uuid().optional()}),response:D.extend({quote:up})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Zn.extend({customerId:_.uuid().optional(),intent:_.enum(["confirm","cancel"]).optional()}),response:D.extend({operation:Ps})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Zn.extend({customerId:_.uuid().optional()}),response:D.extend({operation:Ps})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:lp.safeExtend({customerId:_.uuid()}),response:D.extend({quote:pp})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Zn.extend({customerId:_.uuid()}),response:D.extend({operation:ya})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Zn.extend({customerId:_.uuid()}),response:D.extend({operation:ya})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:cd,response:D.extend({controls:us})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:td,response:D.extend({prepared:rd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:id,response:D.extend({authorization:fa})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:pd,response:D.extend({coupons:md})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:ad,response:D.extend({authorization:fa})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:ld,response:D.extend({invoices:dd})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:ud,response:D.extend({invoice:ci})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:_.object({customerId:_.uuid(),command:sd}).strict(),response:D.extend({controls:us})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:_.object({customerId:_.uuid(),command:Lp}).strict(),response:D.extend({entity:qp})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:_.strictObject({customerId:_.uuid().nullable(),query:Hp}),response:D.extend({analytics:Qp})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:_.object({customerId:_.uuid().nullable(),query:zn}).strict(),response:D.extend({analytics:Wp})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Zp,response:D.extend({batchId:_.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Yp,response:D.extend({batch:Jp})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:bu.extend({customerId:_.string().min(1).optional()}),response:D.extend({check:Xr})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Fp,response:D.extend({paywall:Ea})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:_.strictObject({...hr,selector:jp,customerId:_.string().min(1).optional(),commerce:Zi,requirement:ur.optional()}),response:D.extend({offering:_r,candidates:_.array(_u).max(20),availability:_.array(_.strictObject({productVersionId:_.uuid(),available:_.boolean(),reason:_.enum(["platform_binding_missing","commercial_runtime_pending","commerce_not_configured","currency_mismatch","product_unavailable","already_attached","attach_in_progress","already_scheduled","subscription_change_required","purchase_conflict"]).nullable()})).max(20),check:Xr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),entityId:_.uuid().optional()}).strict(),response:D.extend({holdings:mu})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),query:fu}).strict(),response:D.extend({ledger:hu})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Td.extend({customerId:_.uuid().optional()}),response:D.extend({detail:Rd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:_s.safeExtend({customerId:_.uuid().optional()}),response:D.extend({statement:jd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:_.object({customerId:_.uuid().optional(),command:Yr.options[0]}).strict(),response:D.extend({quote:lu})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:_.strictObject({customerId:_.uuid(),command:_.union([_.strictObject({eventName:_.string().min(1),quantity:ge.optional(),properties:Zt.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)}),_.strictObject({internal_feature_id:_.uuid(),quantity:ge.optional(),properties:Zt.optional(),entityId:_.uuid().optional(),idempotencyKey:_.string().min(1).max(120)})])}),response:D.extend({receipts:_.array(Jr).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:_.object({customerId:_.uuid(),command:Yr.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:D.extend({receipt:Jr})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:om,response:D.extend({redemption:am})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:um,response:D.extend({referralCode:lm})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:sm,response:D.extend({checkout:cm})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Nd,response:D.extend({seats:vs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Fd,response:D.extend({seats:vs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:qS,response:VS},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:$s,response:D.extend({customer:Ar})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Sm,response:D.extend(vm.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:ym,response:D.extend(_m.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:_.object({customerId:_.uuid()}).strict(),response:D.extend({customerToken:_.string().min(1),expiresAt:_.iso.datetime(),sessionId:_.uuid()})},renewSession:{method:"POST",path:"customer-sessions/renew",permission:"sessions:create",audience:"server",request:_.strictObject({customerId:_.uuid(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/)}),response:D.extend({customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:_.uuid(),expiresAt:_.iso.datetime()})},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:_.strictObject({customerId:_.uuid(),sessionId:_.uuid().optional()}),response:D.extend({revoked:_.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ja.optional()}),response:D.extend({customerId:_.uuid(),guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:_.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:D.extend({customerId:_.uuid(),customerToken:_.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),sessionId:_.uuid(),expiresAt:_.iso.datetime()})},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:_.strictObject({guestToken:_.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:_.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:_.uuid()}),response:D.extend({customer:Ar,switched:_.boolean(),replayed:_.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:_.strictObject({code:_.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:_.uuid()}),response:jm()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:_.object({}).strict(),response:D.extend({offers:_.array(oi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:_.object({customerId:_.string().min(1).max(255).optional(),couponId:_.uuid(),...hr,requestId:_.uuid(),couponContentDigest:_.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:jm()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Gs,response:D.extend({receipt:xm})}},QR={listInvoiceTemplates:j.listInvoiceTemplates,previewInvoice:j.previewInvoice,createInvoice:j.createInvoice,manageInvoice:j.manageInvoice,readInvoiceOperation:j.readInvoiceOperation,listInvoices:j.listInvoices,getInvoice:j.getInvoice,getCodeReferenceConfig:j.getCodeReferenceConfig,submitCodeReferences:j.submitCodeReferences,getFeatures:j.getFeatures,evaluateFeatures:j.evaluateFeatures,trackEvents:j.trackEvents,setupPayment:j.setupPayment,readPaymentSetup:j.readPaymentSetup,previewSubscriptionBatch:j.previewSubscriptionBatch,confirmSubscriptionBatch:j.confirmSubscriptionBatch,readSubscriptionBatch:j.readSubscriptionBatch,abandonSubscriptionBatch:j.abandonSubscriptionBatch,manageSubscriptionTrial:j.manageSubscriptionTrial,readSubscriptionTrial:j.readSubscriptionTrial,listSubscriptions:j.listSubscriptions,listPurchases:j.listPurchases,listSubscriptionConflicts:j.listSubscriptionConflicts,retrySubscriptionConflict:j.retrySubscriptionConflict,readAiPricing:j.readAiPricing,readUsage:j.readUsage,setUsage:j.setUsage,previewRefund:j.previewRefund,refund:j.refund,readRefund:j.readRefund,previewUpdate:j.previewUpdate,update:j.update,readSubscriptionUpdate:j.readSubscriptionUpdate,restoreNativePurchase:j.restoreNativePurchase,verifySubscriptions:j.verifySubscriptions,previewAttach:j.previewAttach,attach:j.attach,readSubscriptionOperation:j.readSubscriptionOperation,manageBalanceGrant:j.manageBalanceGrant,readBalanceSource:j.readBalanceSource,adjustBalance:j.adjustBalance,listBalanceGrants:j.listBalanceGrants,readBillingControls:j.readBillingControls,prepareBillingAuthorization:j.prepareBillingAuthorization,confirmBillingAuthorization:j.confirmBillingAuthorization,setBillingCoupons:j.setBillingCoupons,revokeBillingAuthorization:j.revokeBillingAuthorization,listBillingInvoices:j.listBillingInvoices,confirmBillingAdjustment:j.confirmBillingAdjustment,manageBillingLimits:j.manageBillingLimits,createCustomer:j.createCustomer,getCustomer:j.getCustomer,listCustomers:j.listCustomers,updateCustomer:j.updateCustomer,createSession:j.createSession,renewSession:j.renewSession,revokeSessions:j.revokeSessions,createGuestCustomer:j.createGuestCustomer,resumeGuestSession:j.resumeGuestSession,claimGuestCustomer:j.claimGuestCustomer,checkEntitlement:j.checkEntitlement,resolveOffering:j.resolveOffering,resolvePaywall:j.resolvePaywall,readHoldings:j.readHoldings,readLedger:j.readLedger,readBillingInvoice:j.readBillingInvoice,readCreditStatement:j.readCreditStatement,quoteBalance:j.quoteBalance,trackUsage:j.trackUsage,mutateBalance:j.mutateBalance,manageUsageEntity:j.manageUsageEntity,readUsageAnalytics:j.readUsageAnalytics,readCreditAnalytics:j.readCreditAnalytics,submitUsageBatch:j.submitUsageBatch,readUsageBatch:j.readUsageBatch,listOffers:j.listOffers,grantOffer:j.grantOffer,recordCouponRedemption:j.recordCouponRedemption,redeemCoupon:j.redeemCoupon,redeemReward:j.redeemReward,createReferralCode:j.createReferralCode,claimRewardProduct:j.claimRewardProduct,readSeats:j.readSeats,manageSeat:j.manageSeat};var Qe={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},XR="00000000-0000-0000-0000-000000000000";var Da={maxTransitions:1e4,runTimeoutSeconds:2592e3},ej={detailBytes:16384};function tj(e,t){return Number.isInteger(e)&&e>=1&&e<=Da.maxTransitions&&Number.isInteger(t)&&t>=0&&t<e}function wt(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),d=l.replace(".","").length,p=(l.includes(".")?l.indexOf("."):d)+Number(u),g=p<=0?2-p+d:p>=d?p:d+1;n+=g+(c.startsWith("-")?1:0)-s.length}}return n}var Dm={primary:"#2C3C96",background:"#FFFFFF",text:"#1B1D24",radius:"md",font:"system"},Ii=(e,t,n,r,i)=>({kind:"screen",schemaVersion:4,name:e,surface:"popup",presentation:{type:"modal",size:"md"},theme:{...Dm},pages:[{id:"main",name:"\u4E3B\u9875\u9762",root:t}],strings:{defaultLocale:"zh-CN",locales:{"zh-CN":n,en:r}},actions:i}),wr=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}}}),Na={id:"dismiss",type:"close",event:"popup.dismissed",properties:{},close:!0},km=[{id:"blank",label:"\u7A7A\u767D",description:"\u4E00\u4E2A\u6807\u9898\u548C\u4E00\u4E2A\u6309\u94AE\uFF0C\u4ECE\u96F6\u5F00\u59CB\u642D\u3002",document:Ii("\u672A\u547D\u540D\u5F39\u7A97",wr([{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"},[Na])},{id:"announcement",label:"\u516C\u544A",description:"\u65B0\u529F\u80FD\u6216\u91CD\u8981\u901A\u77E5\uFF0C\u4E00\u4E2A\u4E3B\u6309\u94AE\u3002",document:Ii("\u65B0\u529F\u80FD\u516C\u544A",wr([{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},Na])},{id:"upgrade",label:"\u5347\u7EA7\u5230 Pro",description:"\u5217\u51FA\u51E0\u9879\u6743\u76CA\uFF0C\u5F15\u5BFC\u5347\u7EA7\u3002",document:Ii("\u5347\u7EA7\u5230 Pro",wr([{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},Na])},{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:{...Ii("\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},Na]),theme:{...Dm,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:Ii("\u6EE1\u610F\u5EA6\u8C03\u67E5",wr([{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 Fa(e="blank"){let t=km.find(n=>n.id===e)??km[0];if(!t)throw new Error("Screen templates are unavailable");return structuredClone(t.document)}var GS=(e,t,n)=>({type:"stack",id:e,name:"Web \u81EA\u9002\u5E94\u5E03\u5C40",direction:"horizontal",align:"center",justify:"center",children:[{...wr(t),id:`${e}_intro`,name:"\u4ECB\u7ECD",style:{width:480,gap:20,padding:{top:0,right:0,bottom:0,left:0}}},{...wr(n),id:`${e}_detail`,name:"\u5185\u5BB9\u4E0E\u64CD\u4F5C",style:{width:400,gap:20,padding:{top:24,right:24,bottom:24,left:24},background:{type:"color",color:"surface"},shape:{type:"rect",radius:8}}}],style:{gap:40,padding:{top:40,right:24,bottom:40,left:24}}});function ij(e,t="blank"){let n=Fa(t);if(e==="popup"||(n.surface=e,n.presentation={type:"fullscreen"},e==="page"))return n;if(e==="paywall"){let r=Fa("upgrade");r.actions=r.actions.map(o=>o.id==="upgrade"&&o.type==="event"?{...o,event:"paywall.upgrade_clicked",properties:{},close:!1}:o),(r.strings.locales["zh-CN"]??={}).cta="\u4E86\u89E3\u5347\u7EA7\u65B9\u6848",(r.strings.locales.en??={}).cta="Explore upgrade options",(r.strings.locales["zh-CN"]??={}).body="\u4E3A\u4F60\u7684\u5DE5\u4F5C\u533A\u9009\u62E9\u9002\u5408\u7684\u529F\u80FD\u4E0E\u534F\u4F5C\u65B9\u5F0F\u3002",(r.strings.locales.en??={}).body="Find the right features and collaboration tools for your workspace.";let i=r.pages[0];if(!i)throw new Error("Paywall template requires a page");let a=i.root.children;return i.root=GS("root",[...a.slice(0,2),{type:"text",id:"body",text:"body",variant:"body",style:{text:{color:"muted"}}}],a.slice(2)),{...r,surface:e,presentation:{type:"fullscreen"},name:"\u9AD8\u7EA7\u529F\u80FD\u4ED8\u8D39\u5899"}}return{...n,surface:e,presentation:{type:"fullscreen"}}}function Nm(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=Fa(),i=r.pages[0];if(!i)throw new Error("Blank template requires a page");return{...r,name:t==="en"?`Untitled ${n[e]}`:`\u672A\u547D\u540D${n[e]}`,surface:e,presentation:e==="popup"?{type:"modal",size:"md"}:{type:"fullscreen"},pages:[{id:"main",name:t==="en"?e==="onboarding"?"Start":"Main page":e==="onboarding"?"\u5F00\u59CB":"\u4E3B\u9875\u9762",root:{...i.root,name:t==="en"?"Canvas":"\u753B\u5E03",style:e==="popup"?{gap:16,padding:{top:32,right:28,bottom:28,left:28}}:{gap:16,padding:{top:24,right:24,bottom:24,left:24}},children:[]}}],strings:{defaultLocale:t,locales:{[t]:{}}},actions:[]}}import{z as pe}from"zod";var Ai=pe.number().int().min(0).max(1e4),lj=pe.strictObject({couponId:pe.uuid(),couponRevision:pe.number().int().nonnegative(),savedGroupId:pe.uuid(),savedGroupRevision:pe.number().int().nonnegative(),savedGroupName:pe.string().min(1).max(128),count:Ai,snapshotHash:pe.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:pe.iso.datetime({offset:!0})}),WS=pe.strictObject({id:pe.uuid(),couponId:pe.uuid(),couponName:pe.string().min(1).max(80),savedGroupId:pe.uuid(),savedGroupName:pe.string().min(1).max(128),savedGroupRevision:pe.number().int().nonnegative(),status:pe.enum(["pending","running","completed"]),total:Ai,issued:Ai,skipped:Ai,remaining:Ai,createdAt:pe.iso.datetime({offset:!0}),completedAt:pe.iso.datetime({offset:!0}).nullable()}).refine(e=>e.total>0&&e.total===e.issued+e.skipped+e.remaining&&e.status==="completed"==(e.completedAt!==null)&&(e.status!=="completed"||e.remaining===0)),KS=pe.strictObject({id:pe.uuid(),customerId:pe.uuid(),customerName:pe.string().max(255),position:pe.number().int().min(1).max(1e4),status:pe.enum(["pending","issued","skipped"]),grantId:pe.uuid().nullable(),reason:ma.nullable()}).refine(e=>e.status==="issued"==(e.grantId!==null)&&e.status==="skipped"==(e.reason!==null)),dj=pe.strictObject({batch:WS,recipients:pe.array(KS).max(50),nextPosition:pe.number().int().min(1).max(1e4).nullable()}),pj=pe.discriminatedUnion("action",[pe.strictObject({action:pe.literal("create"),requestId:pe.uuid(),couponId:pe.uuid(),couponRevision:pe.number().int().nonnegative(),savedGroupId:pe.uuid(),savedGroupRevision:pe.number().int().nonnegative(),snapshotHash:pe.string().regex(/^[a-f0-9]{64}$/)}),pe.strictObject({action:pe.literal("process"),batchId:pe.uuid()})]);import{z as L}from"zod";var ht=L.number().int().min(0),wi=L.iso.datetime({offset:!0}),Ua=L.strictObject({internalId:L.uuid(),version:L.number().int().positive()}),Fm=L.enum(["subscription_change_required","unsupported_operation_input"]),HS=L.enum([...Fm.options,"internal_error"]),hj=L.strictObject({productId:L.string().min(1),productName:L.string(),from:Ua,to:Ua,noBillingChanges:L.boolean(),counts:L.strictObject({customers:ht,movable:ht,blocked:ht,unsupported:ht,canceled:ht,custom:ht}),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:Fm.nullable()})).max(50),nextCursor:L.uuid().nullable()}),QS=L.enum(["queued","running","succeeded","no_changes","failed","canceled"]),Um=L.enum(["running","succeeded","skipped","failed"]),Mm=L.strictObject({internalId:L.uuid(),id:L.string().min(1),productId:L.string().min(1),productName:L.string(),from:Ua,to:Ua,noBillingChanges:L.boolean(),retryFailed:L.boolean(),step:L.enum(["queued","received","get_customers","migrate_customers","finished","failed"]),snapshot:L.strictObject({total_customers:ht,canceled_customers:ht,custom_customers:ht,migration_customers:ht}),createdAt:wi,run:L.strictObject({id:L.uuid(),status:QS,errorMessage:L.string().nullable(),createdAt:wi,startedAt:wi.nullable(),finishedAt:wi.nullable()}).nullable(),totals:L.strictObject({succeeded:ht,skipped:ht,failed:ht,running:ht,blocked:ht,remaining:ht})}),ZS=L.strictObject({customerId:L.uuid(),customerKey:L.string().nullable(),name:L.string().nullable(),email:L.string().nullable(),status:Um,skipReason:L.enum(["no_updates_needed","ineligible"]).nullable(),updatedAt:wi,error:L.strictObject({code:HS,message:L.string().nullable()}).nullable()}),gj=L.strictObject({migration:Mm,items:L.array(ZS).max(50),nextCursor:L.uuid().nullable()}),bj=L.array(Mm).max(20),_j=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()})]),yj=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:Um.optional(),after:L.uuid().optional()}),L.strictObject({action:L.literal("list"),productId:L.string().min(1).max(120)})]);import{z as ot}from"zod";var Zs=ot.iso.datetime({offset:!0}),Bm=ot.strictObject({internalId:ot.uuid(),productId:ot.string().min(1),name:ot.string(),version:ot.number().int().positive()}),YS=ot.strictObject({id:ot.uuid(),status:ot.literal("scheduled"),effectiveAt:Zs,createdAt:Zs,entityId:ot.string().nullable(),to:Bm,from:Bm.extend({customerProductId:ot.uuid(),status:ot.enum(["active","past_due","trialing"]),endsAt:Zs.nullable()}).nullable(),scheduleId:ot.uuid().nullable(),providerManaged:ot.boolean()}),xj=ot.array(YS).max(100),Ij=ot.strictObject({customerProductId:ot.uuid()});import{z as Pi}from"zod";var JS=Pi.url().refine(e=>new URL(e).protocol==="https:"),Pj=Pi.strictObject({requestId:Pi.uuid()}),Cj=Pi.strictObject({url:JS,createdAt:Pi.iso.datetime()});import{z as Ke}from"zod";var Lm=Ke.object({id:Ke.uuid(),key:Ke.string().nullable(),label:Ke.string().min(1).max(80),description:Ke.string().max(300),category:Ke.string().min(1).max(40),tags:Ke.array(Ke.string().max(30)).max(10),surface:Pu,source:Ke.enum(["official","private"]),document:It,revision:Ke.number().int().positive(),archived_at:Ke.string().nullable(),created_at:Ke.string()}).strict(),Rj=Ke.object({projectId:Ke.uuid(),environmentId:Ke.uuid(),label:Ke.string().trim().min(1).max(80),description:Ke.string().trim().max(300),category:Ke.string().trim().min(1).max(40),document:It}).strict(),jj=Ke.object({projectId:Ke.uuid(),environmentId:Ke.uuid(),id:Ke.uuid(),revision:Ke.number().int().positive()}).strict();import{z as M}from"zod";import{z as Oe}from"zod";import{z as st}from"zod";var Ze=st.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_.:-]*$/).refine(e=>e.split(".").every(t=>t.length>0&&!["__proto__","constructor","prototype"].includes(t)),"Reserved or empty variable path"),Ys=st.strictObject({type:st.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:st.boolean(),enum:st.array(st.string().max(255)).min(1).max(100).optional()}),Pr=Ys.extend({type:st.enum([...Ys.shape.type.options,"array"]),items:Ys.optional()}).superRefine((e,t)=>{(e.type==="array"!=!!e.items||e.enum&&e.type!=="string"||e.items?.enum&&e.items.type!=="string")&&t.addIssue({code:"custom",message:"Array requires items; only strings support enum"})}),Cr=Pr.safeExtend({source:st.discriminatedUnion("type",[st.strictObject({type:st.literal("input")}),st.strictObject({type:st.literal("node")}),st.strictObject({type:st.enum(["parameter","attribute"]),key:Ze})])}),XS=st.record(Ze,Cr),Ma=st.record(Ze,Ze).refine(e=>Object.keys(e).length<=20);function Xt(e,t){return e?t===null?e.nullable:e.enum&&(typeof t!="string"||!e.enum.includes(t))?!1:e.type==="array"?Array.isArray(t)&&t.length<=100&&!!e.items&&t.every(n=>Xt(e.items,n)):["offering_version","reward","paywall_version"].includes(e.type)?typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===2&&t.type===e.type&&st.uuid().safeParse(t.id).success:e.type==="json"||(e.type==="strings"?Array.isArray(t)&&t.every(n=>typeof n=="string"):typeof t===e.type):!1}function Js(e,t){return e.nullable&&!t.nullable?!1:t.type==="json"?!0:e.type!==t.type||t.enum&&(!e.enum||e.enum.some(n=>!t.enum.includes(n)))?!1:e.type!=="array"||!!e.items&&!!t.items&&Js(e.items,t.items)}function nr(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r;if(!Object.hasOwn(o,s))continue;let c=o[s];if(!Xt(i,c))throw new Error(`Invalid variable value: ${r}`);n[r]=c}return n}function Ci(e,t){let n={};for(let[r,i]of Object.entries(e.writes??{})){if(!Object.hasOwn(t,r))throw new Error(`Node output is missing: ${r}`);if(Object.hasOwn(n,i))throw new Error("Node outputs cannot overwrite one another");n[i]=t[r]}return n}function zS(e,t,n){let r=new Set(Object.values(t.writes??{}));for(let[i,a]of Object.entries(n))if(!r.has(i)||e[i]?.source.type!=="node"||!Xt(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var Oi=Ie;function qm(e){let t={};for(let[n,r]of Object.entries(nr(e.declarations,e))){let i=n.split(".");if(i.some(s=>["__proto__","constructor","prototype"].includes(s)))throw new Error("Reserved result path");let a=t;for(let s of i.slice(0,-1)){Object.hasOwn(a,s)||(a[s]={});let c=a[s];if(!c||typeof c!="object"||Array.isArray(c))throw new Error("Ambiguous result path");a=c}let o=i.at(-1);if(o===void 0)throw new Error("Empty result path");a[o]=r}return{...e.attributes,variables:t}}function Xs(e,t){return Ki(qm(t),e,t.savedGroups)}function Ei(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 rr}from"zod";var $t=rr.string().min(1).max(255).regex(/^[a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+){0,9}$/).refine(e=>e.split(".").every(t=>!["__proto__","constructor","prototype"].includes(t)),"Reserved value path"),cn=rr.discriminatedUnion("source",[rr.strictObject({source:rr.literal("literal"),value:Ie}),rr.strictObject({source:rr.literal("variable"),key:rr.string().min(1).max(255),path:$t.optional()})]);function Or(e,t){if(!t)return e;for(let n of $t.parse(t).split(".")){if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Ti(e,t){if(e.source==="literal")return structuredClone(e.value);let n=nr(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Ie.parse(Or(n[e.key],e.path)))}function Vm(e,t){let n={},r=Object.entries(e).sort(([i],[a])=>i.split(".").length-a.split(".").length||i.localeCompare(a,"en",{numeric:!0}));for(let[i,a]of r){let o=$t.parse(i).split("."),s=n;for(let u=0;u<o.length-1;u++){let l=o[u],d=o[u+1];if(l===void 0||d===void 0)throw new Error("Invalid binding path");if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>s.length))throw new Error("Invalid array binding index");Object.hasOwn(s,l)||Reflect.set(s,l,/^(0|[1-9]\d*)$/.test(d)?[]:{});let p=Array.isArray(s)?s[Number(l)]:s[l];if(!p||typeof p!="object")throw new Error("Nested input requires an object or array");if(Array.isArray(p)!==/^(0|[1-9]\d*)$/.test(d))throw new Error("Nested input container does not match its path");s=p}let c=o.at(-1);if(Array.isArray(s)&&(!/^(0|[1-9]\d*)$/.test(c)||Number(c)>s.length))throw new Error("Invalid array binding index");Reflect.set(s,c,Ti(a,t))}return n}var Ba=Oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),$m=Oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),La=qt.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),zs=Oe.record(Ba,Oe.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),e0=cn,Gm=Oe.strictObject({type:Oe.literal("external_task"),endpointId:Oe.uuid(),taskKey:Ba,inputs:Oe.record(Ba,e0).refine(e=>Object.keys(e).length<=20),outputs:zs}),Wm=Oe.strictObject({maxAttempts:Oe.number().int().min(1).max(5),retryDelaySeconds:Oe.number().int().min(1).max(30),backoff:Oe.enum(["fixed","exponential"]),requestTimeoutSeconds:Oe.number().int().min(1).max(10),timeoutSeconds:Oe.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline"),Qj={maxAttempts:4,retryDelaySeconds:5,backoff:"fixed",requestTimeoutSeconds:8,timeoutSeconds:120},Zj=Oe.strictObject({outcome:Oe.enum(["success","failure"]),data:La});function Yj(e,t){let n=La.parse(t);if(Object.keys(n).length!==Object.keys(e).length||Object.entries(e).some(([r,i])=>!Object.hasOwn(n,r)||(i==="strings"?!Array.isArray(n[r])||!n[r].every(a=>typeof a=="string"):typeof n[r]!==i)))throw new Error("Task data does not match its declared outputs");return n}function Jj(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=Ti(i,t);return La.parse(n)}var Xj=Oe.discriminatedUnion("operation",[Oe.strictObject({operation:Oe.literal("signal"),runId:Oe.uuid(),nodeId:$m,eventName:Ba,eventId:Oe.uuid(),data:La}),Oe.strictObject({operation:Oe.literal("read_results"),runId:Oe.uuid()})]),zj=Oe.strictObject({scope:je,runId:Oe.uuid(),eventId:Oe.uuid(),accepted:Oe.boolean()}),t0=Oe.record($m,Oi),ek=Oe.strictObject({scope:je,runId:Oe.uuid(),results:t0});import{z as U}from"zod";import{z as De}from"zod";var ec=De.enum(["local","remote"]),Ri=De.strictObject({port:De.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Ie.optional(),sticky:De.array(De.strictObject({expected:Hi.nullable(),next:Hi})).max(100),exposures:De.array(Ie).max(100),features:De.array(Ie).max(100)}),qa=De.strictObject({type:De.literal("evaluate"),receiptId:De.uuid(),environmentId:De.uuid(),policyRevision:De.number().int().nonnegative(),attributes:Bt,sticky:De.record(De.string(),Hi)}),Km=qa.extend({runId:De.uuid(),versionId:De.uuid(),nodeId:De.string().min(1).max(64),visit:De.number().int().nonnegative(),revision:De.number().int().nonnegative()}),tc=qa.omit({type:!0,receiptId:!0}).extend({type:De.literal("evaluate_segment")}),Va=De.strictObject({nodeId:De.string().min(1).max(64),result:Ri}),Hm=tc.extend({runId:De.uuid(),versionId:De.uuid(),nodeId:De.string().min(1).max(64),visit:De.number().int().nonnegative(),revision:De.number().int().nonnegative(),parameters:qt,answers:$n,variables:De.record(De.string(),Ie)});var ji=U.discriminatedUnion("type",[U.strictObject({type:U.literal("literal"),value:Ie}),U.strictObject({type:U.literal("variable"),key:Ze,path:$t.optional()}),U.strictObject({type:U.literal("feature"),featureKey:U.string().min(1).max(128)})]),n0=U.strictObject({requestId:U.uuid(),decisionId:U.uuid(),customerId:U.uuid(),externalUserId:U.string().min(1).max(255).nullable(),versionId:U.uuid(),receiptId:U.uuid(),value:Ie}),nc={funnelId:U.uuid(),requestId:U.uuid(),customer:xr,customerData:Ir.optional(),attributes:Bt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},mk=U.discriminatedUnion("operation",[U.strictObject({operation:U.literal("decide"),...nc}).refine(er,tr),U.strictObject({operation:U.literal("read_decision"),decisionId:U.uuid()}),U.strictObject({operation:U.literal("evaluate_decision"),decisionId:U.uuid(),requestId:U.uuid(),nodeId:U.string().min(1).max(64),visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),receiptId:U.uuid(),policyRevision:U.number().int().nonnegative(),generation:U.string().min(1).max(256),result:Ri}),U.strictObject({operation:U.literal("feature_config"),funnelId:U.uuid()}),U.strictObject({operation:U.literal("commit_decision_segment"),decisionId:U.uuid(),requestId:U.uuid(),nodeId:U.string().min(1).max(64),visit:U.number().int().nonnegative(),revision:U.number().int().nonnegative(),policyRevision:U.number().int().nonnegative(),generation:U.string().min(1).max(256),steps:U.array(Va).max(32),boundary:U.strictObject({nodeId:U.string().min(1).max(64),visit:U.number().int().nonnegative()}).optional()}),U.strictObject({operation:U.literal("segment_configuration"),funnelId:U.uuid(),versionId:U.uuid()}),U.strictObject({operation:U.literal("configuration"),funnelId:U.uuid(),versionId:U.uuid().optional()}),U.strictObject({operation:U.literal("local_configuration"),funnelId:U.uuid()}),U.strictObject({operation:U.literal("report_used"),decisionId:U.uuid(),eventId:U.uuid(),occurredAt:U.iso.datetime({offset:!0}),reference:U.string().min(1).max(128).optional()})]),fk=U.strictObject({scope:je,decisionId:U.uuid(),requestId:U.uuid(),status:U.enum(["pending","completed","failed"]),decision:n0.nullable(),evaluation:U.discriminatedUnion("type",[Km,Hm]).optional()}).refine(e=>e.status==="completed"==(e.decision!==null)&&(!e.decision||e.decision.decisionId===e.decisionId&&e.decision.requestId===e.requestId),"Completed decisions carry their committed result"),hk=U.strictObject({scope:je,decisionId:U.uuid(),eventId:U.uuid(),source:U.literal("caller_reported")});import{z as Je}from"zod";var Qm=Je.strictObject({type:Je.literal("bundle"),paywall:cn.optional(),offering:cn.optional(),coupons:cn,data:cn}),$a=e=>Je.strictObject({type:Je.literal(e),id:Je.uuid()}),r0=Je.strictObject({type:Je.literal("bundle"),paywallVersionId:Je.uuid().optional(),offeringVersionId:Je.uuid().optional(),couponIds:Je.array(Je.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Ie});function vk(e,t,n){let r=a=>Ti(a,t),i=Je.array($a("reward")).max(20).parse(r(e.coupons));for(let a of[e.paywall,e.offering,e.coupons]){if(!a)continue;let o=r(a);for(let s of Array.isArray(o)?o:[o])if(!s||typeof s!="object"||Array.isArray(s)||!Object.values(n).some(c=>c.type===s.type&&c.id===s.id))throw new Error("Bundle resource outside pinned references")}return r0.parse({type:"bundle",...e.paywall?{paywallVersionId:$a("paywall_version").parse(r(e.paywall)).id}:{},...e.offering?{offeringVersionId:$a("offering_version").parse(r(e.offering)).id}:{},couponIds:i.map(a=>a.id),data:r(e.data)})}var xk=Je.strictObject({type:Je.literal("bundle"),offering:$a("offering_version").nullable(),paywall:Je.strictObject({versionId:Je.uuid(),paywallId:Je.uuid(),offeringVersionId:Je.uuid()}).nullable(),coupons:Je.array(oi).max(20),data:Ie});function Ik(e){let t=a=>a?.source==="literal"&&a.value&&typeof a.value=="object"&&!Array.isArray(a.value)&&typeof a.value.id=="string"?a.value.id:void 0,n=e.coupons.source==="literal"&&Array.isArray(e.coupons.value)?e.coupons.value:[],r=t(e.paywall),i=t(e.offering);return{type:"bundle",...r?{paywallVersionId:r}:{},...i?{offeringVersionId:i}:{},couponIds:n.flatMap(a=>a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?[a.id]:[]),data:e.data.source==="literal"?e.data.value:{variable:e.data.key}}}import{z as zt}from"zod";import{z as ct}from"zod";var Zm=ct.union([ct.string(),ct.number().finite(),ct.boolean(),ct.null()]),i0=ct.union([Zm,ct.array(Zm).min(1).max(20)]),a0=ct.record($t,i0).refine(e=>Object.keys(e).length<=10),rc=ct.strictObject({path:$t,type:ct.enum(["string","number","boolean","strings"]),nullable:ct.boolean().optional(),aggregation:ct.enum(["count","exists"]).optional(),where:a0.optional()}).superRefine((e,t)=>{(e.aggregation==="count"&&e.type!=="number"||e.aggregation==="exists"&&e.type!=="boolean"||!e.aggregation&&e.where)&&t.addIssue({code:"custom",message:"Collection summaries require their matching type"})});function Ck(e,t){return Object.fromEntries(Object.entries(e).map(([n,r])=>{let i=rc.parse(r),a=Or(t,i.path);if(i.nullable&&a==null)return[n,null];if(i.aggregation){if(!Array.isArray(a))throw new Error("Collection projection requires an array");let s=a.filter(c=>Object.entries(i.where??{}).every(([u,l])=>{let d=Or(c,u);return Array.isArray(l)?l.some(p=>p===d):l===d}));return[n,i.aggregation==="count"?s.length:s.length>0]}let o=i.type==="strings"?ct.array(ct.string()):i.type==="string"?ct.string():i.type==="number"?ct.number().finite():ct.boolean();return[n,o.parse(a)]}))}var o0=["checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","previewAttach","attach","readSubscriptionOperation","previewUpdate","update","readSubscriptionUpdate","setupPayment","readPaymentSetup","verifySubscriptions","previewRefund","refund","readRefund","restoreNativePurchase","readBillingControls","prepareBillingAuthorization","confirmBillingAuthorization","setBillingCoupons","revokeBillingAuthorization","listBillingInvoices","confirmBillingAdjustment","manageBillingLimits","readSeats","manageSeat","quoteBalance","mutateBalance","trackUsage","readUsage","setUsage","adjustBalance","readBalanceSource","manageBalanceGrant","listBalanceGrants","manageUsageEntity","readUsageAnalytics","readCreditAnalytics","submitUsageBatch","readUsageBatch","redeemCoupon","listOffers","grantOffer","redeemReward","createReferralCode","claimRewardProduct"],Ym=zt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),s0=cn,Jm=zt.discriminatedUnion("type",[Gm,zt.strictObject({type:zt.literal("claim_offer"),coupon:cn}),zt.strictObject({type:zt.literal("event"),event:Ym}),zt.strictObject({type:zt.literal("api"),operation:zt.enum(o0),inputs:zt.record($t,s0).refine(e=>Object.keys(e).length<=40),outputs:zt.record(Ym,rc).refine(e=>Object.keys(e).length<=20)})]);function kk(e,t){return Vm(e,t)}var Ge=M.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),c0=M.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),kt={id:Ge,name:M.string().trim().min(1).max(80),position:M.strictObject({x:M.number().finite(),y:M.number().finite()}).optional()},u0={success:Ge,cancel:Ge,unavailable:Ge,failure:Ge},ic=M.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),ac=M.enum(["same_window","new_window"]),l0=M.discriminatedUnion("type",[M.strictObject({...kt,type:M.literal("entry"),next:Ge}),M.strictObject({...kt,type:M.literal("screen"),screenId:Ge,presentation:gn,outputs:M.record(Ge,Ge),offering:M.discriminatedUnion("source",[M.strictObject({source:M.literal("variable"),key:Ze}),M.strictObject({source:M.literal("fixed"),versionId:M.uuid()})]).optional()}),M.strictObject({...kt,type:M.literal("offering"),configuration:M.discriminatedUnion("source",[M.strictObject({source:M.literal("fixed"),versionId:M.uuid()}),M.strictObject({source:M.literal("feature"),featureKey:M.string().min(1).max(128)})]),writes:M.strictObject({value:Ze}),next:Ge}),M.strictObject({...kt,type:M.literal("coupon"),couponId:M.uuid(),writes:M.strictObject({value:Ze}),next:Ge}),M.strictObject({...kt,type:M.literal("coupons"),couponIds:M.array(M.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:M.strictObject({value:Ze}),next:Ge}),M.strictObject({...kt,type:M.literal("output"),value:M.discriminatedUnion("type",[...ji.options,Qm,M.strictObject({type:M.literal("selection"),screenId:Ge,offeringKey:Ze})])}),M.strictObject({...kt,type:M.literal("condition"),cases:M.array(M.strictObject({condition:xn,target:Ge})).min(1).max(50),default:Ge}),M.strictObject({...kt,type:M.literal("feature"),featureKey:M.string().min(1).max(128),writes:M.strictObject({value:Ze}),next:Ge}),M.strictObject({...kt,type:M.literal("split"),experimentId:M.uuid(),routes:M.record(c0,Ge).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Ge}),M.strictObject({...kt,type:M.literal("action"),...u0,execution:Wm,action:Jm,writes:Ma.optional()}),M.strictObject({...kt,type:M.literal("external_page"),url:ic,openIn:ac,opened:Ge,failed:Ge}),M.strictObject({...kt,type:M.literal("end"),outcome:M.enum(["completed","closed","ineligible","failed"]),output:ji.optional()}),M.strictObject({...kt,type:M.literal("wait"),writes:Ma.optional(),wait:M.discriminatedUnion("type",[M.strictObject({type:M.literal("duration"),delaySeconds:M.number().int().min(1).max(2592e3),elapsed:Ge}),M.strictObject({type:M.literal("event"),eventName:Ge,outputs:zs,timeoutSeconds:M.number().int().min(1).max(2592e3),received:Ge,timeout:Ge})])})]),oc=M.strictObject({version:M.literal(5),entry:Ge,nodes:M.array(l0).min(1).max(Qe.flowNodes)}),sc=oc.superRefine((e,t)=>{d0(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Er(e){switch(e.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":return[e.next];case"screen":return Object.values(e.outputs);case"condition":return[...e.cases.map(t=>t.target),e.default];case"split":return[...Object.values(e.routes),e.notParticipating];case"action":return[e.success,e.cancel,e.unavailable,e.failure];case"external_page":return[e.opened,e.failed];case"end":case"output":return[];case"wait":return e.wait.type==="duration"?[e.wait.elapsed]:[e.wait.received,e.wait.timeout]}}function d0(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,d,p)=>{n.push(l),t?.({message:l,reason:d,path:p?["nodes",e.nodes.indexOf(p)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>Qe.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>Qe.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let d of Er(l))d===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(d)||i(`Missing target ${d}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let d of Er(r.get(l)))u(d);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}function p0(e,t){let n=e.cases.findIndex(r=>Xs(r.condition,t));return{ruleIndex:n<0?null:n,target:e.cases[n]?.target??e.default}}function Wk(e,t,n,r){let i=e.nodes.find(c=>c.id===t.nodeId),a=[...t.history];if(!i||!["running","waiting"].includes(t.status))throw new Error("Flow is not active");let o,s=[];switch(n.type){case"start":if(i.type!=="entry")throw new Error("Flow already started");o=i.next;break;case"next":if(i.type!=="screen"||!Object.hasOwn(i.outputs,n.output)||i.outputs[n.output]===void 0)throw new Error("Invalid screen output");{let c=i.outputs[n.output];if(c===void 0)throw new Error("Invalid screen output");o=c}a.push(i.id);break;case"back":if(i.type!=="screen"||!a.length)throw new Error("No previous screen");if(o=a.pop(),e.nodes.find(c=>c.id===o)?.type!=="screen")throw new Error("Invalid screen history");break;case"condition":if(i.type!=="condition")throw new Error("Not a condition node");{let c=p0(i,r);o=c.target,s.push({nodeId:i.id,...c})}break;case"feature":if(i.type!=="feature")throw new Error("Not a Feature node");o=i.next;break;case"configuration":if(i.type!=="offering"&&i.type!=="coupon")throw new Error("Not a configuration node");o=i.next;break;case"assignment":if(i.type!=="split")throw new Error("Not an Experiment node");{let c=n.variantId===null?i.notParticipating:i.routes[n.variantId];if(!c)throw new Error("Unknown native Variant key");o=c}break;case"result":if(i.type!=="action")throw new Error("Not a capability invocation");o=i[n.result];break;case"page":if(i.type!=="external_page")throw new Error("Not an external page");o=i[n.result];break;case"wait":if(i.type!=="wait")throw new Error("Not a wait node");if(i.wait.type==="duration"){if(n.result!=="elapsed")throw new Error("Invalid timer result");o=i.wait.elapsed}else{if(n.result==="elapsed")throw new Error("Invalid event result");o=i.wait[n.result]}break}if(!e.nodes.some(c=>c.id===o))throw new Error("Target does not exist");return{state:{nodeId:o,history:a.slice(-Qe.pages),status:"running"},entered:[o],routed:s}}import{z as cc}from"zod";var ki=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function zk(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>Ki(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new ki("Required GB Feature is unavailable");i=wo(e.featureKey,t),o=i.value,Object.assign(r,Ci(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new ki("Required GB Experiment is unavailable");if(a=au(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new ki("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:wo(e.configuration.featureKey,t).value;o={type:"offering_version",id:cc.uuid().parse(u)},Object.assign(r,Ci(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,Ci(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function Xm(e,t,n){cc.uuid().parse(e),cc.number().int().nonnegative().parse(t);let r=Gi(Wi(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as nt}from"zod";import{z as gt}from"zod";var Tr=gt.string().regex(/^[a-f0-9]{64}$/),m0=xu.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),zm=gt.strictObject({couponDigests:gt.record(gt.uuid(),Tr),variables:gt.record(mn,gt.record(gt.uuid(),gt.partialRecord(gt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),gt.string()))),locales:gt.record(mn,lr.extend({nodes:gt.record(gt.string(),gt.strictObject({base:m0})),plans:gt.object({}).strict(),pickers:gt.object({}).strict()}).omit({paywall:!0}))});var ef=nt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),uD=nt.strictObject({operation:nt.literal("resolve_screen"),funnelId:nt.uuid(),versionId:nt.uuid(),screenId:ef,locale:mn,customerId:nt.uuid().optional()}),lD=nt.strictObject({scope:je,funnelId:nt.uuid(),versionId:nt.uuid(),screenId:ef,locale:mn,coupons:nt.record(nt.uuid(),nt.strictObject({available:nt.boolean(),offer:nt.strictObject({id:nt.uuid(),expiresAt:nt.iso.datetime()}).nullable()})),couponDigests:nt.record(nt.uuid(),Tr)});import{z as E}from"zod";function Ga(e,t){let n=[...t].sort((i,a)=>a.length-i.length).find(i=>e===i||e.startsWith(i+"."));if(!n)return null;let r=e===n?void 0:e.slice(n.length+1);return r&&!$t.safeParse(r).success?null:{key:n,path:r}}function uc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Lt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Iu))]}function lc(e){return uc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function bD(e,t){let n=nr(t.declarations,t);return Object.fromEntries(lc(e).flatMap(r=>{let i=Ga(r,Object.keys(t.declarations)),a=i&&Object.hasOwn(n,i.key)?Or(n[i.key],i.path):void 0;return a!==void 0?[[r,Ie.parse(a)]]:[]}))}function _D(e,t,n){let r=i=>i.replace(/\{\{\s*variables\.([^{}]+?)\s*\}\}/g,(a,o)=>(o=o.trim(),o===t||o.startsWith(t+".")?"{{ variables."+n+o.slice(t.length)+" }}":a));return e.screens.map(i=>{if(i.type!=="owned")return i;let a=structuredClone(i.document);for(let o of Object.values(a.strings.locales))for(let s of Object.keys(o))o[s]=r(o[s]);return Lt(a,o=>{if(o.type==="custom_html")for(let s of Object.keys(o.html))o.html[s]=r(o.html[s])}),{...i,document:a}})}function tf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Ei(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as C}from"zod";var Rr=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Wa=e=>C.record(C.string(),Ie).refine(t=>wt(t)<=e,"Funnel evidence exceeds its byte budget"),wD=C.enum(["local_segment","evaluation","presentation","timer","event","operation"]),pc=C.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),mc=C.discriminatedUnion("type",[C.strictObject({type:C.literal("flag"),key:C.string().min(1).max(128)}),C.strictObject({type:C.literal("experiment"),id:C.uuid()}),C.strictObject({type:C.literal("saved_group"),id:C.uuid()}),C.strictObject({type:C.literal("config"),key:C.string().min(1).max(128)}),C.strictObject({type:C.literal("constant"),key:C.string().min(1).max(128)}),C.strictObject({type:C.literal("paywall_version"),id:C.uuid()}),C.strictObject({type:C.literal("offering_version"),id:C.uuid()}),C.strictObject({type:C.literal("reward"),id:C.uuid()})]),jr=C.strictObject({schemaVersion:C.literal(1),kind:pc,selector:mc.nullable(),context:Wa(131072),contract:C.strictObject({version:C.number().int().positive(),evaluator:C.string().min(1).max(128),policyRevision:C.number().int().nonnegative()})}).refine(e=>wt(e)<=131072,"Node input exceeds its byte budget"),nf=C.strictObject({schemaVersion:C.literal(1),kind:pc,outcome:C.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Wa(131072),route:C.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Wa(131072)}).refine(e=>wt(e)<=131072,"Node result exceeds its byte budget"),PD=C.strictObject({schemaVersion:C.literal(1),operations:C.record(Rr,C.strictObject({attempts:C.number().int().nonnegative(),maxAttempts:C.number().int().min(1).max(5),deadlineAt:C.iso.datetime({offset:!0}),retryAt:C.iso.datetime({offset:!0}).nullable(),error:C.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:C.strictObject({type:Rr,id:C.uuid()}).nullable()}))}).refine(e=>wt(e)<=65536,"Execution state exceeds its byte budget"),ir={receiptId:C.uuid()},dc=C.iso.datetime({offset:!0}),CD=C.discriminatedUnion("type",[C.strictObject({type:C.literal("node_entered"),details:C.strictObject({kind:pc})}),C.strictObject({type:C.literal("presentation_shown"),details:C.strictObject({...ir,source:C.literal("client"),occurredAt:dc.optional()})}),C.strictObject({type:C.literal("decision_accepted"),details:C.strictObject(ir)}),C.strictObject({type:C.literal("signal_received"),details:C.strictObject({signalId:C.uuid(),nodeId:Rr,eventName:Rr,data:Wa(8192),source:C.literal("server"),occurredAt:dc})}),C.strictObject({type:C.literal("signal_consumed"),details:C.strictObject({...ir,signalId:C.uuid()})}),C.strictObject({type:C.literal("wait_elapsed"),details:C.strictObject(ir)}),C.strictObject({type:C.literal("wait_timeout"),details:C.strictObject(ir)}),C.strictObject({type:C.literal("operation_completed"),details:C.strictObject({...ir,operation:Rr,reference:C.strictObject({type:Rr,id:C.uuid()}).nullable()})}),C.strictObject({type:C.literal("execution_recovered"),details:C.strictObject({generation:C.number().int().positive(),reason:C.enum(["interrupted","expired_lease","delivery_failed"])})}),C.strictObject({type:C.literal("execution_failed"),details:C.strictObject({generation:C.number().int().positive(),code:C.string().regex(/^[a-z_]{1,64}$/)})}),C.strictObject({type:C.literal("run_completed"),details:C.strictObject({outcome:C.enum(["completed","ineligible","failed"])})}),C.strictObject({type:C.literal("run_closed"),details:C.strictObject({source:C.enum(["client","server","expiry"])})}),C.strictObject({type:C.literal("treatment_used"),details:C.strictObject({...ir,source:C.enum(["client","server"]),occurredAt:dc,reference:C.string().min(1).max(128).optional()})})]);var Gt=E.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),f0=E.discriminatedUnion("type",[E.strictObject({id:Gt,type:E.literal("owned"),publicData:zm.optional(),document:It.refine(e=>e.surface!=="paywall"&&e.pages.length===1&&e.actions.every(t=>t.type==="event"&&!t.close),"A Funnel owns one Page or Popup per screen and emits outputs; Paywall owns its purchase policies")}),E.strictObject({id:Gt,type:E.literal("paywall"),paywallVersionId:E.uuid()})]),hc={kind:E.literal("funnel"),schemaVersion:E.literal(4),screens:E.array(f0).max(Qe.pages),references:E.record(Gt,mc).refine(e=>Object.keys(e).length<=500),inputs:E.array(E.strictObject({variable:Gt,screenId:Gt,componentId:Gt,required:E.boolean()})).max(Qe.questions),variables:E.record(Ze,Cr).refine(e=>Object.keys(e).length<=Qe.logicNodes),outputSchema:Pr,execution:E.strictObject({runTimeoutSeconds:E.number().int().min(1).max(Da.runTimeoutSeconds),maxTransitions:E.number().int().min(1).max(Da.maxTransitions)})},Dt=E.strictObject({...hc,graph:oc});function rf(e,t){let n=(g,m,h=[])=>t.addIssue({code:"custom",message:g,path:h,params:{reason:m}}),r=Object.values(e.references),i=new Map(e.screens.map(g=>[g.id,g])),a=(g,m)=>r.some(h=>h.type===g&&("id"in h?h.id:h.key)===m);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(g=>g.type==="screen");(o.length!==i.size||o.some(g=>!i.has(g.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(g=>c.some(m=>g!==m&&m.startsWith(g+".")))&&n("Variable paths must not overlap","variable");function u(g,m){Object.hasOwn(e.variables,g)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(m)]);let h=s.get(g)??new Set;h.add(m.id),s.set(g,h)}for(let[g,m]of e.graph.nodes.entries()){let h=["graph","nodes",g],y=m.type==="feature"?m.featureKey:m.type==="offering"&&m.configuration.source==="feature"?m.configuration.featureKey:m.type==="output"&&m.value.type==="feature"?m.value.featureKey:m.type==="end"&&m.output?.type==="feature"?m.output.featureKey:null;y&&!a("flag",y)&&n("Flag selectors require an explicit GB resource reference","feature",h);let w=m.type==="feature"||m.type==="offering"||m.type==="coupon"||m.type==="coupons"||m.type==="action"&&m.action.type==="api"?["value"]:m.type==="action"&&m.action.type==="external_task"?Object.keys(m.action.outputs):m.type==="wait"&&m.wait.type==="event"?Object.keys(m.wait.outputs):[],x="writes"in m?m.writes??{}:{};(w.length!==Object.keys(x).length||w.some(I=>!Object.hasOwn(x,I))||new Set(Object.values(x)).size!==Object.values(x).length)&&n("Node writes must map every named output exactly once","variable",h);for(let[I,v]of Object.entries(x)){u(v,m);let K=e.variables[v],$=m.type==="offering"?"offering_version":m.type==="coupon"?"reward":m.type==="action"&&m.action.type==="api"?"json":m.type==="action"&&m.action.type==="external_task"?m.action.outputs[I]:m.type==="wait"&&m.wait.type==="event"?m.wait.outputs[I]:void 0;(K?.source.type!=="node"||$&&K.type!==$)&&n("Node writer source or output type does not match declaration","variable",h)}if(m.type==="coupons"){let I=e.variables[m.writes.value];(I?.type!=="array"||I.items?.type!=="reward"||I.items.nullable||I.nullable)&&n("Coupons output requires a non-null Reward array","variable",h);for(let v of m.couponIds)a("reward",v)||n("Coupons require Reward references","coupon",h)}if(m.type==="split"&&!a("experiment",m.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",h),m.type==="coupon"&&!a("reward",m.couponId)&&n("Coupon selectors require a Reward reference","coupon",h),m.type==="action"&&m.action.type==="claim_offer"&&m.action.coupon.source==="literal"){let I=m.action.coupon.value;(!I||typeof I!="object"||Array.isArray(I)||I.type!=="reward"||typeof I.id!="string"||Object.keys(I).length!==2||!a("reward",I.id))&&n("Coupon claims require a Reward reference","coupon",h)}if(m.type==="offering"&&m.configuration.source==="fixed"&&!a("offering_version",m.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",h),m.type==="screen"&&m.offering?.source==="variable"&&e.variables[m.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",h),m.type==="action"&&m.action.type==="claim_offer"&&m.action.coupon.source==="variable"&&(e.variables[m.action.coupon.key]?.type!=="reward"||m.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",h),m.type==="screen"){let I=i.get(m.screenId);if(m.offering?.source==="fixed"&&!a("offering_version",m.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",h),I?.type==="paywall"&&m.offering&&n("Paywall owns its fixed Offering Version","offering",h),I?.type==="paywall"&&!a("paywall_version",I.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",h),I?.type==="owned"){let v=I.document.pages[0];if(!v){n("Owned screen requires a page","screen",h);continue}Yi(I.document).some($=>!$.complete)&&n("Owned screens require complete local content","translations",h);let K=new Set(I.document.actions.map($=>$.id));(K.size!==Object.keys(m.outputs).length||Object.keys(m.outputs).some($=>!K.has($)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",h),zr(v.root,$=>{!m.offering&&($.type==="plan_picker"||($.type==="stack"||$.type==="button")&&$.bind?.plan||$.type==="customer_data"&&["customer_plans","credit_packs"].includes($.data.source))&&n("Product presentation requires an Offering Version","offering",h),$.type==="customer_data"&&Object.values($.data.outputs??{}).some(we=>we!==void 0&&!K.has(we))&&n("Customer components require declared screen outcomes","componentOutput",h)})}}m.type==="end"&&["completed","ineligible"].includes(m.outcome)&&!m.output&&n("Completed and ineligible ends require a declared output","output",h),m.type==="end"&&m.output?.type==="literal"&&!Xt(e.outputSchema,m.output.value)&&n("Terminal output does not match outputSchema","output",h),m.type==="output"&&m.value.type==="literal"&&!Xt(e.outputSchema,m.value.value)&&n("Terminal output does not match outputSchema","output",h);let k=m.type==="output"?m.value:m.type==="end"?m.output:void 0;if(k?.type==="variable"&&!k.path){let I=e.variables[k.key];I&&!Js(I,e.outputSchema)&&n("Variable output does not match outputSchema","output",h)}if(m.type==="screen"){let I=i.get(m.screenId);if(I?.type==="owned")for(let v of uc(I.document))(/^(input|params)\./.test(v)||v.startsWith("variables.")&&!Ga(v.slice(10),c))&&n("Screen values must reference registered variables","variable",h)}if(m.type==="condition")for(let I of m.cases){for(let v of cr(I.condition))a("saved_group",v)||n("Conditions require explicit Saved Group references","savedGroup",h);for(let v of Ei(I.condition))v.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",h)}if(m.type==="output"&&m.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",h);for(let[I,v]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let K=m.value[I];if(K)if(K.source==="literal"){let $=I==="coupons"?K.value:[K.value];(!Array.isArray($)||$.length>20||$.some(we=>!Xt({type:v,nullable:!1},we)||!a(v,we.id))||I==="coupons"&&new Set($.map(we=>we.id)).size!==$.length)&&n("Bundle requires distinct scoped resource references",I==="coupons"?"coupon":I==="paywall"?"paywall":"offering",[...h,"value",I])}else{let $=e.variables[K.key];(K.path||!$||$.nullable||(I==="coupons"?$.type!=="array"||$.items?.type!=="reward"||$.items.nullable:$.type!==v))&&n("Bundle binding type does not match its slot","output",h)}}}}for(let[g,m]of e.graph.nodes.entries()){let h=m.type==="screen"?i.get(m.screenId):void 0,y=[...tf(m,c),...h?.type==="owned"?lc(h.document).map(w=>Ga(w,c)?.key??w):[]];for(let w of new Set(y)){let v=function(K){if(K===m.id)return!0;if(I.has(K))return!1;I.add(K);let $=e.graph.nodes.find(Te=>Te.id===K);return $?(k.has(K)?$.type==="action"?[$.cancel,$.unavailable,$.failure]:$.type==="wait"&&$.wait.type==="event"?[$.wait.timeout]:[]:Er($)).some(v):!1};var p=v;if(!Object.hasOwn(e.variables,w)){n("Consumed variable is undeclared","variable",["graph","nodes",g]);continue}let x=e.variables[w];if(m.type==="screen"&&x.source.type==="input"&&e.inputs.some(K=>K.screenId===m.screenId&&K.variable===w)||x.source.type==="parameter"||x.source.type==="attribute")continue;let k=x.source.type==="input"?new Set(e.inputs.filter(K=>K.variable===w&&K.required).flatMap(K=>o.filter($=>$.screenId===K.screenId).map($=>$.id))):s.get(w)??new Set,I=new Set;(!k.size||v(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",g])}}(new Set(e.inputs.map(g=>g.variable)).size!==e.inputs.length||new Set(e.inputs.map(g=>`${g.screenId}:${g.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[g,m]of e.inputs.entries()){e.variables[m.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",g]);let h=i.get(m.screenId),y=h?.type==="owned"?Cu(h.document,m.componentId):null;if((y?.type!=="stack"||!y.interaction||!["input","toggle","select","multiselect","tabs"].includes(y.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",g]),y?.type==="stack"&&y.interaction){let w=y.interaction.type==="toggle"?"boolean":y.interaction.type==="multiselect"?"strings":"string";e.variables[m.variable]?.type!==w&&n("Input variable type does not match component","inputBinding",["inputs",g]);let x=e.variables[m.variable]?.enum;x&&!y.children.filter(k=>!k.hidden).every(k=>x.includes(k.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",g])}}for(let[g,m]of Object.entries(e.variables))m.enum&&m.type!=="string"&&n("Only string variables support enum","variable",["variables",g]),m.source.type==="input"&&!e.inputs.some(h=>h.variable===g)&&n("Input variable requires a component binding","inputBinding",["variables",g]);let l=0,d=0;for(let g of e.screens)if(g.type==="owned"){for(let m of g.document.pages)zr(m.root,()=>{l++});d+=g.document.actions.length}(l>Qe.components||d>Qe.actions||wt(e)>Qe.documentBytes)&&n("Funnel document exceeds its budget","budget")}var af=E.strictObject({...hc,graph:sc}).superRefine(rf),ar=E.strictObject({...hc,graph:sc,displayName:E.string().trim().min(1).max(80)}).superRefine(rf),Ka=E.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),kr={requestId:E.uuid(),nodeId:Gt,visit:E.number().int().nonnegative(),revision:E.number().int().nonnegative(),customerToken:Ka.optional()},h0=E.discriminatedUnion("type",[E.strictObject({type:E.literal("screen"),output:Gt,answers:$n,selection:E.record(Gt,E.union([E.string().max(200),E.boolean()])).optional()}),E.strictObject({type:E.literal("paywall_quote"),actionId:Gt,productVersionId:E.uuid(),offerId:E.uuid().optional(),nativeOffer:Cn.optional(),predecessor:E.strictObject({operationId:E.uuid().nullable(),generation:E.number().int().positive()}).optional()}),E.strictObject({type:E.literal("paywall_confirm"),operationId:E.uuid()}),E.strictObject({type:E.literal("paywall_cancel"),operationId:E.uuid()}),E.strictObject({type:E.literal("client_action"),receiptId:E.uuid(),outcome:E.enum(["success","cancel","failure","opened","failed"])})]),g0=E.object({nodeId:Gt,visit:E.number().int().nonnegative(),revision:E.number().int().nonnegative(),components:E.record(Gt,E.object({resourceKey:E.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:E.number().int().min(1).max(1e5),after:Ji.nullable(),filter:E.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Di=E.discriminatedUnion("operation",[E.strictObject({operation:E.literal("start"),funnelId:E.uuid(),requestId:E.uuid(),customer:xr.optional(),customerData:Ir.optional(),locale:E.string().min(1).max(35),parameters:qt}).refine(er,tr),E.strictObject({operation:E.literal("get"),settlementRequestId:E.uuid().optional(),data:g0.optional(),purchase:E.strictObject({receiptId:E.uuid(),operationId:E.uuid()}).optional(),customerToken:Ka.optional()}),E.strictObject({operation:E.literal("resume"),requestId:E.uuid(),customerToken:Ka.optional()}),E.strictObject({operation:E.literal("submit"),...kr,input:h0}),E.strictObject({operation:E.literal("back"),...kr}),E.strictObject({operation:E.literal("shown"),...kr}),E.strictObject({operation:E.literal("close"),...kr}),E.strictObject({operation:E.literal("commit_segment"),...kr,policyRevision:E.number().int().nonnegative(),generation:E.string().min(1).max(256),steps:E.array(Va).max(32),boundary:E.strictObject({nodeId:E.string().min(1).max(64),visit:E.number().int().nonnegative()}).optional()}),E.strictObject({operation:E.literal("evaluate"),...kr,receiptId:E.uuid(),policyRevision:E.number().int().nonnegative(),generation:E.string().min(1).max(256),result:Ri}),E.strictObject({operation:E.literal("review"),receiptId:E.uuid().optional(),customerToken:Ka.optional()})]);function fc(e,t){if(!e||e.hidden)return null;if(e.id===t)return e;if(e.type!=="stack")return null;for(let n of e.children){let r=fc(n,t);if(r)return r}return null}function b0(e,t,n,r,i){let a=e.graph.nodes.find(u=>u.id===t);if(a?.type!=="screen")throw new Error("Input is only accepted on a screen");let o=e.screens.find(u=>u.id===a.screenId),s=e.inputs.filter(u=>u.screenId===a.screenId),c={...r};for(let[u,l]of Object.entries(n)){let d=s.find(h=>h.variable===u);if(!d||o?.type!=="owned")throw new Error("Unknown screen input");let p=fc(o.document.pages[0]?.root,d.componentId);if(p?.type!=="stack"||!p.interaction)throw new Error("Input is unavailable");let g=p.interaction;switch(g.type){case"input":if(typeof l!="string"||l.length>g.maxLength)throw new Error("Invalid input text");if(l&&g.keyboard==="email"&&!E.email().safeParse(l).success)throw new Error("Invalid email");if(l&&g.keyboard==="url"&&!E.url().safeParse(l).success)throw new Error("Invalid URL");break;case"toggle":if(typeof l!="boolean")throw new Error("Invalid toggle value");break;case"select":case"tabs":if(typeof l!="string"||!p.children.some(h=>h.id===l&&!h.hidden))throw new Error("Invalid selected option");break;case"multiselect":if(!Array.isArray(l)||new Set(l).size!==l.length||l.length>g.max||i&&l.length<g.min||l.some(h=>!p.children.some(y=>y.id===h&&!y.hidden)))throw new Error("Invalid selected options");break;default:throw new Error("Component cannot accept input")}let m=e.variables[u];if(m?.source.type!=="input"||!Xt(m,l))throw new Error("Invalid input variable");c[u]=l}if(i)for(let u of s){let l=c[u.variable];if(u.required&&(l===void 0||l===""||Array.isArray(l)&&l.length===0))throw new Error(`Required input: ${u.variable}`);l!==void 0&&!Object.hasOwn(n,u.variable)&&b0(e,t,{[u.variable]:l},{},!1);let d=o?.type==="owned"?fc(o.document.pages[0]?.root,u.componentId):null;if(d?.type==="stack"&&d.interaction?.type==="multiselect"&&Array.isArray(l)&&l.length<d.interaction.min)throw new Error("Not enough selected options")}return c}import{z as _e}from"zod";var _0=_e.strictObject({id:_e.uuid(),projectId:_e.uuid(),environmentId:_e.uuid(),name:_e.string().min(1).max(80),revision:_e.number().int().nonnegative(),evaluationMode:ec,evaluationRevision:_e.number().int().nonnegative(),state:_e.enum(["active","paused","archived"]),publishedVersionId:_e.uuid().nullable(),updatedAt:_e.iso.datetime({offset:!0}),draft:Dt}),zD=_e.strictObject({rows:_e.array(_0).max(200),nextCursor:_e.uuid().nullable()}),eN=_e.discriminatedUnion("action",[_e.strictObject({action:_e.literal("setEvaluationMode"),id:_e.uuid(),revision:_e.number().int().nonnegative(),evaluationMode:ec}),_e.strictObject({action:_e.literal("create"),requestId:_e.uuid(),name:_e.string().trim().min(1).max(80),document:Dt}),_e.strictObject({action:_e.literal("save"),id:_e.uuid(),revision:_e.number().int().nonnegative(),name:_e.string().trim().min(1).max(80),document:Dt}),_e.strictObject({action:_e.literal("terminateRun"),id:_e.uuid(),revision:_e.number().int().nonnegative(),runId:_e.uuid()}),_e.strictObject({action:_e.enum(["publish","archive","pause","activate","stop"]),id:_e.uuid(),revision:_e.number().int().nonnegative()})]).superRefine((e,t)=>{(e.action==="create"||e.action==="save")&&wt(e.document)>Qe.documentBytes&&t.addIssue({code:"custom",path:["document"],message:"Funnel document exceeds its byte budget"})});function tN(e){let t=e==="en",n=Nm("popup",e);n.name=t?"Welcome":"\u6B22\u8FCE";let r=n.pages[0];if(!r)throw new Error("Blank screen requires a page");return r.root.children=[{id:"heading",type:"text",text:"heading",variant:"title",style:{text:{align:"center"}}},{id:"body",type:"text",text:"body",variant:"body",style:{text:{align:"center"}}},{id:"continue_button",type:"button",label:"continue",variant:"primary",action:"continue",style:{width:"fill",margin:{top:8,right:0,bottom:0,left:0}}}],n.actions=[{id:"continue",type:"event",event:"continue",properties:{},close:!1}],n.strings.locales[e]={heading:t?"Welcome":"\u6B22\u8FCE",body:t?"Tell people what this step is for and what happens next.":"\u544A\u8BC9\u7528\u6237\u8FD9\u4E00\u6B65\u7684\u4F5C\u7528\uFF0C\u4EE5\u53CA\u63A5\u4E0B\u6765\u4F1A\u53D1\u751F\u4EC0\u4E48\u3002",continue:t?"Continue":"\u7EE7\u7EED"},af.parse({schemaVersion:4,references:{},variables:{},outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",inputs:[],screens:[{id:"welcome",type:"owned",document:n}],graph:{version:5,entry:"entry",nodes:[{id:"entry",name:t?"Entry":"\u5165\u53E3",type:"entry",next:"welcome"},{id:"welcome",name:t?"Welcome":"\u6B22\u8FCE",type:"screen",screenId:"welcome",presentation:{type:"modal",size:"md"},outputs:{continue:"done"}},{id:"done",name:t?"Completed":"\u5B8C\u6210",type:"end",outcome:"completed",output:{type:"literal",value:null}}]}})}import{z as N}from"zod";var Tn=N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gc=N.enum(["running","waiting","completed","closed","ineligible","failed"]),y0=N.discriminatedUnion("type",[qa,tc,N.strictObject({type:N.literal("wait"),receiptId:N.uuid(),kind:N.enum(["timer","event","operation"]),deadline:N.iso.datetime({offset:!0}).nullable(),eventName:Tn.optional()}),N.strictObject({type:N.literal("open_url"),receiptId:N.uuid(),url:ic,openIn:ac}),N.strictObject({type:N.literal("event"),receiptId:N.uuid(),event:Tn})]),S0=N.strictObject({type:N.literal("funnel"),id:N.uuid(),versionId:N.uuid()}),v0={id:Tn,presentation:gn,outputs:N.array(Tn).max(250),inputs:Eo,values:N.record(N.string(),Ie).optional(),offeringKey:Ze.optional(),capabilities:lr,customerData:Au,dataCursors:N.record(Tn,Ji.nullable())},x0=N.strictObject({...v0,content:N.strictObject({type:N.literal("document"),document:It})}),bc=N.strictObject({id:N.uuid(),source:S0,revision:N.number().int().nonnegative(),visit:N.number().int().nonnegative(),nodeId:Tn,nodeType:N.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:gc,stopped:N.boolean(),canBack:N.boolean(),recoveryRestricted:N.boolean().optional(),authenticated:N.boolean(),locale:N.string().min(1).max(35),answers:$n,parameters:qt,variables:N.record(N.string(),Ie),output:Ie.nullable(),screen:x0.nullable(),paywall:N.strictObject({receiptId:N.uuid(),resolution:Ea,quote:hi.nullable(),operation:br.nullable(),purchaseRequestId:N.uuid().nullable(),selectionGeneration:N.number().int().nonnegative().optional(),canReselect:N.boolean().optional()}).nullable(),instruction:y0.nullable(),pendingRequest:N.strictObject({requestId:N.uuid(),authenticationRequired:N.boolean()}).nullable(),runExpiresAt:N.iso.datetime({offset:!0}),credentialExpiresAt:N.iso.datetime({offset:!0}).nullable()}),of=N.strictObject({scope:je,run:bc,settlement:N.strictObject({requestId:N.uuid(),state:N.enum(["pending","unknown","settled"]),operationId:N.uuid().nullable(),receiptId:N.uuid().nullable().optional()}).optional(),purchase:N.strictObject({receiptId:N.uuid(),quote:hi.nullable(),operation:br.nullable(),canReselect:N.boolean().optional()}).optional(),review:N.strictObject({activeOperationId:N.uuid().nullable(),pages:N.array(N.strictObject({receiptId:N.uuid(),nodeId:Tn,visit:N.number().int().nonnegative()})).max(100),page:N.strictObject({receiptId:N.uuid(),nodeId:Tn,visit:N.number().int().nonnegative(),document:It,answers:$n,inputs:Eo,values:N.record(N.string(),Ie).optional()}).nullable(),coupons:N.array(N.strictObject({grantId:N.uuid(),status:N.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:N.string().nullable()})).max(100),purchases:N.array(N.strictObject({receiptId:N.uuid(),operationId:N.uuid(),status:N.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:N.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:N.uuid().optional()}),gN="X-Indiana-Server-Key";import{z as Pt}from"zod";import{z as Ha}from"zod";var SN=Ha.strictObject({operation:Ha.literal("renew_run"),runId:Ha.uuid(),customerId:Ha.uuid()}),sf=of.refine(e=>!!e.runToken,"Renewal returns a credential");var ON=Pt.discriminatedUnion("operation",[Pt.strictObject({operation:Pt.literal("campaign_decide"),...nc}).refine(er,tr),Pt.strictObject({operation:Pt.literal("campaign_start"),funnelId:Pt.uuid(),requestId:Pt.uuid(),customer:xr,customerData:Ir.optional(),locale:Pt.string().min(1).max(35),parameters:qt,cooldownSeconds:Pt.number().int().min(1).max(2592e3)}).refine(er,tr)]),EN=Pt.union([Pt.strictObject({scope:je,suppressed:Pt.literal(!0),reason:Pt.enum(["frequency","in_progress"]),retryAt:Pt.iso.datetime({offset:!0})}),sf]);import{z as ye}from"zod";function Qa(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(m){for(let h of cr(m))l(h)}function l(m){if(i.has(m)||!Object.hasOwn(t.savedGroups,m))return;let h=t.savedGroups[m];h&&(i.add(m),c.set(m,h),a.push(()=>{!Array.isArray(h)&&h.type==="condition"&&u(h.condition)}))}function d(m){u(m.condition);for(let h of m.parentConditions??[])p(h.id),u(h.condition)}function p(m,h=!1){let y=Object.hasOwn(t.features,m)?t.features[m]:void 0;if(!y){if(h)throw new Error("Required GB Feature is unavailable");return}n.has(m)||(n.add(m),o.set(m,y),a.push(()=>{for(let w of y.rules??[]){d(w);for(let x of w.tracks??[])d(x.experiment)}}))}function g(m){let h=Object.hasOwn(t.experiments,m)?t.experiments[m]:void 0;if(!h)throw new Error("Required GB Experiment is unavailable");r.has(m)||(r.add(m),s.set(m,h),a.push(()=>d(h)))}for(let m of e.graph.nodes){m.type==="feature"&&p(m.featureKey,!0),m.type==="split"&&g(m.experimentId),m.type==="condition"&&m.cases.forEach(y=>u(y.condition)),m.type==="offering"&&m.configuration.source==="feature"&&p(m.configuration.featureKey,!0);let h=m.type==="output"?m.value:m.type==="end"?m.output:null;h?.type==="feature"&&p(h.featureKey,!0)}for(let m of a)m();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var Dr=ye.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),uf=ye.strictObject({entry:Dr,nodes:ye.array(ye.strictObject({id:Dr,type:ye.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:ye.record(ye.string(),Dr),writes:ye.record(Ze,Ze),resources:ye.strictObject({screenId:Dr.optional(),paywallVersionId:ye.uuid().optional(),couponId:ye.uuid().optional(),couponIds:ye.array(ye.uuid()).max(20).optional(),experimentId:ye.uuid().optional(),featureKey:ye.string().optional(),offeringVersionId:ye.uuid().optional()})})).min(1).max(500)}),cf={scope:je,funnelId:ye.uuid(),versionId:ye.uuid(),evaluationRevision:ye.number().int().nonnegative(),expiresAt:ye.iso.datetime({offset:!0}).nullable(),topology:uf},Za=ye.discriminatedUnion("evaluationMode",[ye.strictObject({...cf,evaluationMode:ye.literal("local"),growth:nn,conditions:ye.record(Dr,ye.array(ye.strictObject({condition:xn,port:ye.string()})))}),ye.strictObject({...cf,evaluationMode:ye.literal("remote")})]),I0=Za.options[0].extend({evaluation:ye.strictObject({maxTransitions:ye.number().int().min(1).max(1e4),variables:ye.record(Ze,Cr),outputSchema:Pr,terminals:ye.record(Dr,ye.strictObject({outcome:ye.enum(["completed","closed","ineligible","failed"]),output:ji.nullable()}))})});function A0(e){return uf.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=ye.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function w0(e){let t=ar.parse(e.document),n=e.evaluationMode==="local"?nn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:A0(t)};return Za.parse(e.evaluationMode==="remote"?r:{...r,growth:Qa(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function qN(e){let t=w0(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=ar.parse(e.document);return I0.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as B}from"zod";var df={commands:Qe.flowNodes*4,receipts:Qe.flowNodes*2,requestBytes:Qe.documentBytes+2e6},Nr=B.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),lf={requestId:B.uuid(),nodeId:Nr,visit:B.number().int().nonnegative(),revision:B.number().int().nonnegative()},P0=B.union([Di.options[3].omit({customerToken:!0}),Di.options[4].omit({customerToken:!0}),Di.options[5].omit({customerToken:!0}),Di.options[6].omit({customerToken:!0}),B.strictObject({operation:B.literal("wait"),...lf,result:B.enum(["elapsed","received","timeout"])}),B.strictObject({operation:B.literal("simulate"),...lf,outcome:B.enum(["success","cancel","failure","unavailable"])})]),_c=B.enum(["success","cancel","failure","unavailable","pending"]),yc=B.strictObject({seed:B.uuid(),now:B.iso.datetime({offset:!0}),locale:B.string().min(2).max(35),currency:ae,parameters:qt,attributes:B.record(B.string(),Oi).refine(e=>Object.keys(e).length<=100),authenticated:B.boolean(),holdings:B.enum(["sample","empty"]),results:B.record(B.string(),Ie).optional(),outcomes:B.record(Nr,_c),variants:B.record(Nr,B.string().min(1).max(128).nullable())}),Sc=B.strictObject({schemaVersion:B.literal(1),growth:nn,paywalls:B.record(B.uuid(),Oa),offerings:B.record(B.uuid(),_r),surfaces:B.record(Nr,Ie)}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=1e6,"Preview dependencies exceed their byte budget"),C0=B.array(B.strictObject({command:P0,authenticated:B.boolean(),outcome:_c})).max(df.commands),O0=B.discriminatedUnion("type",[B.strictObject({type:B.literal("draft"),document:Dt}),B.strictObject({type:B.literal("snapshot"),id:B.uuid()})]),eF=B.strictObject({previewId:B.uuid(),source:O0,scenario:yc,journal:C0,dependencySnapshot:Sc.optional()}),tF=B.strictObject({mode:B.literal("simulation"),run:bc,dependencySnapshot:Sc,traceTruncated:B.boolean(),trace:B.array(B.strictObject({nodeId:Nr,visit:B.number().int().nonnegative(),type:B.enum(["entered","shown","assigned","feature_evaluated","action","closed","wait_elapsed","wait_timeout","wait_received"]),details:B.record(B.string(),B.union([B.string(),B.number(),B.boolean(),B.null()]))})).max(2e3),receipts:B.array(B.strictObject({id:B.uuid(),nodeId:Nr,visit:B.number().int().nonnegative(),outcome:_c})).max(df.receipts)}),nF=B.strictObject({id:B.uuid(),projectId:B.uuid(),environmentId:B.uuid(),document:Dt,scenario:yc,dependencySnapshot:Sc,expiresAt:B.iso.datetime({offset:!0})}),rF=B.discriminatedUnion("action",[B.strictObject({action:B.literal("create"),requestId:B.uuid(),document:Dt,scenario:yc}),B.strictObject({action:B.literal("revoke"),id:B.uuid()})]);import{z as ve}from"zod";var oF=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 vc={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 uF(e,t,n=[],r={}){let i=Qi(t)??"en",[a="en",...o]=i.split("-"),s=a==="zh"&&!o.includes("Hans")&&o.some(h=>["Hant","TW","HK","MO"].includes(h))?"zh-Hant":a,c=vc[s]??vc.en,u=vc[s]?i:"en",l=h=>new Intl.NumberFormat(u).format(h),d=h=>new Intl.DateTimeFormat(u,{dateStyle:"medium",timeStyle:"short",timeZone:"UTC"}).format(new Date(h))+" UTC",p=[e.appliesTo.type==="all"?c[0]:`${c[1]}${n.length?`: ${n.slice(0,3).join(", ")+(n.length>3?` (+${l(n.length-3)})`:"")}`:""}`,e.eligibility.firstPurchaseOnly?c[3]:c[2],Object.keys(e.eligibility.condition).length||r.qualificationRequired?`${c[4]}${r.includeQualificationTags!==!1&&pf(e.eligibility.condition)?`: ${pf(e.eligibility.condition)}`:""}`:null].filter(Boolean).join(" \xB7 "),g=[e.startsAt?`${c[5]}: ${d(e.startsAt)}`:null,e.endsAt?`${c[6]}: ${d(e.endsAt)}`:c[7]].filter(Boolean).join(" \xB7 "),m=[p,g,`${c[8]}: ${l(e.grantWindowHours)} ${c[9]}`,`${c[10]}: ${l(e.perCustomerLimit)}`,e.totalLimit===null?null:`${c[11]}: ${l(e.totalLimit)}`].filter(Boolean).join(" \xB7 ");return{eligibility:p,validity:g,terms:m}}function pf(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 xc={"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 mF(e,t){let n=mf(e);if(!n||!Object.hasOwn(xc,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 fF(e){let t=mf(e),n=t?xc[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}from"zod";var Wt=z.string().min(1).max(255),Rn=z.number().finite().nonnegative(),ff=z.strictObject({properties:z.record(z.string().min(1).max(64),z.union([z.string().min(1).max(128),z.number().finite(),z.boolean()]).transform(String).pipe(z.string())).refine(e=>Object.keys(e).length>=1&&Object.keys(e).length<=4)}),E0=z.strictObject({feature_id:Wt,enabled:z.boolean().default(!1),threshold:z.number().finite(),quantity:z.number().finite().min(1),purchase_limit:z.strictObject({interval:z.enum(["hour","day","week","month"]),interval_count:z.number().finite().min(1).default(1),limit:z.number().finite().min(1)}).optional(),invoice_mode:z.boolean().optional()}),T0=z.strictObject({feature_id:Wt.optional(),enabled:z.boolean().default(!1),limit_type:z.enum(["absolute","usage_percentage"]).optional(),overage_limit:Rn.optional(),skip_overage_billing:z.boolean().optional()}).refine(e=>e.overage_limit===void 0&&e.skip_overage_billing===void 0||e.feature_id!==void 0,"A feature is required for overage limits and billing controls"),R0=z.strictObject({feature_id:Wt,enabled:z.boolean().default(!0),limit:Rn,interval:z.enum(["day","week","month","year"]),anchor:z.enum(["billing_cycle","utc"]).optional(),filter:ff.optional()}),j0=z.strictObject({feature_id:Wt.optional(),enabled:z.boolean().default(!0),threshold:Rn,threshold_type:z.enum(["usage","usage_percentage","remaining","remaining_percentage"]),basis:z.enum(["balance","included","recurring","usage_limit"]).default("balance"),filter:ff.optional(),name:z.string().optional()}).refine(e=>e.threshold_type!=="remaining_percentage"||e.threshold<=100,"Remaining percentage cannot exceed 100").refine(e=>e.basis!=="usage_limit"||e.feature_id!==void 0,"Usage-limit alerts require a feature").refine(e=>e.filter===void 0||e.basis==="usage_limit","Filters apply only to usage-limit alerts"),k0=z.strictObject({feature_id:Wt,enabled:z.boolean().default(!1)}),D0=z.strictObject({auto_topups:z.array(E0).nullable(),spend_limits:z.array(T0).nullable(),usage_limits:z.array(R0).nullable(),usage_alerts:z.array(j0).nullable(),overage_allowed:z.array(k0).nullable()}),_F=D0.omit({auto_topups:!0}),N0=vr,yF=z.strictObject({internal_id:z.uuid(),id:Wt.nullable(),project_id:z.uuid(),environment_id:z.uuid(),name:z.string().max(80).nullable(),email:z.string().max(254).nullable(),metadata:N0.nullable(),created_at:z.number().finite().nonnegative().max(864e13)}),SF=z.strictObject({id:Wt,internal_product_id:Wt,product_id:Wt.nullable(),status:z.enum(["scheduled","pending","active","past_due","expired","unknown","trialing","paused"]),canceled_at:Rn.nullable(),free_trial_id:Wt.nullable(),trial_ends_at:Rn.nullable(),starts_at:Rn.nullable(),access_starts_at:Rn.nullable(),ended_at:Rn.nullable(),product:z.strictObject({internal_id:Wt,id:Wt,name:z.string(),version:z.number().int().positive(),is_add_on:z.boolean()})});function AF(e,t,n=[]){let r={nodes:{}},i=t.startsWith("zh"),a=(s,c)=>i?s:c,o=(s,c,u,l,d=[])=>({id:s,label:c,value:u,status:l,detail:d,facts:[]});return Lt(e,s=>{if(s.type!=="customer_data")return;let c={...wu(s.data.source),status:"ready",stale:!1,preview:!0};if(s.data.source==="credit_balance"){let u=s.data.resourceKey??n[0]?.key??"credits";c.resources=[{key:u,name:n.find(l=>l.key===u)?.label??a("\u521B\u4F5C\u79EF\u5206","Creative credits"),spendable:"3,840",available:"4,040",reserved:"200",expiry:a("1,200 \xB7 2026\u5E7411\u67081\u65E5","1,200 \xB7 November 1, 2026"),sources:[o("sample-monthly",a("\u4F1A\u5458\u6708\u5EA6\u79EF\u5206","Monthly membership credits"),"2,640",a("\u53EF\u7528","Available")),o("sample-pack",a("\u8D2D\u4E70\u79EF\u5206\u5305","Purchased credit pack"),"1,200",a("\u53EF\u7528","Available"))],sourceCount:2,sourcePage:1,hasNextSources:!1,hasPreviousSources:!1}]}else s.data.source==="credit_transactions"?(c.rows=[o("sample-usage-1",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67083\u65E5 09:42","Oct 3, 09:42")]),o("sample-usage-2",a("\u89C6\u9891\u751F\u6210","Video generation"),"",a("\u9884\u6263","Reserved"),[a("10\u67083\u65E5 09:30","Oct 3, 09:30")]),o("sample-usage-3",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u9000\u56DE","Refund"),[a("10\u67082\u65E5 16:10","Oct 2, 16:10")]),o("sample-usage-4",a("\u89C6\u9891\u751F\u6210","Video generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67082\u65E5 15:24","Oct 2, 15:24")]),o("sample-usage-5",a("\u56FE\u50CF\u751F\u6210","Image generation"),"",a("\u6D88\u8D39","Usage"),[a("10\u67082\u65E5 14:08","Oct 2, 14:08")])].slice(0,s.data.pageSize),c.rows.forEach((u,l)=>{u.facts=[{label:a("\u521B\u4F5C\u79EF\u5206","Creative credits"),value:l%2===1?"180":l===4?"24":"12"}]})):s.data.source==="membership"?c.rows=[o("sample-plan",a("\u4E13\u4E1A\u7248 \xB7 \u6708\u4ED8","Pro \xB7 Monthly"),"",a("\u6709\u6548","Active"),[a("\u5F53\u524D\u5468\u671F\u7ED3\u675F \xB7 2026\u5E7411\u67081\u65E5","Current period ends \xB7 November 1, 2026")])]:s.data.source==="customer_plans"?c.rows=[o("sample-free",a("\u57FA\u7840\u7248","Starter"),a("\u514D\u8D39","Free"),a("\u53EF\u9009\u62E9","Available")),o("sample-pro",a("\u4E13\u4E1A\u7248","Pro"),a("$29 / \u6708","$29 / month"),a("\u5F53\u524D\u5957\u9910","Current plan")),o("sample-team",a("\u56E2\u961F\u7248","Team"),a("$79 / \u6708","$79 / month"),a("\u53EF\u9009\u62E9","Available"))].slice(0,s.data.pageSize):s.data.source==="billing_controls"?c.rows=[o("sample-control",a("\u6708\u5EA6\u7528\u91CF\u4E0A\u9650","Monthly usage limit"),"240 / 1,000",a("\u793A\u4F8B \xB7 \u672A\u6388\u6743\u4ED8\u6B3E","Sample \xB7 Payments not authorized"),[a("\u4EC5\u5C55\u793A\u793A\u4F8B\uFF0C\u9884\u89C8\u4E0D\u4F1A\u542F\u7528\u81EA\u52A8\u5145\u503C\u6216\u540E\u4ED8\u8D39\u3002","Preview does not authorize auto top-ups or postpaid billing.")])]:s.data.source==="billing"?c.rows=[{...o("sample-invoice","GROW-2026-001","$29.00",a("\u5DF2\u652F\u4ED8","Paid"),["October 1, 2026"]),billingActions:[{action:"invoice_open",label:a("\u67E5\u770B\u53D1\u7968","View invoice")}]}]:s.data.source==="credit_packs"?c.rows=[o("sample-pack-small",a("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12","",[a("1,200 \u79EF\u5206 \xB7 90 \u5929\u6709\u6548","1,200 credits \xB7 90 days validity")]),o("sample-pack-large",a("\u521B\u4F5C\u6269\u5C55\u5305","Creative expansion"),"$40","",[a("5,000 \u79EF\u5206 \xB7 180 \u5929\u6709\u6548","5,000 credits \xB7 180 days validity")])].slice(0,s.data.pageSize).map((u,l)=>({...u,...s.data.allowPurchase?{purchaseId:`10000000-0000-4000-8000-${String(l+1).padStart(12,"0")}`}:{}})):s.data.source==="credit_pack_orders"?c.rows=[o("sample-order",a("\u521B\u4F5C\u8865\u5145\u5305","Creative top-up"),"$12",a("\u5DF2\u4ED8\u6B3E","Paid"),["2026-10-01 12:30"])]:c.rows=[o("sample-offer",a("\u4F1A\u5458\u7EED\u8D39\u4F18\u60E0","Membership renewal offer"),"",a("\u53EF\u7528","Available"),[a("2026\u5E7411\u67081\u65E5\u5230\u671F","Expires November 1, 2026")])];r.nodes[s.id]=c}),r}import{z as Ee}from"zod";import{z as le}from"zod";var F0=le.enum(["customer","coupon","audience"]),U0=le.enum(["name","description","email","metadata","tags","config","status","terms","codes","content"]),Ya=le.object({baseRevision:le.number().int().nonnegative(),latestRevision:le.number().int().nonnegative(),mode:le.enum(["merge","use_latest"]),decisions:le.array(le.object({field:U0,mine:le.number().int().min(0).max(1e3),latest:le.number().int().min(0).max(1e3)}).strict().refine(e=>e.mine+e.latest>0)).max(28)}).strict().refine(e=>e.latestRevision>e.baseRevision).refine(e=>new Set(e.decisions.map(t=>t.field)).size===e.decisions.length).refine(e=>e.mode!=="use_latest"||e.decisions.length===0),hf=le.number().int().nonnegative().nullable(),M0=le.object({resource:F0,id:le.uuid(),projectId:le.uuid(),environmentId:le.uuid(),fromRevision:hf,toRevision:hf,provenance:le.enum(["recorded","historical"]),changes:le.array(le.object({field:le.string(),redacted:le.boolean(),before:le.union([le.string(),le.number(),le.boolean(),le.null()]),after:le.union([le.string(),le.number(),le.boolean(),le.null()])})),merge:Ya.safeExtend({source:le.literal("client")}).nullable()}),B0=le.object({createdAt:le.iso.datetime({offset:!0}),id:le.uuid()}).strict(),CF=le.object({events:le.array(le.object({id:le.uuid(),action:le.string(),actorId:le.uuid().nullable(),actorEmail:le.email().nullable(),createdAt:le.iso.datetime({offset:!0}),object:M0})),nextCursor:B0.nullable()});var jF={type:"condition",condition:{}},kF=Ee.strictObject({id:Ee.uuid(),name:Ee.string().min(1).max(80),description:Ee.string().max(500),config:Po,revision:Ee.number().int().min(1),status:Ee.enum(["active","archived"]),batchable:Ee.boolean(),created_at:Ee.iso.datetime({offset:!0}),updated_at:Ee.iso.datetime({offset:!0})}),DF=Ee.discriminatedUnion("action",[Ee.strictObject({action:Ee.literal("save"),id:Ee.uuid().nullable(),audit:Ya.nullable().optional(),revision:Ee.number().int().min(0),name:Ee.string().trim().min(1).max(80),description:Ee.string().max(500),config:Po}),Ee.strictObject({action:Ee.literal("archive"),id:Ee.uuid(),audit:Ya.nullable().optional(),revision:Ee.number().int().min(1)})]),L0=Ee.object({id:Ee.uuid(),name:Ee.string().nullable(),external_user_id:Ee.string(),attributes:Bt,created_at:Ee.iso.datetime({offset:!0})}),NF=Ee.object({customers:L0.array(),hasMore:Ee.boolean(),offset:Ee.number().int().min(0),limit:Ee.number().int().min(1),evaluatedAt:Ee.iso.datetime({offset:!0}),revision:Ee.number().int().min(1)});import{z as Ni}from"zod";var BF=Ni.object({defaultLocale:mn,locales:Ni.record(mn,Ni.object({name:Ni.string().max(80),description:Ni.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 LF(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=su([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",Ja="#667085",q0="#E2E6EE",V0="#2C3C96",St=e=>({top:e,right:e,bottom:e,left:e}),ut=e=>({type:"color",color:e}),Nt=class{constructor(t,n={}){this.name=t;this.design=n}name;design;zh={};en={};text(t,n,r,i=13,a=Ja,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=q0){return{id:t,type:"divider",style:{background:ut(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":Ja,{text:{size:11,color:o?"#A9B4CB":Ja,letterSpacing:1.4,weight:600}}),this.text("heading",t,n,28,o?"#FFFFFF":gf),this.text("description",r,i,14,o?"#A9B4CB":Ja)],{gap:12,width:660,grow:!0}),...a?[a]:[]],{gap:32},!0)}document(t,n=!1){return It.parse({kind:"screen",schemaVersion:4,name:this.name,surface:"page",presentation:{type:"fullscreen"},theme:{primary:V0,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 za="#19202E",$0="#667080",Ic="#2C3C96",bf="#DDE2E9",_f="#F0F3FA",G0=(e=72,t=za)=>({text:{size:e,color:t,weight:600,font:"system"}}),Xa=(e,t=1)=>({width:e,grow:t}),W0={background:ut("#FFFFFF"),shape:{type:"rect",radius:10}};function K0(e){return new Nt(e,{theme:{background:"#FFFFFF",text:za,primary:Ic},width:1184,gap:32,padding:{top:24,right:24,bottom:40,left:24}})}function H0(e,t,n,r,i){let a=e.text("wordmark","GROW / \u8D26\u6237","GROW / ACCOUNT",13,Ic,{text:{size:13,color:Ic,weight:700,letterSpacing:.8}});return e.stack("page_header",[a,e.text("heading",t,n,40,za,{text:{size:40,color:za,weight:700,lineHeight:1.18,letterSpacing:-1.4}}),e.text("description",r,i,14,$0)],{gap:12,padding:{top:8,right:0,bottom:8,left:0}})}function yf(){let e="#FAF7F0",t="#302923",n="#A63C25",r="#73665A",i=new Nt("\u8D26\u6237\u4E00\u89C8",{theme:{background:e,text:t,primary:n,radius:"none"},width:1120,gap:36,padding:{top:32,right:24,bottom:48,left:24}}),a=(o,s,c)=>i.text(o,s,c,12,n,{text:{size:12,color:n,font:"mono",weight:500,letterSpacing:1.1}});return i.document([i.stack("journal_masthead",[i.stack("journal_identity",[i.text("wordmark","GROW","GROW",22,t,{text:{size:22,color:t,weight:700,letterSpacing:-1}}),a("edition","\u8D26\u6237 / ACCOUNT","ACCOUNT / JOURNAL")],{gap:16},!0),i.rule("masthead_rule",t),i.stack("journal_intro",[i.text("heading","\u8D26\u6237\u4E00\u89C8","Your account.",64,t,{width:720,grow:2,text:{size:64,color:t,font:"serif",weight:400,lineHeight:1.12,letterSpacing:-2}}),i.stack("intro_note",[a("intro_index","\u4E3A\u4F60\u7684\u4E0B\u4E00\u6B21\u521B\u4F5C","FOR YOUR NEXT CHAPTER"),i.text("description",`\u4F60\u7684\u4F1A\u5458\u3001\u79EF\u5206\u4E0E\u8D2D\u4E70\u8BB0\u5F55\uFF0C
|
|
2
|
-
\u5728\u4E00\u5904\u4ECE\u5BB9\u638C\u63E1\u3002`,`Membership, credits and purchases.
|
|
3
|
-
A little clarity for what's next.`,14,r)],{width:300,grow:1,gap:12,padding:{top:8,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("account_summary",[i.stack("member_column",[a("member_index","01 / \u4F1A\u5458","01 / MEMBERSHIP"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:t,font:"serif",size:40,weight:400}})],{width:660,grow:2,gap:16}),i.stack("balance_column",[a("balance_index","02 / \u79EF\u5206","02 / CREDITS"),i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!0,{text:{color:t,font:"serif",size:64,weight:400}})],{width:340,grow:1,gap:16})],{gap:48,padding:{top:12,right:0,bottom:12,left:0}},!0),i.rule("records_rule","#D9CFC1"),i.stack("account_records",[i.stack("purchase_column",[a("purchase_index","03 / \u8D2D\u4E70\u8BB0\u5F55","03 / PURCHASES"),i.widget("orders","credit_pack_orders","\u6BCF\u4E00\u7B14\u8D2D\u4E70","Your purchases",!1,{text:{color:t}})],{width:660,grow:2,gap:16}),i.stack("offer_column",[a("offer_index","04 / \u4E13\u5C5E\u4F18\u60E0","04 / YOUR OFFERS"),i.widget("offers","offer_history","\u53EF\u7528\u4F18\u60E0","Available offers",!0,{text:{color:t}})],{width:340,grow:1,gap:16})],{gap:48},!0),i.rule("catalog_rule","#D9CFC1"),i.stack("account_catalog",[a("catalog_index","05 / \u65B9\u6848","05 / PLANS"),i.widget("plans","customer_plans","\u63A2\u7D22\u9002\u5408\u4F60\u7684\u65B9\u6848","Find your next plan",!0,{text:{color:t}})],{gap:16}),i.text("journal_footer","GROW / \u8BA9\u521B\u4F5C\u7EE7\u7EED","GROW / KEEP CREATING",11,r,{text:{size:11,color:r,font:"mono",letterSpacing:1}})])}function Sf(){let e="#182C4A",t="#596B83",n="#CCD6E4",r=new Nt("\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:St(28),background:ut("#E0E8F4")}),r.stack("ledger_panel",[i("activity_index","02 / \u8D26\u76EE\u660E\u7EC6","02 / ACTIVITY"),r.widget("activity","credit_transactions","\u79EF\u5206\u6D41\u6C34","Credit history",!1,{text:{color:e}})],{gap:16,padding:St(28),background:ut("#FFFFFF")})],{width:820,grow:2,gap:2}),r.stack("purchase_rail",[r.stack("plan_context",[i("membership_index","\u8D26\u6237 / \u65B9\u6848","ACCOUNT / PLAN"),r.widget("membership","membership","\u5F53\u524D\u65B9\u6848","Current plan",!0,{text:{color:e}})],{gap:16,padding:St(24),background:ut("#FFFFFF")}),r.stack("purchase_panel",[i("purchase_index","03 / \u8865\u5145\u79EF\u5206","03 / TOP UP"),r.widget("packs","credit_packs","\u8D2D\u4E70\u79EF\u5206","Buy credits",!0,{text:{color:e}}),r.text("purchase_note","\u8D2D\u4E70\u524D\u67E5\u770B\u79EF\u5206\u6570\u91CF\u4E0E\u6709\u6548\u671F\u3002","Check the credit amount and validity before purchase.",12,t)],{gap:16,padding:St(24),background:ut("#FFFFFF")}),r.stack("orders_panel",[i("orders_index","04 / \u8D2D\u4E70\u8BB0\u5F55","04 / PURCHASES"),r.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0,{text:{color:e}})],{gap:16,padding:St(24),background:ut("#FFFFFF")})],{width:348,grow:1,gap:2})],{gap:24},!0),r.rule("terminal_rule",n),i("terminal_footer","GROW / \u6309\u8D44\u6E90\u67E5\u770B\u4F59\u989D \xB7 \u6309\u8BB0\u5F55\u6838\u5BF9\u4F7F\u7528","GROW / RESOURCE BALANCES \xB7 TRANSACTION RECORDS")])}function vf(){let e="#253F34",t="#F5F3EC",n="#5C6A60",r="#DBE8B8",i=new Nt("\u4F1A\u5458\u4FF1\u4E50\u90E8",{theme:{background:t,text:e,primary:e,radius:"none"},width:1160,gap:32,padding:{top:28,right:24,bottom:48,left:24}}),a=(o,s,c,u=n)=>i.text(o,s,c,12,u,{text:{size:12,color:u,font:"mono",letterSpacing:1,weight:500}});return i.document([i.stack("club_masthead",[i.stack("club_identity",[i.text("wordmark","GROW CLUB","GROW CLUB",22,e,{text:{size:22,color:e,weight:700,letterSpacing:-.6}}),a("club_edition","\u4F1A\u5458 / MEMBERSHIP","MEMBERSHIP / YOUR SPACE")],{gap:20},!0),i.rule("club_rule",e),i.stack("club_intro",[i.text("heading","\u4F1A\u5458\u4E0E\u65B9\u6848","Room to grow.",64,e,{width:752,grow:2,text:{size:64,color:e,font:"serif",weight:400,lineHeight:1.1,letterSpacing:-2}}),i.stack("club_description",[a("club_intro_label","\u4E3A\u6301\u7EED\u7684\u521B\u9020\u529B","FOR WHAT COMES NEXT"),i.text("description",`\u67E5\u770B\u4F60\u7684\u4F1A\u5458\u72B6\u6001\uFF0C
|
|
4
|
-
\u627E\u5230\u9002\u5408\u4E0B\u4E00\u6B65\u7684\u65B9\u6848\u3002`,`Your membership, at a glance.
|
|
5
|
-
A plan for what comes next.`,14,n)],{width:320,grow:1,gap:12,padding:{top:10,right:0,bottom:0,left:0}})],{gap:40},!0)],{gap:24}),i.stack("membership_summary",[i.stack("member_spread",[a("member_index","01 / \u4F60\u7684\u4F1A\u5458","01 / YOUR MEMBERSHIP","#CCD9CA"),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,{text:{color:"#FFFFFF",font:"serif",size:52,weight:400}})],{width:744,grow:2,gap:20,padding:St(32),background:ut(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:St(28),background:ut(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=K0("\u521B\u4F5C\u5DE5\u4F5C\u533A");return e.document([H0(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,{...Xa(784,2),...G0(80)}),e.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!1,{...Xa(328),background:ut(_f),padding:St(24),shape:{type:"rect",radius:10}})],{gap:48,padding:{top:12,right:0,bottom:8,left:0}},!0),e.rule("workspace_rule",bf),e.stack("studio_workspace",[e.widget("transactions","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",!1,Xa(784,2)),e.stack("credit_shop",[e.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!0),e.rule("shop_rule",bf),e.widget("orders","credit_pack_orders","\u6700\u8FD1\u8D2D\u4E70","Recent purchases",!0)],{...Xa(328),...W0,padding:St(24),gap:24,background:ut(_f)})],{gap:48},!0)])}function If(){return xf()}var un=(e,t=1)=>({width:e,grow:t}),eo=(e=16)=>({shape:{type:"rect",radius:e}}),Xe=(e,t,n="system")=>({text:{color:e,...t?{size:t,font:n,weight:500}:{}}}),bn=(e,t,n=e)=>({top:e,right:t,bottom:n,left:t});function Q0(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 Z0(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 Fi(e,t,n,r,i,a="system"){let o=e.stack("masthead",[Q0(e,t,n,r,a),Z0(e,"scope","\u4E2A\u4EBA\u8D26\u6237","PERSONAL ACCOUNT",i)],{gap:20},!0);return o.justify="between",o.align="center",o}function Af(e,t,n=!1,r=5){let i=e.widget("activity","credit_transactions","\u6700\u8FD1\u4F7F\u7528","Recent activity",n,Xe(t));return i.data.pageSize=r,i}function Y0(){let e="#171D1A",t="#F2F5ED",n="#9EADA2",r="#D5E7B0",i=new Nt("\u6697\u7EFF\u79EF\u5206\u53F0",{theme:{background:e,text:t,primary:e},width:1120,gap:32,padding:bn(32,24,48)});return i.document([Fi(i,"\u79EF\u5206\u8D26\u6237","Credits",t,n),i.rule("header_rule","#354039"),i.stack("wallet_workspace",[i.stack("wallet_primary",[i.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,Xe(t,96)),i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,Xe(t))],{...un(680,2),gap:32,padding:bn(20,0,12)}),i.stack("purchase_sheet",[i.widget("packs","credit_packs","\u8865\u5145\u79EF\u5206","Add credits",!1,Xe(e))],{...un(328),background:ut(r),padding:St(24),...eo(20)})],{gap:72},!0),i.rule("activity_rule","#354039"),Af(i,t,!1,4)])}function J0(){let e="#302C26",t="#7D766B",n="#D8D1C5",r=new Nt("\u8D26\u6237\u6863\u6848",{theme:{background:"#F7F3EB",text:e,primary:"#84503B"},width:1080,gap:32,padding:bn(40,24,48)});return r.document([Fi(r,"\u8D26\u6237\u6863\u6848","Account journal",e,t,"serif"),r.rule("header_rule",e),r.stack("statement",[r.stack("balance_column",[r.widget("balance","credit_balance","\u53EF\u7528\u79EF\u5206","Available credits",!1,Xe(e,96,"serif"))],{...un(628,2),padding:bn(12,0),gap:24}),r.stack("membership_column",[r.widget("membership","membership","\u4F1A\u5458\u72B6\u6001","Membership",!1,Xe(e)),r.widget("offers","offer_history","\u8D26\u6237\u4F18\u60E0","Your offers",!0,Xe(e))],{...un(356),gap:20,padding:bn(12,0)})],{gap:96},!0),r.rule("orders_rule",n),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Purchases",!1,Xe(e))])}function X0(){let e="#223E33",t="#687C70",n="#254A3B",r="#F7F9F5",i=new Nt("\u4F1A\u5458\u7A7A\u95F4",{theme:{background:r,text:e,primary:n},width:1120,gap:32,padding:bn(32,24,48)});return i.document([Fi(i,"\u4F1A\u5458\u4E2D\u5FC3","Membership",e,t),i.stack("current_membership",[i.stack("member_credential",[i.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Current membership",!1,Xe("#F4F7F0"))],{...un(640,2),gap:24,background:ut(n),padding:St(32),...eo(20)}),i.stack("credit_context",[i.widget("balance","credit_balance","\u8D26\u6237\u79EF\u5206","Account credits",!0,Xe(e,64))],{...un(400),background:ut("#E9EFE5"),padding:St(28),...eo(20)})],{gap:24},!0),i.widget("plans","customer_plans","\u65B9\u6848\u4E0E\u4EF7\u683C","Plans & pricing",!1,Xe(e)),i.rule("offer_rule","#D5DFD3"),i.widget("offers","offer_history","\u6211\u7684\u4F18\u60E0","Your offers",!0,Xe(e))])}function z0(){let e="#23262B",t="#797E87",n="#DFE2E7",r=new Nt("\u7528\u91CF\u8D26\u518C",{theme:{background:"#FFFFFF",text:e,primary:e},width:1160,gap:28,padding:bn(32,24,48)});return r.document([Fi(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,{...un(688,2),...Xe(e,56,"mono")}),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,{...un(372),...Xe(e)})],{gap:72,padding:bn(4,0,8)},!0),r.rule("activity_rule",n),Af(r,e),r.rule("order_rule",n),r.widget("orders","credit_pack_orders","\u79EF\u5206\u8D2D\u4E70","Credit purchases",!0,Xe(e))])}function ev(){let e="#3F3029",t="#8B766A",n="#A34525",r=new Nt("\u79EF\u5206\u8865\u7ED9",{theme:{background:"#FEFAF5",text:e,primary:n},width:1160,gap:32,padding:bn(32,24,48)});return r.document([Fi(r,"\u8865\u5145\u79EF\u5206","Add credits",e,t),r.rule("header_rule","#E8DDD3"),r.stack("purchase_workspace",[r.stack("account_context",[r.widget("balance","credit_balance","\u73B0\u6709\u79EF\u5206","Current credits",!0,Xe(e,56)),r.rule("context_rule","#DBC5B5"),r.widget("membership","membership","\u5F53\u524D\u4F1A\u5458","Membership",!0,Xe(e))],{...un(304),gap:28,padding:St(24),background:ut("#F1E5D9"),...eo(16)}),r.stack("purchase_catalog",[r.widget("packs","credit_packs","\u53EF\u8D2D\u4E70\u7684\u79EF\u5206\u5305","Available credit packs",!1,Xe(e))],{...un(800,2),gap:24})],{gap:32},!0),r.rule("orders_rule","#E8DDD3"),r.widget("orders","credit_pack_orders","\u8D2D\u4E70\u8BB0\u5F55","Recent purchases",!1,Xe(e))])}function wf(){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:Y0},{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:J0},{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:X0},{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:If},{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:z0},{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:ev}].map(({create:e,...t})=>({...t,document:e()}))}function tv(){return Sf()}function nv(){return yf()}function rv(){return vf()}function zF(){return[...wf(),{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:tv()},{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:nv()},{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:rv()}]}import{z as Ct}from"zod";var Pf=Ct.object({id:Ct.string().min(1).max(136),name:Ct.string().min(1).max(128),type:Ct.enum(["entry","condition","feature"])}).strict(),iv=Ct.object({id:Ct.uuid(),name:Ct.string().min(1).max(80),status:Ct.enum(["draft","published","archived"]),draftNodes:Ct.array(Pf).max(600),publishedNodes:Ct.array(Pf).max(600),runningVersions:Ct.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"),n2=Ct.object({rows:Ct.array(iv).max(50),nextCursor:Ct.uuid().nullable()}).strict();import{z as Se}from"zod";var bt=Se.number().int().nonnegative(),Cf=Se.strictObject({at:Se.iso.datetime({offset:!0}),id:Se.uuid()}),s2=Se.strictObject({versionId:Se.uuid().nullable(),from:Se.iso.datetime({offset:!0}).nullable(),to:Se.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"),c2=Se.strictObject({funnelId:Se.uuid(),snapshotAt:Se.iso.datetime({offset:!0}),versions:Se.array(Se.strictObject({id:Se.uuid(),version:Se.number().int().positive(),createdAt:Se.iso.datetime({offset:!0})})).max(100),versionsLimited:Se.boolean(),overall:Se.strictObject({started:bt,completed:bt,closed:bt,failed:bt,waiting:bt,paid:bt}),decisions:Se.strictObject({queries:bt,completed:bt,reportedUsed:bt,pending:bt,failed:bt}),revenue:Se.array(Se.strictObject({currency:ae,grossMinor:Se.string().regex(/^\d+$/),refundMinor:Se.string().regex(/^\d+$/),netMinor:Se.string().regex(/^-?\d+$/)})).max(100),nodes:Se.array(Se.strictObject({versionId:Se.uuid(),nodeId:Se.string(),visits:bt,completed:bt,shown:bt,waiting:bt})).max(1e4),recentRuns:Se.array(Se.strictObject({id:Se.uuid(),versionId:Se.uuid(),customerId:Se.uuid(),status:gc,nodeId:Se.string(),visit:bt,createdAt:Se.iso.datetime({offset:!0}),updatedAt:Se.iso.datetime({offset:!0})})).max(100),nextCursor:Cf.nullable()});import{z as jn}from"zod";var m2=jn.object({requestId:jn.uuid(),coupon:Hl,audienceId:jn.uuid().nullable(),productVersionId:jn.uuid().optional(),presentation:gn,locale:jn.enum(["en","zh-CN"])}).strict(),f2=jn.object({couponId:jn.uuid(),funnelId:jn.uuid()}).strict();import{z as Ae}from"zod";var lt=Ae.number().int().nonnegative(),to=Ae.string().regex(/^-?\d+$/),av=Ae.object({currency:ae,grossMinor:to,refundMinor:to,netMinor:to,purchases:lt,refunds:lt}).strict(),_2=Ae.object({snapshotAt:Ae.iso.datetime({offset:!0}),customers:Ae.object({total:lt,created:lt,paid:lt}).strict(),memberships:Ae.object({active:lt,trial:lt,pastDue:lt,ended:lt}).strict(),runs:Ae.object({started:lt,completed:lt,closed:lt,paid:lt}).strict(),revenue:Ae.array(av).max(100),unknownMoney:lt,funnels:Ae.array(Ae.object({id:Ae.uuid(),name:Ae.string(),started:lt,completed:lt,paid:lt}).strict()).max(50),daily:Ae.array(Ae.object({date:Ae.iso.date(),currency:ae,netMinor:to}).strict()).max(9e3)}).strict(),y2=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 Kt}from"zod";import{z as dt}from"zod";var Of=dt.discriminatedUnion("provider",[dt.strictObject({provider:dt.literal("apple"),orderId:dt.uuid(),receiptId:dt.uuid(),signedTransaction:dt.string().min(1).max(131072)}),dt.strictObject({provider:dt.literal("google"),orderId:dt.uuid(),receiptId:dt.uuid(),purchaseToken:dt.string().min(1).max(16384)})]),Ef=dt.strictObject({orderId:dt.uuid(),receiptId:dt.uuid(),transactionIds:dt.array(dt.string().min(1).max(255)).min(1).max(50),membership:dt.boolean()});var P2=Kt.strictObject({operation:Kt.literal("native_receipt"),requestId:Kt.uuid(),customerToken:Kt.string().regex(/^gg_ct_[A-Za-z0-9_-]{32,128}$/),orderId:Kt.uuid(),receiptId:Kt.uuid(),nativeEvidence:Of.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),C2=Kt.strictObject({scope:je,requestId:Kt.uuid(),orderId:Kt.uuid(),receiptId:Kt.uuid(),orderStatus:Kt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:Kt.boolean(),nativeCompletion:Ef.optional()});import{z as ov}from"zod";var sv=Lm.extend({document:ov.union([It.refine(e=>e.pages.length===1,"Use a single owned screen template"),Dt.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 F2(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 cv(e,t){let n=structuredClone(sv.parse(e).document);if(n.kind==="funnel"){let l=function(d){if(Array.isArray(d)){d.forEach(l);return}if(!d||typeof d!="object")return;let p=d;p.type==="experiment-ref"&&(p.experimentId=u),p.$savedGroup&&typeof p.$savedGroup=="object"&&(p.$savedGroup.id=u),typeof p.$inGroup=="string"&&(p.$inGroup=u),typeof p.$notInGroup=="string"&&(p.$notInGroup=u),Object.values(p).forEach(l)};var c=l;let u="00000000-0000-0000-0000-000000000000";for(let d of Object.values(n.references))"id"in d&&(d.id=u);for(let d of n.graph.nodes)d.type==="condition"&&d.cases.forEach(p=>l(p.condition));for(let d of n.screens)d.type==="owned"&&Tf(d.document);return Dt.parse({...n,screens:n.screens.map(d=>d.type==="owned"?{...d,document:{...d.document,strings:{...d.document.strings,defaultLocale:Oo(d.document,[t])}}}:d),graph:{...n.graph,nodes:n.graph.nodes.map(d=>d.type==="split"?{...d,experimentId:"00000000-0000-0000-0000-000000000000"}:d.type==="offering"?{...d,configuration:d.configuration.source==="fixed"?{source:"fixed",versionId:u}:d.configuration}:d.type==="coupons"?{...d,couponIds:[]}:d.type==="coupon"?{...d,couponId:u}:d)}})}let r={...n,strings:{...n.strings,defaultLocale:Oo(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((u,l)=>{let d=`action_${l}`;return a[u.id]=u.close?"closed":"done",u.type==="open_url"?(a[u.id]=d,i.push({id:d,name:u.id,type:"output",value:{type:"literal",value:{intent:"open_url",url:u.url}}})):u.type==="claim_offer"&&(a[u.id]="unconnected"),{id:u.id,type:"event",event:u.id,properties:{},close:!1}}),Tf(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(Er)),s={};return Dt.parse({references:{},variables:s,outputSchema:{type:"json",nullable:!0},execution:{runTimeoutSeconds:604800,maxTransitions:1e4},kind:"funnel",schemaVersion:4,inputs:(()=>{let u=[];return Lt(r,l=>{if(l.type==="stack"&&l.interaction&&["input","select","multiselect","toggle","tabs"].includes(l.interaction.type)){let d=`answer_${crypto.randomUUID().replaceAll("-","")}`;s[d]={type:l.interaction.type==="toggle"?"boolean":l.interaction.type==="multiselect"?"strings":"string",nullable:!1,source:{type:"input"}},u.push({variable:d,screenId:"screen",componentId:l.id,required:!1})}}),u})(),screens:[{id:"screen",type:"owned",document:r}],graph:{version:5,entry:"entry",nodes:i.filter(u=>u.type!=="end"||o.has(u.id))}})}function U2(e,t,n){if(t.document.kind!=="screen")throw new Error("Choose a single screen template");let r=cv(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,p)=>+(p.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(([p,g])=>[p,o(g)]))}:d.type==="action"?{...d,id:o(d.id),success:o(d.success),cancel:o(d.cancel),unavailable:o(d.unavailable),failure:o(d.failure)}:d.type==="external_page"?{...d,id:o(d.id),opened:o(d.opened),failed:o(d.failed)}:{...d,id:o(d.id)}),c=Dt.parse({...e,variables:{...e.variables,...r.variables},screens:[...e.screens,...r.screens.map(d=>({...d,id:o(d.id)}))],inputs:[...e.inputs,...r.inputs.map(d=>({...d,screenId:o(d.screenId)}))],graph:{...e.graph,nodes:[...e.graph.nodes,...s]}}),u=0,l=0;for(let d of c.screens)d.type==="owned"&&(Lt(d.document,()=>{u++}),l+=d.document.actions.length);if(u>Qe.components||l>Qe.actions||wt(c)>Qe.documentBytes)throw new Error("Template exceeds the flow capacity");return c}function Tf(e){Lt(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 uv(e){return e.kind==="membership"&&["week","month","year"].includes(e.interval)}function B2(e){return e.kind==="topup"?"credit_pack":e.interval==="one_time"?"lifetime":"membership"}function Rf(e){return uv(e)?e.intervalCount??1:1}function L2(e,t){return e.interval===t.interval&&Rf(e)===Rf(t)}function q2(e,t,n=1){if(e==="free")return"";if(e==="one_time")return t.startsWith("zh")?" \xB7 \u4E00\u6B21\u4ED8\u6B3E":" \xB7 one-time";let r=t.split("-")[0]??"en",i={zh:["/\u6708","/\u5E74"],en:["/month","/year"],ja:["/\u6708","/\u5E74"],ko:["/\uC6D4","/\uB144"],es:["/mes","/a\xF1o"],fr:["/mois","/an"],de:["/Monat","/Jahr"],pt:["/m\xEAs","/ano"],it:["/mese","/anno"],ar:["/\u0634\u0647\u0631","/\u0633\u0646\u0629"]},a={zh:"\u5468",en:"week",ja:"\u9031",ko:"\uC8FC",es:"semana",fr:"semaine",de:"Woche",pt:"semana",it:"settimana",ar:"\u0623\u0633\u0628\u0648\u0639"},o=e==="week"?`/${a[r]??a.en}`:(i[r]??i.en)[e==="month"?0:1];return n===1?o:`/${n} ${o.slice(1)}${r==="en"?"s":""}`}import{z as Ve}from"zod";var jf=Ve.enum(["membership","trial","topup","manual","rollover","seat"]),kf=Ve.enum(["scheduled","active","expired","revoked","unavailable"]),K2=Ve.strictObject({customerId:Ve.uuid().nullable(),entityId:Ve.uuid().nullable(),internal_feature_id:Ve.uuid().nullable(),reason:jf.nullable(),status:kf.nullable(),after:Ve.uuid().nullable(),limit:Ve.number().int().min(1).max(50)}),H2=Ve.strictObject({snapshotAt:Ve.iso.datetime({offset:!0}),rows:Ve.array(Ve.strictObject({id:Ve.uuid(),customerId:Ve.uuid(),fundingCustomerId:Ve.uuid(),entityId:Ve.uuid().nullable(),internal_feature_id:Ve.uuid(),key:$i,name:Ve.string().min(1).max(120),kind:Ve.enum(["access","metered","credit"]),reason:jf,status:kf,unlimited:Ve.boolean(),granted:Tt,available:Tt,held:Tt,spent:Tt,revoked:Tt,transferred:Tt,startsAt:Ve.iso.datetime({offset:!0}).nullable(),expiresAt:Ve.iso.datetime({offset:!0}).nullable(),grantId:Ve.uuid().nullable(),membershipId:Ve.uuid().nullable(),seatPoolId:Ve.uuid().nullable()})).max(50),nextCursor:Ve.uuid().nullable()});import{z as Me}from"zod";var Df=Me.string().regex(/^[a-f0-9]{64}$/),lv=Ou.omit({variations:!0,active:!0}).extend({changeId:Df,variations:Me.array(Me.strictObject({urlRedirect:Me.string().max(2048)})).min(2).max(20)}),z2=Me.strictObject({environmentId:Me.uuid(),trackExposures:Me.boolean(),generation:Df,experiments:Me.array(lv).max(100),savedGroups:Tu}),dv=Me.strictObject({eventUuid:Me.uuid(),timestamp:Me.iso.datetime({offset:!0}).optional(),deviceId:Me.string().min(1).max(128),sessionId:Me.string().min(1).max(128).optional(),url:Me.url().max(2048),pageTitle:Me.string().max(512).optional(),experimentKey:Me.string().min(1).max(255),variationKey:Me.string().min(1).max(64)}),eU=Me.strictObject({events:Me.array(dv).min(1).max(20)}),tU=Me.strictObject({inserted:Me.number().int().nonnegative(),duplicates:Me.number().int().nonnegative(),skipped:Me.number().int().nonnegative(),rejected:Me.array(Me.strictObject({index:Me.number().int().nonnegative(),reason:Me.string()}))});import{z as q}from"zod";var Ff=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"})}),Uf=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)}),Ac={id:q.uuid(),revision:q.number().int().positive()},oU=q.strictObject({groups:q.array(q.strictObject({id:q.uuid(),name:q.string(),type:q.enum(["condition","list"])})),experiments:q.array(q.strictObject({...Ac,configuration:Zr,archivedAt:q.iso.datetime({offset:!0}).nullable()})),namespaces:q.array(q.strictObject({...Ac,configuration:Uf})),attributes:q.array(q.strictObject({...Ac,configuration:Ff})),truncated:q.boolean()}),wc={id:q.uuid().nullable(),revision:q.number().int().min(0)},sU=q.discriminatedUnion("resource",[q.strictObject({...wc,resource:q.literal("experiment"),configuration:Zr.safeExtend({archivedAt:q.iso.datetime({offset:!0}).nullable()})}),q.strictObject({...wc,resource:q.literal("namespace"),configuration:Uf}),q.strictObject({...wc,resource:q.literal("attribute"),configuration:Ff})]),cU=q.strictObject({operation:q.literal("evaluate"),attributes:Bt,condition:xn.optional(),features:ou,featureKey:q.string().min(1).max(128),customerId:q.uuid().nullable()}),uU=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()}),Nf=q.strictObject({resource:q.enum(["group","experiment","coupon"]),id:q.uuid()}),lU=q.strictObject({rows:q.array(Nf.extend({name:q.string(),status:q.string()})).max(50),total:q.number().int().nonnegative(),nextCursor:Nf.nullable()});var no=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function pv(e,t){let n=e.phases.at(-1),r=t.phases.at(-1),i=[];(!no(n.condition,r.condition)||!no(n.savedGroups,r.savedGroups))&&i.push("targeting"),r.coverage<n.coverage&&i.push("coverage"),r.namespace&&(!n.namespace||n.namespace.id!==r.namespace.id)&&i.push("namespace"),r.namespace&&n.namespace?.id===r.namespace.id&&n.namespace.ranges.some(([c,u])=>{let l=c;for(let[d,p]of[...r.namespace.ranges].sort((g,m)=>g[0]-m[0]))d<=l&&p>l&&(l=p);return l<u})&&i.push("namespaceRange"),(!no(n.variationWeights,r.variationWeights)||!no(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 mU(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(pv(e,t).disableSamePhase&&n.startsWith("same-phase"))throw Error("Start a new phase for these changes");if(a.bucketVersion=e.bucketVersion+(s&&n!=="same-phase-sticky"?1:0),a.minBucketVersion=n==="new-phase-block-sticky"?a.bucketVersion:e.minBucketVersion,n.startsWith("new-phase")){a.phases=structuredClone(e.phases);let c=a.phases.at(-1);if(!c)throw new Error("Experiment requires a phase");c.dateEnded=r,a.phases.push({...o,name:o.name,reason:o.reason,dateStarted:r,dateEnded:null,seed:i})}return Zr.parse(a)}import{z as mv}from"zod";var gU=mv.enum(["owner","admin","developer","sales","member"]),fv=["organisation","customers","features","plans","rewards","balances","billing","migrations","analytics","apiKeys","platform"],Mf=fv.flatMap(e=>e==="analytics"?["analytics:read"]:[`${e}:read`,`${e}:write`]),Bf={owner:Mf,admin:Mf,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 bU(e,t){if(!e||!Object.hasOwn(Bf,e))return!1;let n=Bf[e];return n.includes(t)||t.endsWith(":read")&&n.includes(t.replace(/:read$/,":write"))}var yU=["boolean","metered","credit_system","ai_credit_system"];function SU(e,t,n,r=!1){let i=[],a=(o,s)=>i.push({field:o,code:s});return e.type!==t.type&&(e.type==="credit_system"!=(t.type==="credit_system")&&a("type","type_switch_credit_system"),n.customerHistory&&a("type","attached_to_customer"),n.entityFeature&&a("type","used_as_entity_feature"),n.usagePrice&&a("type","has_usage_price"),n.creditSystems&&a("type","used_in_credit_system"),n.productEntitlements&&(e.type==="credit_system"||t.type==="credit_system")&&a("type","used_in_product_credit_system")),e.id!==t.id&&(r&&a("id","id_already_exists"),n.customerHistory&&a("id","attached_to_customer")),e.type!=="boolean"&&t.type!=="boolean"&&e.config?.usage_type!==t.config?.usage_type&&t.config?.usage_type&&(n.creditSystems&&a("usage_type","used_in_credit_system"),n.entityFeature&&a("usage_type","used_as_entity_feature"),n.customerHistory&&a("usage_type","attached_to_customer")),i}/*!
|
|
6
|
-
* decimal.js v10.6.0
|
|
7
|
-
* An arbitrary-precision Decimal type for JavaScript.
|
|
8
|
-
* https://github.com/MikeMcl/decimal.js
|
|
9
|
-
* Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
|
|
10
|
-
* MIT Licence
|
|
11
|
-
*/var Fr=9e15,Fn=1e9,Pc="0123456789abcdef",ao="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",oo="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",Cc={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-Fr,maxE:Fr,crypto:!1},$f,_n,se=!0,co="[DecimalError] ",Nn=co+"Invalid argument: ",Gf=co+"Precision limit exceeded",Wf=co+"crypto unavailable",Kf="[object Decimal]",_t=Math.floor,ze=Math.pow,hv=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,gv=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,bv=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,Hf=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,en=1e7,te=7,_v=9007199254740991,yv=ao.length-1,Oc=oo.length-1,O={toStringTag:Kf};O.absoluteValue=O.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),J(e)};O.ceil=function(){return J(new this.constructor(this),this.e+1,2)};O.clampedTo=O.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(Nn+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};O.comparedTo=O.cmp=function(e){var t,n,r,i,a=this,o=a.d,s=(e=new a.constructor(e)).d,c=a.s,u=e.s;if(!o||!s)return!c||!u?NaN:c!==u?c:o===s?0:!o^c<0?1:-1;if(!o[0]||!s[0])return o[0]?c:s[0]?-u:0;if(c!==u)return c;if(a.e!==e.e)return a.e>e.e^c<0?1:-1;for(r=o.length,i=s.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==s[t])return o[t]>s[t]^c<0?1:-1;return r===i?0:r>i^c<0?1:-1};O.cosine=O.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+te,r.rounding=1,n=Sv(r,Xf(r,n)),r.precision=e,r.rounding=t,J(_n==2||_n==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};O.cubeRoot=O.cbrt=function(){var e,t,n,r,i,a,o,s,c,u,l=this,d=l.constructor;if(!l.isFinite()||l.isZero())return new d(l);for(se=!1,a=l.s*ze(l.s*l,1/3),!a||Math.abs(a)==1/0?(n=pt(l.d),e=l.e,(a=(e-n.length+1)%3)&&(n+=a==1||a==-2?"0":"00"),a=ze(n,1/3),e=_t((e+1)/3)-(e%3==(e<0?-1:2)),a==1/0?n="5e"+e:(n=a.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new d(n),r.s=l.s):r=new d(a.toString()),o=(e=d.precision)+3;;)if(s=r,c=s.times(s).times(s),u=c.plus(l),r=Be(u.plus(l).times(s),u.plus(c),o+2,1),pt(s.d).slice(0,o)===(n=pt(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(J(s,e+1,0),s.times(s).times(s).eq(l))){r=s;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(J(r,e+1,1),t=!r.times(r).times(r).eq(l));break}return se=!0,J(r,e,d.rounding,t)};O.decimalPlaces=O.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-_t(this.e/te))*te,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};O.dividedBy=O.div=function(e){return Be(this,new this.constructor(e))};O.dividedToIntegerBy=O.divToInt=function(e){var t=this,n=t.constructor;return J(Be(t,new n(e),0,1,1),n.precision,n.rounding)};O.equals=O.eq=function(e){return this.cmp(e)===0};O.floor=function(){return J(new this.constructor(this),this.e+1,3)};O.greaterThan=O.gt=function(e){return this.cmp(e)>0};O.greaterThanOrEqualTo=O.gte=function(e){var t=this.cmp(e);return t==1||t===0};O.hyperbolicCosine=O.cosh=function(){var e,t,n,r,i,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/lo(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),a=Ur(o,1,a.times(t),new o(1),!0);for(var c,u=e,l=new o(8);u--;)c=a.times(a),a=s.minus(c.times(l.minus(c.times(l))));return J(a,o.precision=n,o.rounding=r,!0)};O.hyperbolicSine=O.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=Ur(a,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/lo(5,e)),i=Ur(a,2,i,i,!0);for(var o,s=new a(5),c=new a(16),u=new a(20);e--;)o=i.times(i),i=i.times(s.plus(o.times(c.times(o).plus(u))))}return a.precision=t,a.rounding=n,J(i,t,n,!0)};O.hyperbolicTangent=O.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Be(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};O.inverseCosine=O.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?ln(t,r,i):new t(0):new t(NaN):e.isZero()?ln(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};O.inverseHyperbolicCosine=O.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,se=!1,n=n.times(n).minus(1).sqrt().plus(n),se=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};O.inverseHyperbolicSine=O.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,se=!1,n=n.times(n).plus(1).sqrt().plus(n),se=!0,r.precision=e,r.rounding=t,n.ln())};O.inverseHyperbolicTangent=O.atanh=function(){var e,t,n,r,i=this,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?J(new a(i),e,t,!0):(a.precision=n=r-i.e,i=Be(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)};O.inverseSine=O.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=ln(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)))};O.inverseTangent=O.atan=function(){var e,t,n,r,i,a,o,s,c,u=this,l=u.constructor,d=l.precision,p=l.rounding;if(u.isFinite()){if(u.isZero())return new l(u);if(u.abs().eq(1)&&d+4<=Oc)return o=ln(l,d+4,p).times(.25),o.s=u.s,o}else{if(!u.s)return new l(NaN);if(d+4<=Oc)return o=ln(l,d+4,p).times(.5),o.s=u.s,o}for(l.precision=s=d+10,l.rounding=1,n=Math.min(28,s/te+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(se=!1,t=Math.ceil(s/te),r=1,c=u.times(u),o=new l(u),i=u;e!==-1;)if(i=i.times(c),a=o.minus(i.div(r+=2)),i=i.times(c),o=a.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===a.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),se=!0,J(o,l.precision=d,l.rounding=p,!0)};O.isFinite=function(){return!!this.d};O.isInteger=O.isInt=function(){return!!this.d&&_t(this.e/te)>this.d.length-2};O.isNaN=function(){return!this.s};O.isNegative=O.isNeg=function(){return this.s<0};O.isPositive=O.isPos=function(){return this.s>0};O.isZero=function(){return!!this.d&&this.d[0]===0};O.lessThan=O.lt=function(e){return this.cmp(e)<0};O.lessThanOrEqualTo=O.lte=function(e){return this.cmp(e)<1};O.logarithm=O.log=function(e){var t,n,r,i,a,o,s,c,u=this,l=u.constructor,d=l.precision,p=l.rounding,g=5;if(e==null)e=new l(10),t=!0;else{if(e=new l(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new l(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new l(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)a=!0;else{for(i=n[0];i%10===0;)i/=10;a=i!==1}if(se=!1,s=d+g,o=Dn(u,s),r=t?so(l,s+10):Dn(e,s),c=Be(o,r,s,1),Ui(c.d,i=d,p))do if(s+=10,o=Dn(u,s),r=t?so(l,s+10):Dn(e,s),c=Be(o,r,s,1),!a){+pt(c.d).slice(i+1,i+15)+1==1e14&&(c=J(c,d+1,0));break}while(Ui(c.d,i+=10,p));return se=!0,J(c,d,p)};O.minus=O.sub=function(e){var t,n,r,i,a,o,s,c,u,l,d,p,g=this,m=g.constructor;if(e=new m(e),!g.d||!e.d)return!g.s||!e.s?e=new m(NaN):g.d?e.s=-e.s:e=new m(e.d||g.s!==e.s?g:NaN),e;if(g.s!=e.s)return e.s=-e.s,g.plus(e);if(u=g.d,p=e.d,s=m.precision,c=m.rounding,!u[0]||!p[0]){if(p[0])e.s=-e.s;else if(u[0])e=new m(g);else return new m(c===3?-0:0);return se?J(e,s,c):e}if(n=_t(e.e/te),l=_t(g.e/te),u=u.slice(),a=l-n,a){for(d=a<0,d?(t=u,a=-a,o=p.length):(t=p,n=l,o=u.length),r=Math.max(Math.ceil(s/te),o)+2,a>r&&(a=r,t.length=1),t.reverse(),r=a;r--;)t.push(0);t.reverse()}else{for(r=u.length,o=p.length,d=r<o,d&&(o=r),r=0;r<o;r++)if(u[r]!=p[r]){d=u[r]<p[r];break}a=0}for(d&&(t=u,u=p,p=t,e.s=-e.s),o=u.length,r=p.length-o;r>0;--r)u[o++]=0;for(r=p.length;r>a;){if(u[--r]<p[r]){for(i=r;i&&u[--i]===0;)u[i]=en-1;--u[i],u[r]+=en}u[r]-=p[r]}for(;u[--o]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=uo(u,n),se?J(e,s,c):e):new m(c===3?-0:0)};O.modulo=O.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?J(new r(n),r.precision,r.rounding):(se=!1,r.modulo==9?(t=Be(n,e.abs(),0,3,1),t.s*=e.s):t=Be(n,e,0,r.modulo,1),t=t.times(e),se=!0,n.minus(t))};O.naturalExponential=O.exp=function(){return Ec(this)};O.naturalLogarithm=O.ln=function(){return Dn(this)};O.negated=O.neg=function(){var e=new this.constructor(this);return e.s=-e.s,J(e)};O.plus=O.add=function(e){var t,n,r,i,a,o,s,c,u,l,d=this,p=d.constructor;if(e=new p(e),!d.d||!e.d)return!d.s||!e.s?e=new p(NaN):d.d||(e=new p(e.d||d.s===e.s?d:NaN)),e;if(d.s!=e.s)return e.s=-e.s,d.minus(e);if(u=d.d,l=e.d,s=p.precision,c=p.rounding,!u[0]||!l[0])return l[0]||(e=new p(d)),se?J(e,s,c):e;if(a=_t(d.e/te),r=_t(e.e/te),u=u.slice(),i=a-r,i){for(i<0?(n=u,i=-i,o=l.length):(n=l,r=a,o=u.length),a=Math.ceil(s/te),o=a>o?a+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=u.length,i=l.length,o-i<0&&(i=o,n=l,l=u,u=n),t=0;i;)t=(u[--i]=u[i]+l[i]+t)/en|0,u[i]%=en;for(t&&(u.unshift(t),++r),o=u.length;u[--o]==0;)u.pop();return e.d=u,e.e=uo(u,r),se?J(e,s,c):e};O.precision=O.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Nn+e);return n.d?(t=Qf(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};O.round=function(){var e=this,t=e.constructor;return J(new t(e),e.e+1,t.rounding)};O.sine=O.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+te,r.rounding=1,n=xv(r,Xf(r,n)),r.precision=e,r.rounding=t,J(_n>2?n.neg():n,e,t,!0)):new r(NaN)};O.squareRoot=O.sqrt=function(){var e,t,n,r,i,a,o=this,s=o.d,c=o.e,u=o.s,l=o.constructor;if(u!==1||!s||!s[0])return new l(!u||u<0&&(!s||s[0])?NaN:s?o:1/0);for(se=!1,u=Math.sqrt(+o),u==0||u==1/0?(t=pt(s),(t.length+c)%2==0&&(t+="0"),u=Math.sqrt(t),c=_t((c+1)/2)-(c<0||c%2),u==1/0?t="5e"+c:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+c),r=new l(t)):r=new l(u.toString()),n=(c=l.precision)+3;;)if(a=r,r=a.plus(Be(o,a,n+2,1)).times(.5),pt(a.d).slice(0,n)===(t=pt(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(J(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")&&(J(r,c+1,1),e=!r.times(r).eq(o));break}return se=!0,J(r,c,l.rounding,e)};O.tangent=O.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Be(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,J(_n==2||_n==4?n.neg():n,e,t,!0)):new r(NaN)};O.times=O.mul=function(e){var t,n,r,i,a,o,s,c,u,l=this,d=l.constructor,p=l.d,g=(e=new d(e)).d;if(e.s*=l.s,!p||!p[0]||!g||!g[0])return new d(!e.s||p&&!p[0]&&!g||g&&!g[0]&&!p?NaN:!p||!g?e.s/0:e.s*0);for(n=_t(l.e/te)+_t(e.e/te),c=p.length,u=g.length,c<u&&(a=p,p=g,g=a,o=c,c=u,u=o),a=[],o=c+u,r=o;r--;)a.push(0);for(r=u;--r>=0;){for(t=0,i=c+r;i>r;)s=a[i]+g[r]*p[i-r-1]+t,a[i--]=s%en|0,t=s/en|0;a[i]=(a[i]+t)%en|0}for(;!a[--o];)a.pop();return t?++n:a.shift(),e.d=a,e.e=uo(a,n),se?J(e,d.precision,d.rounding):e};O.toBinary=function(e,t){return Tc(this,2,e,t)};O.toDecimalPlaces=O.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(Ot(e,0,Fn),t===void 0?t=r.rounding:Ot(t,0,8),J(n,e+n.e+1,t))};O.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=dn(r,!0):(Ot(e,0,Fn),t===void 0?t=i.rounding:Ot(t,0,8),r=J(new i(r),e+1,t),n=dn(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};O.toFixed=function(e,t){var n,r,i=this,a=i.constructor;return e===void 0?n=dn(i):(Ot(e,0,Fn),t===void 0?t=a.rounding:Ot(t,0,8),r=J(new a(i),e+i.e+1,t),n=dn(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};O.toFraction=function(e){var t,n,r,i,a,o,s,c,u,l,d,p,g=this,m=g.d,h=g.constructor;if(!m)return new h(g);if(u=n=new h(1),r=c=new h(0),t=new h(r),a=t.e=Qf(m)-g.e-1,o=a%te,t.d[0]=ze(10,o<0?te+o:o),e==null)e=a>0?t:u;else{if(s=new h(e),!s.isInt()||s.lt(u))throw Error(Nn+s);e=s.gt(t)?a>0?t:u:s}for(se=!1,s=new h(pt(m)),l=h.precision,h.precision=a=m.length*te*2;d=Be(s,t,0,1,1),i=n.plus(d.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=c.plus(d.times(i)),c=i,i=t,t=s.minus(d.times(i)),s=i;return i=Be(e.minus(n),r,0,1,1),c=c.plus(i.times(u)),n=n.plus(i.times(r)),c.s=u.s=g.s,p=Be(u,r,a,1).minus(g).abs().cmp(Be(c,n,a,1).minus(g).abs())<1?[u,r]:[c,n],h.precision=l,se=!0,p};O.toHexadecimal=O.toHex=function(e,t){return Tc(this,16,e,t)};O.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:Ot(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(se=!1,n=Be(n,e,0,t,1).times(e),se=!0,J(n)):(e.s=n.s,n=e),n};O.toNumber=function(){return+this};O.toOctal=function(e,t){return Tc(this,8,e,t)};O.toPower=O.pow=function(e){var t,n,r,i,a,o,s=this,c=s.constructor,u=+(e=new c(e));if(!s.d||!e.d||!s.d[0]||!e.d[0])return new c(ze(+s,u));if(s=new c(s),s.eq(1))return s;if(r=c.precision,a=c.rounding,e.eq(1))return J(s,r,a);if(t=_t(e.e/te),t>=e.d.length-1&&(n=u<0?-u:u)<=_v)return i=Zf(c,s,n,r),e.s<0?new c(1).div(i):J(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=ze(+s,u),t=n==0||!isFinite(n)?_t(u*(Math.log("0."+pt(s.d))/Math.LN10+s.e+1)):new c(n+"").e,t>c.maxE+1||t<c.minE-1?new c(t>0?o/0:0):(se=!1,c.rounding=s.s=1,n=Math.min(12,(t+"").length),i=Ec(e.times(Dn(s,r+n)),r),i.d&&(i=J(i,r+5,1),Ui(i.d,r,a)&&(t=r+10,i=J(Ec(e.times(Dn(s,t+n)),t),t+5,1),+pt(i.d).slice(r+1,r+15)+1==1e14&&(i=J(i,r+1,0)))),i.s=o,se=!0,c.rounding=a,J(i,r,a))};O.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=dn(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(Ot(e,1,Fn),t===void 0?t=i.rounding:Ot(t,0,8),r=J(new i(r),e,t),n=dn(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};O.toSignificantDigits=O.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(Ot(e,1,Fn),t===void 0?t=r.rounding:Ot(t,0,8)),J(new r(n),e,t)};O.toString=function(){var e=this,t=e.constructor,n=dn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};O.truncated=O.trunc=function(){return J(new this.constructor(this),this.e+1,1)};O.valueOf=O.toJSON=function(){var e=this,t=e.constructor,n=dn(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function pt(e){var t,n,r,i=e.length-1,a="",o=e[0];if(i>0){for(a+=o,t=1;t<i;t++)r=e[t]+"",n=te-r.length,n&&(a+=kn(n)),a+=r;o=e[t],r=o+"",n=te-r.length,n&&(a+=kn(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return a+o}function Ot(e,t,n){if(e!==~~e||e<t||e>n)throw Error(Nn+e)}function Ui(e,t,n,r){var i,a,o,s;for(a=e[0];a>=10;a/=10)--t;return--t<0?(t+=te,i=0):(i=Math.ceil((t+1)/te),t%=te),a=ze(10,te-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)==ze(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)==ze(10,t-3)-1,o}function ro(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]+=Pc.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 Sv(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/lo(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=Ur(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 Be=(function(){function e(r,i,a){var o,s=0,c=r.length;for(r=r.slice();c--;)o=r[c]*i+s,r[c]=o%a|0,s=o/a|0;return s&&r.unshift(s),r}function t(r,i,a,o){var s,c;if(a!=o)c=a>o?1:-1;else for(s=c=0;s<a;s++)if(r[s]!=i[s]){c=r[s]>i[s]?1:-1;break}return c}function n(r,i,a,o){for(var s=0;a--;)r[a]-=s,s=r[a]<i[a]?1:0,r[a]=s*o+r[a]-i[a];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,a,o,s,c){var u,l,d,p,g,m,h,y,w,x,k,I,v,K,$,we,Te,oe,V,Fe,Z=r.constructor,rt=r.s==i.s?1:-1,de=r.d,ie=i.d;if(!de||!de[0]||!ie||!ie[0])return new Z(!r.s||!i.s||(de?ie&&de[0]==ie[0]:!ie)?NaN:de&&de[0]==0||!ie?rt*0:rt/0);for(c?(g=1,l=r.e-i.e):(c=en,g=te,l=_t(r.e/g)-_t(i.e/g)),V=ie.length,Te=de.length,w=new Z(rt),x=w.d=[],d=0;ie[d]==(de[d]||0);d++);if(ie[d]>(de[d]||0)&&l--,a==null?(K=a=Z.precision,o=Z.rounding):s?K=a+(r.e-i.e)+1:K=a,K<0)x.push(1),m=!0;else{if(K=K/g+2|0,d=0,V==1){for(p=0,ie=ie[0],K++;(d<Te||p)&&K--;d++)$=p*c+(de[d]||0),x[d]=$/ie|0,p=$%ie|0;m=p||d<Te}else{for(p=c/(ie[0]+1)|0,p>1&&(ie=e(ie,p,c),de=e(de,p,c),V=ie.length,Te=de.length),we=V,k=de.slice(0,V),I=k.length;I<V;)k[I++]=0;Fe=ie.slice(),Fe.unshift(0),oe=ie[0],ie[1]>=c/2&&++oe;do p=0,u=t(ie,k,V,I),u<0?(v=k[0],V!=I&&(v=v*c+(k[1]||0)),p=v/oe|0,p>1?(p>=c&&(p=c-1),h=e(ie,p,c),y=h.length,I=k.length,u=t(h,k,y,I),u==1&&(p--,n(h,V<y?Fe:ie,y,c))):(p==0&&(u=p=1),h=ie.slice()),y=h.length,y<I&&h.unshift(0),n(k,h,I,c),u==-1&&(I=k.length,u=t(ie,k,V,I),u<1&&(p++,n(k,V<I?Fe:ie,I,c))),I=k.length):u===0&&(p++,k=[0]),x[d++]=p,u&&k[0]?k[I++]=de[we]||0:(k=[de[we]],I=1);while((we++<Te||k[0]!==void 0)&&K--);m=k[0]!==void 0}x[0]||x.shift()}if(g==1)w.e=l,$f=m;else{for(d=1,p=x[0];p>=10;p/=10)d++;w.e=d+l*g-1,J(w,s?a+w.e+1:a,o,m)}return w}})();function J(e,t,n,r){var i,a,o,s,c,u,l,d,p,g=e.constructor;e:if(t!=null){if(d=e.d,!d)return e;for(i=1,s=d[0];s>=10;s/=10)i++;if(a=t-i,a<0)a+=te,o=t,l=d[p=0],c=l/ze(10,i-o-1)%10|0;else if(p=Math.ceil((a+1)/te),s=d.length,p>=s)if(r){for(;s++<=p;)d.push(0);l=c=0,i=1,a%=te,o=a-te+1}else break e;else{for(l=s=d[p],i=1;s>=10;s/=10)i++;a%=te,o=a-te+i,c=o<0?0:l/ze(10,i-o-1)%10|0}if(r=r||t<0||d[p+1]!==void 0||(o<0?l:l%ze(10,i-o-1)),u=n<4?(c||r)&&(n==0||n==(e.s<0?3:2)):c>5||c==5&&(n==4||r||n==6&&(a>0?o>0?l/ze(10,i-o):0:d[p-1])%10&1||n==(e.s<0?8:7)),t<1||!d[0])return d.length=0,u?(t-=e.e+1,d[0]=ze(10,(te-t%te)%te),e.e=-t||0):d[0]=e.e=0,e;if(a==0?(d.length=p,s=1,p--):(d.length=p+1,s=ze(10,te-a),d[p]=o>0?(l/ze(10,i-o)%ze(10,o)|0)*s:0),u)for(;;)if(p==0){for(a=1,o=d[0];o>=10;o/=10)a++;for(o=d[0]+=s,s=1;o>=10;o/=10)s++;a!=s&&(e.e++,d[0]==en&&(d[0]=1));break}else{if(d[p]+=s,d[p]!=en)break;d[p--]=0,s=1}for(a=d.length;d[--a]===0;)d.pop()}return se&&(e.e>g.maxE?(e.d=null,e.e=NaN):e.e<g.minE&&(e.e=0,e.d=[0])),e}function dn(e,t,n){if(!e.isFinite())return Jf(e);var r,i=e.e,a=pt(e.d),o=a.length;return t?(n&&(r=n-o)>0?a=a.charAt(0)+"."+a.slice(1)+kn(r):o>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(e.e<0?"e":"e+")+e.e):i<0?(a="0."+kn(-i-1)+a,n&&(r=n-o)>0&&(a+=kn(r))):i>=o?(a+=kn(i+1-o),n&&(r=n-i-1)>0&&(a=a+"."+kn(r))):((r=i+1)<o&&(a=a.slice(0,r)+"."+a.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(a+="."),a+=kn(r))),a}function uo(e,t){var n=e[0];for(t*=te;n>=10;n/=10)t++;return t}function so(e,t,n){if(t>yv)throw se=!0,n&&(e.precision=n),Error(Gf);return J(new e(ao),t,1,!0)}function ln(e,t,n){if(t>Oc)throw Error(Gf);return J(new e(oo),t,n,!0)}function Qf(e){var t=e.length-1,n=t*te+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function kn(e){for(var t="";e--;)t+="0";return t}function Zf(e,t,n,r){var i,a=new e(1),o=Math.ceil(r/te+4);for(se=!1;;){if(n%2&&(a=a.times(t),qf(a.d,o)&&(i=!0)),n=_t(n/2),n===0){n=a.d.length-1,i&&a.d[n]===0&&++a.d[n];break}t=t.times(t),qf(t.d,o)}return se=!0,a}function Lf(e){return e.d[e.d.length-1]&1}function Yf(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 Ec(e,t){var n,r,i,a,o,s,c,u=0,l=0,d=0,p=e.constructor,g=p.rounding,m=p.precision;if(!e.d||!e.d[0]||e.e>17)return new p(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(se=!1,c=m):c=t,s=new p(.03125);e.e>-2;)e=e.times(s),d+=5;for(r=Math.log(ze(2,d))/Math.LN10*2+5|0,c+=r,n=a=o=new p(1),p.precision=c;;){if(a=J(a.times(e),c,1),n=n.times(++l),s=o.plus(Be(a,n,c,1)),pt(s.d).slice(0,c)===pt(o.d).slice(0,c)){for(i=d;i--;)o=J(o.times(o),c,1);if(t==null)if(u<3&&Ui(o.d,c-r,g,u))p.precision=c+=10,n=a=s=new p(1),l=0,u++;else return J(o,p.precision=m,g,se=!0);else return p.precision=m,o}o=s}}function Dn(e,t){var n,r,i,a,o,s,c,u,l,d,p,g=1,m=10,h=e,y=h.d,w=h.constructor,x=w.rounding,k=w.precision;if(h.s<0||!y||!y[0]||!h.e&&y[0]==1&&y.length==1)return new w(y&&!y[0]?-1/0:h.s!=1?NaN:y?0:h);if(t==null?(se=!1,l=k):l=t,w.precision=l+=m,n=pt(y),r=n.charAt(0),Math.abs(a=h.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)h=h.times(e),n=pt(h.d),r=n.charAt(0),g++;a=h.e,r>1?(h=new w("0."+n),a++):h=new w(r+"."+n.slice(1))}else return u=so(w,l+2,k).times(a+""),h=Dn(new w(r+"."+n.slice(1)),l-m).plus(u),w.precision=k,t==null?J(h,k,x,se=!0):h;for(d=h,c=o=h=Be(h.minus(1),h.plus(1),l,1),p=J(h.times(h),l,1),i=3;;){if(o=J(o.times(p),l,1),u=c.plus(Be(o,new w(i),l,1)),pt(u.d).slice(0,l)===pt(c.d).slice(0,l))if(c=c.times(2),a!==0&&(c=c.plus(so(w,l+2,k).times(a+""))),c=Be(c,new w(g),l,1),t==null)if(Ui(c.d,l-m,x,s))w.precision=l+=m,u=o=h=Be(d.minus(1),d.plus(1),l,1),p=J(h.times(h),l,1),i=s=1;else return J(c,w.precision=k,x,se=!0);else return w.precision=k,c;c=u,i+=2}}function Jf(e){return String(e.s*e.s/0)}function io(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%te,n<0&&(r+=te),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=te;r<i;)e.d.push(+t.slice(r,r+=te));t=t.slice(r),r=te-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),se&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function vv(e,t){var n,r,i,a,o,s,c,u,l;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),Hf.test(t))return io(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(gv.test(t))n=16,t=t.toLowerCase();else if(hv.test(t))n=2;else if(bv.test(t))n=8;else throw Error(Nn+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=Zf(r,new r(n),a,a*2)),u=ro(t,n,en),l=u.length-1,a=l;u[a]===0;--a)u.pop();return a<0?new r(e.s*0):(e.e=uo(u,l),e.d=u,se=!1,o&&(e=Be(e,i,s*4)),c&&(e=e.times(Math.abs(c)<54?ze(2,c):tn.pow(2,c))),se=!0,e)}function xv(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:Ur(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/lo(5,n)),t=Ur(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 Ur(e,t,n,r,i){var a,o,s,c,u=1,l=e.precision,d=Math.ceil(l/te);for(se=!1,c=n.times(n),s=new e(r);;){if(o=Be(s.times(c),new e(t++*t++),l,1),s=i?r.plus(o):r.minus(o),r=Be(o.times(c),new e(t++*t++),l,1),o=s.plus(r),o.d[d]!==void 0){for(a=d;o.d[a]===s.d[a]&&a--;);if(a==-1)break}a=s,s=r,r=o,o=a,u++}return se=!0,o.d.length=d+1,o}function lo(e,t){for(var n=e;--t;)n*=e;return n}function Xf(e,t){var n,r=t.s<0,i=ln(e,e.precision,1),a=i.times(.5);if(t=t.abs(),t.lte(a))return _n=r?4:1,t;if(n=t.divToInt(i),n.isZero())_n=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(a))return _n=Lf(n)?r?2:3:r?4:1,t;_n=Lf(n)?r?1:4:r?3:2}return t.minus(i).abs()}function Tc(e,t,n,r){var i,a,o,s,c,u,l,d,p,g=e.constructor,m=n!==void 0;if(m?(Ot(n,1,Fn),r===void 0?r=g.rounding:Ot(r,0,8)):(n=g.precision,r=g.rounding),!e.isFinite())l=Jf(e);else{for(l=dn(e),o=l.indexOf("."),m?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(l=l.replace(".",""),p=new g(1),p.e=l.length-o,p.d=ro(dn(p),10,i),p.e=p.d.length),d=ro(l,10,i),a=c=d.length;d[--c]==0;)d.pop();if(!d[0])l=m?"0p+0":"0";else{if(o<0?a--:(e=new g(e),e.d=d,e.e=a,e=Be(e,p,n,r,0,i),d=e.d,a=e.e,u=$f),o=d[n],s=i/2,u=u||d[n+1]!==void 0,u=r<4?(o!==void 0||u)&&(r===0||r===(e.s<0?3:2)):o>s||o===s&&(r===4||u||r===6&&d[n-1]&1||r===(e.s<0?8:7)),d.length=n,u)for(;++d[--n]>i-1;)d[n]=0,n||(++a,d.unshift(1));for(c=d.length;!d[c-1];--c);for(o=0,l="";o<c;o++)l+=Pc.charAt(d[o]);if(m){if(c>1)if(t==16||t==8){for(o=t==16?4:3,--c;c%o;c++)l+="0";for(d=ro(l,i,t),c=d.length;!d[c-1];--c);for(o=1,l="1.";o<c;o++)l+=Pc.charAt(d[o])}else l=l.charAt(0)+"."+l.slice(1);l=l+(a<0?"p":"p+")+a}else if(a<0){for(;++a;)l="0"+l;l="0."+l}else if(++a>c)for(a-=c;a--;)l+="0";else a<c&&(l=l.slice(0,a)+"."+l.slice(a))}l=(t==16?"0x":t==2?"0b":t==8?"0o":"")+l}return e.s<0?"-"+l:l}function qf(e,t){if(e.length>t)return e.length=t,!0}function Iv(e){return new this(e).abs()}function Av(e){return new this(e).acos()}function wv(e){return new this(e).acosh()}function Pv(e,t){return new this(e).plus(t)}function Cv(e){return new this(e).asin()}function Ov(e){return new this(e).asinh()}function Ev(e){return new this(e).atan()}function Tv(e){return new this(e).atanh()}function Rv(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=ln(this,a,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?ln(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=ln(this,a,1).times(.5),n.s=e.s):t.s<0?(this.precision=a,this.rounding=1,n=this.atan(Be(e,t,a,1)),t=ln(this,a,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Be(e,t,a,1)),n}function jv(e){return new this(e).cbrt()}function kv(e){return J(e=new this(e),e.e+1,2)}function Dv(e,t,n){return new this(e).clamp(t,n)}function Nv(e){if(!e||typeof e!="object")throw Error(co+"Object expected");var t,n,r,i=e.defaults===!0,a=["precision",1,Fn,"rounding",0,8,"toExpNeg",-Fr,0,"toExpPos",0,Fr,"maxE",0,Fr,"minE",-Fr,0,"modulo",0,9];for(t=0;t<a.length;t+=3)if(n=a[t],i&&(this[n]=Cc[n]),(r=e[n])!==void 0)if(_t(r)===r&&r>=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(Nn+n+": "+r);if(n="crypto",i&&(this[n]=Cc[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(Wf);else this[n]=!1;else throw Error(Nn+n+": "+r);return this}function Fv(e){return new this(e).cos()}function Uv(e){return new this(e).cosh()}function zf(e){var t,n,r;function i(a){var o,s,c,u=this;if(!(u instanceof i))return new i(a);if(u.constructor=i,Vf(a)){u.s=a.s,se?!a.d||a.e>i.maxE?(u.e=NaN,u.d=null):a.e<i.minE?(u.e=0,u.d=[0]):(u.e=a.e,u.d=a.d.slice()):(u.e=a.e,u.d=a.d?a.d.slice():a.d);return}if(c=typeof a,c==="number"){if(a===0){u.s=1/a<0?-1:1,u.e=0,u.d=[0];return}if(a<0?(a=-a,u.s=-1):u.s=1,a===~~a&&a<1e7){for(o=0,s=a;s>=10;s/=10)o++;se?o>i.maxE?(u.e=NaN,u.d=null):o<i.minE?(u.e=0,u.d=[0]):(u.e=o,u.d=[a]):(u.e=o,u.d=[a]);return}if(a*0!==0){a||(u.s=NaN),u.e=NaN,u.d=null;return}return io(u,a.toString())}if(c==="string")return(s=a.charCodeAt(0))===45?(a=a.slice(1),u.s=-1):(s===43&&(a=a.slice(1)),u.s=1),Hf.test(a)?io(u,a):vv(u,a);if(c==="bigint")return a<0?(a=-a,u.s=-1):u.s=1,io(u,a.toString());throw Error(Nn+a)}if(i.prototype=O,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Nv,i.clone=zf,i.isDecimal=Vf,i.abs=Iv,i.acos=Av,i.acosh=wv,i.add=Pv,i.asin=Cv,i.asinh=Ov,i.atan=Ev,i.atanh=Tv,i.atan2=Rv,i.cbrt=jv,i.ceil=kv,i.clamp=Dv,i.cos=Fv,i.cosh=Uv,i.div=Mv,i.exp=Bv,i.floor=Lv,i.hypot=qv,i.ln=Vv,i.log=$v,i.log10=Wv,i.log2=Gv,i.max=Kv,i.min=Hv,i.mod=Qv,i.mul=Zv,i.pow=Yv,i.random=Jv,i.round=Xv,i.sign=zv,i.sin=ex,i.sinh=tx,i.sqrt=nx,i.sub=rx,i.sum=ix,i.tan=ax,i.tanh=ox,i.trunc=sx,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 Mv(e,t){return new this(e).div(t)}function Bv(e){return new this(e).exp()}function Lv(e){return J(e=new this(e),e.e+1,3)}function qv(){var e,t,n=new this(0);for(se=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return se=!0,new this(1/0);n=t}return se=!0,n.sqrt()}function Vf(e){return e instanceof tn||e&&e.toStringTag===Kf||!1}function Vv(e){return new this(e).ln()}function $v(e,t){return new this(e).log(t)}function Gv(e){return new this(e).log(2)}function Wv(e){return new this(e).log(10)}function Kv(){return Yf(this,arguments,-1)}function Hv(){return Yf(this,arguments,1)}function Qv(e,t){return new this(e).mod(t)}function Zv(e,t){return new this(e).mul(t)}function Yv(e,t){return new this(e).pow(t)}function Jv(e){var t,n,r,i,a=0,o=new this(1),s=[];if(e===void 0?e=this.precision:Ot(e,1,Fn),r=Math.ceil(e/te),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(Wf);else for(;a<r;)s[a++]=Math.random()*1e7|0;for(r=s[--a],e%=te,r&&e&&(i=ze(10,te-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-=te)s.shift();for(r=1,i=s[0];i>=10;i/=10)r++;r<te&&(n-=te-r)}return o.e=n,o.d=s,o}function Xv(e){return J(e=new this(e),e.e+1,this.rounding)}function zv(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function ex(e){return new this(e).sin()}function tx(e){return new this(e).sinh()}function nx(e){return new this(e).sqrt()}function rx(e,t){return new this(e).sub(t)}function ix(){var e=0,t=arguments,n=new this(t[e]);for(se=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return se=!0,J(n,this.precision,this.rounding)}function ax(e){return new this(e).tan()}function ox(e){return new this(e).tanh()}function sx(e){return J(e=new this(e),e.e+1,1)}O[Symbol.for("nodejs.util.inspect.custom")]=O.toString;O[Symbol.toStringTag]="Decimal";var tn=O.constructor=zf(Cc);ao=new tn(ao);oo=new tn(oo);var{PAYLOAD_BYTES:cx}={PAYLOAD_BYTES:20},{KSUID_EPOCH:ux}={KSUID_EPOCH:14e8},{getRandomBytes:lx}={getRandomBytes:({size:t})=>{let n=new Uint8Array(t);return globalThis.crypto.getRandomValues(n),n}},{ALPHABET:dx}={ALPHABET:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"},{ENCODED_LENGTH:px}={ENCODED_LENGTH:27},{base62Encode:mx}=(e=>({base62Encode:({bytes:n,padTo:r})=>{let i=[],a=new Uint8Array(n),o=!1;for(;!o;){o=!0;let s=0;for(let c=0;c<a.length;c++){let u=s*256+a[c];a[c]=Math.floor(u/62),s=u%62,a[c]!==0&&(o=!1)}i.push(s)}for(i.reverse();i.length<r;)i.unshift(0);return i.map(s=>e[s]).join("")}}))(dx),{generateKsuid:eh}=((e,t,n,r,i)=>({generateKsuid:({prefix:o=""}={})=>{let s=new Uint8Array(e),c=Math.floor(Date.now()/1e3)-t;s[0]=c>>>24&255,s[1]=c>>>16&255,s[2]=c>>>8&255,s[3]=c&255;let u=n({size:16});s.set(u,4);let l=r({bytes:s,padTo:i});return`${o}${l}`}}))(cx,ux,lx,mx,px);var th={randomSync:()=>({string:eh({})})};import{z as xe}from"zod/v4";var fx=202,hx=502,gx=400,bx=409,_x=100,yx=201,Sx=417;var vx=403,xx=504,Ix=410,Ax=505,wx=418,Px=419,Cx=507,Ox=500,Ex=411,Tx=423,Rx=420,jx=405,kx=301,Dx=302,Nx=207,Fx=300,Ux=511,Mx=204,Bx=203,Lx=406,qx=404,Vx=501,$x=304,Gx=200,Wx=206,Kx=402,Hx=308,Qx=412,Zx=428,Yx=102,Jx=407,Xx=431,zx=408,eI=413,tI=414,nI=416,rI=205,iI=303,aI=503,oI=101,sI=307,cI=429,uI=401,lI=422,dI=415,pI=305,nh={ACCEPTED:fx,BAD_GATEWAY:hx,BAD_REQUEST:gx,CONFLICT:bx,CONTINUE:_x,CREATED:yx,EXPECTATION_FAILED:Sx,FORBIDDEN:vx,GATEWAY_TIMEOUT:xx,GONE:Ix,HTTP_VERSION_NOT_SUPPORTED:Ax,IM_A_TEAPOT:wx,INSUFFICIENT_SPACE_ON_RESOURCE:Px,INSUFFICIENT_STORAGE:Cx,INTERNAL_SERVER_ERROR:Ox,LENGTH_REQUIRED:Ex,LOCKED:Tx,METHOD_FAILURE:Rx,METHOD_NOT_ALLOWED:jx,MOVED_PERMANENTLY:kx,MOVED_TEMPORARILY:Dx,MULTI_STATUS:Nx,MULTIPLE_CHOICES:Fx,NETWORK_AUTHENTICATION_REQUIRED:Ux,NO_CONTENT:Mx,NON_AUTHORITATIVE_INFORMATION:Bx,NOT_ACCEPTABLE:Lx,NOT_FOUND:qx,NOT_IMPLEMENTED:Vx,NOT_MODIFIED:$x,OK:Gx,PARTIAL_CONTENT:Wx,PAYMENT_REQUIRED:Kx,PERMANENT_REDIRECT:Hx,PRECONDITION_FAILED:Qx,PRECONDITION_REQUIRED:Zx,PROCESSING:Yx,PROXY_AUTHENTICATION_REQUIRED:Jx,REQUEST_HEADER_FIELDS_TOO_LARGE:Xx,REQUEST_TIMEOUT:zx,REQUEST_TOO_LONG:eI,REQUEST_URI_TOO_LONG:tI,REQUESTED_RANGE_NOT_SATISFIABLE:nI,RESET_CONTENT:rI,SEE_OTHER:iI,SERVICE_UNAVAILABLE:aI,SWITCHING_PROTOCOLS:oI,TEMPORARY_REDIRECT:sI,TOO_MANY_REQUESTS:cI,UNAUTHORIZED:uI,UNPROCESSABLE_ENTITY:lI,UNSUPPORTED_MEDIA_TYPE:dI,USE_PROXY:pI};var rh={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"},ih={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 mI(e){var t=rh[e.toString()];if(!t)throw new Error("Status code does not exist: "+e);return t}function ah(e){var t=ih[e];if(!t)throw new Error("Reason phrase does not exist: "+e);return t}var oh=mI;var Un;(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"})(Un||(Un={}));var po=function(){return po=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++){t=arguments[n];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},po.apply(this,arguments)},kU=po(po({},nh),{getStatusCode:ah,getStatusText:oh});var{generateId:Mr}=(e=>({generateId:n=>n?`${n}_${e.randomSync().string}`:e.randomSync().string}))(th),{BILLING_CONTROL_KEYS:mo}={BILLING_CONTROL_KEYS:["auto_topups","spend_limits","usage_limits","usage_alerts","overage_allowed"]},{PurchaseLimitInterval:fI}=(()=>{var e;return(function(t){t.Hour="hour",t.Day="day",t.Week="week",t.Month="month"})(e||(e={})),{PurchaseLimitInterval:e}})(),{entToPrice:sh}={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:Ht}={nullish:t=>t==null},{FeatureType:yt}=(()=>{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:fo}=(()=>{var e;return(function(t){t.Fixed="fixed",t.Unlimited="unlimited",t.None="none"})(e||(e={})),{AllowanceType:e}})(),{Infinite:Mi}={Infinite:"inf"},{EntInterval:Br}=(()=>{var e;return(function(t){t.Lifetime="lifetime",t.Minute="minute",t.Hour="hour",t.Day="day",t.Week="week",t.Month="month",t.Quarter="quarter",t.SemiAnnual="semi_annual",t.Year="year"})(e||(e={})),{EntInterval:e}})(),{BillingInterval:yn}=(()=>{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:hI}={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:gI}={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:Rc}={TierInfinite:"inf"},{FeatureUsageType:Mn}=(()=>{var e;return(function(t){t.Single="single_use",t.Continuous="continuous_use"})(e||(e={})),{FeatureUsageType:e}})(),{PriceType:Lr}=(()=>{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:Bi}=(()=>{var e;return(function(t){t.InAdvance="in_advance",t.StartOfPeriod="start_of_period",t.EndOfPeriod="end_of_period"})(e||(e={})),{BillWhen:e}})(),{AllocatedBillingBehavior:Bn}=(()=>{var e;return(function(t){t.Arrear="arrear",t.Prorated="prorated"})(e||(e={})),{AllocatedBillingBehavior:e}})(),{ProductItemFeatureType:Sn}=(()=>{var e;return(function(t){t.SingleUse="single_use",t.ContinuousUse="continuous_use",t.Boolean="boolean",t.Static="static"})(e||(e={})),{ProductItemFeatureType:e}})(),{UsageModel:Vr}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.PayPerUse="pay_per_use"})(e||(e={})),{UsageModel:e}})(),{InternalError:bI}=(()=>{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:ch}=((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}}))(yt,Sn),{billingControlsFromColumns:uh}=(e=>({billingControlsFromColumns:n=>n?Object.fromEntries(e.flatMap(r=>n[r]==null?[]:[[r,n[r]]])):{}}))(mo),{nullish:$r}={nullish:t=>t==null},{RecaseError:Et}=(()=>{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:Ft}={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:_I}=((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})}}))(Et,Ft),{notNullish:Gr}=(e=>({notNullish:n=>!e(n)}))($r),{keyToTitle:lh}={keyToTitle:t=>t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())},{AggregateType:yI}=(()=>{var e;return(function(t){t.Sum="sum"})(e||(e={})),{AggregateType:e}})(),{ProductItemType:SI}=(()=>{var e;return(function(t){t.Feature="feature",t.FeaturePrice="priced_feature",t.Price="price"})(e||(e={})),{ProductItemType:e}})(),{ApiFeatureType:vI}=(()=>{var e;return(function(t){t.Static="static",t.Boolean="boolean",t.SingleUsage="single_use",t.ContinuousUse="continuous_use",t.CreditSystem="credit_system",t.AiCreditSystem="ai_credit_system"})(e||(e={})),{ApiFeatureType:e}})(),{ProductItemInterval:jc}=(()=>{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:dh}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:xI}={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:II}=(e=>({COMMON_SET:new Set(e)}))(dh),{hasNoDuplicateCurrencies:ph}={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:mh}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{TierBehavior:ho}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{OnIncrease:Wr}=(()=>{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:Li}=(()=>{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:kc}=(()=>{var e;return(function(t){t.Month="month",t.Forever="forever"})(e||(e={})),{RolloverExpiryDurationType:e}})(),{EntitlementDuration:AI}=(()=>{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:wI}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:PI}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:fh}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(xe),{flatCreditRateShape:hh}=(e=>({flatCreditRateShape:{credit_amount:e.number(),tier_behavior:e.never().optional(),tiers:e.never().optional()}}))(xe),{CreditTierSchema:CI}=(e=>({CreditTierSchema:e.object({to:e.union([e.number(),e.literal("inf")]),credit_amount:e.number()})}))(xe),{CreditMultiplierSchema:OI}=((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"})}))(xe,fh),{MarkupEntrySchema:gh}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(xe),{ModelMarkupsSchema:EI}=((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()}))(xe,gh),{isFeaturePriceItem:Dc}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(Gr),{notNullish:or}={notNullish:t=>t!=null},{isAiCreditSystem:Nc}=(e=>({isAiCreditSystem:n=>n===e.AiCreditSystem}))(yt),{VIOLATION_MESSAGES:TI}={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:RI}={sameSpecificity:(t,n)=>Object.keys(t.match).length===Object.keys(n.match).length&&(t.priority??null)===(n.priority??null)},{matchesCanCoexist:bh}={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:jI}={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:DI}={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:NI}=((e,t)=>({worstCaseRate:({multipliers:r,cheapestRate:i})=>r.reduce((a,o)=>{let s=[];for(let u of r){let l=u.factor!==void 0&&u.factor<1||u.add!==void 0&&u.add<0,d=s.every(p=>e(p.match,u.match));(l||u===o)&&e(o.match,u.match)&&d&&s.push(u)}let c=s.reduce((u,l)=>u.mul(l.factor!==void 0&&l.factor<1?l.factor:1).add(l.add!==void 0&&l.add<0?l.add:0),new t(i));return t.min(a,c)},new t(i))}))(bh,tn),{validateCreditSystemSchemaReferences:FI}=((e,t,n,r)=>({validateCreditSystemSchemaReferences:({config:a,allFeatures:o,selfFeatureId:s})=>{let c=Array.isArray(a?.schema)?a.schema:[];if(c.length!==0)for(let u of c){let l=u.metered_feature_id;if(!l||l===s)continue;let d=o.find(p=>p.id===l);if(d){if(d.type===e.CreditSystem)throw new t({message:`Credit system schema cannot reference another credit system (${l}). Only metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Boolean)throw new t({message:`Credit system schema cannot reference boolean feature ${l}. Only consumable (single-use) metered or AI credit features are allowed.`,code:n.InvalidFeature,statusCode:400});if(d.type===e.Metered&&d.config?.usage_type===r.Continuous)throw new t({message:`Credit system schema cannot reference continuous feature ${l}. Only consumable (single-use) metered features are allowed.`,code:n.InvalidFeature,statusCode:400})}}}}))(yt,Et,Ft,Mn),{isPriceItem:Fc}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(Gr,$r),{isFeatureItem:go}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)}))(Gr,$r),{itemToBillingInterval:Ln}=((e,t)=>({itemToBillingInterval:({item:r})=>{let i=r.price_interval??r.interval;return e(i)?t.OneOff:i}}))(Ht,yn),{rolloverConfigToIssue:UI}={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:bo}=((e,t,n)=>({itemToEntInterval:({item:i})=>e(i.interval)||i.feature_type===n.ContinuousUse?t.Lifetime:i.interval}))(Ht,Br,Sn),{itemToEntIntervalCount:_o}={itemToEntIntervalCount:({item:t})=>t.interval_count??1},{itemToBillingIntervalCount:Kr}={itemToBillingIntervalCount:({item:t})=>t.price_interval_count??t.interval_count??1},{isFeatureItem:yo}=((e,t)=>({isFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price===0)&&t(r.tiers)}))(or,Ht),{toKey:_h}={toKey:t=>t.toLowerCase()},{priceOwnedStripePriceId:MI}=(e=>({priceOwnedStripePriceId:({price:n})=>{let r=n.config,i=r.stripe_prepaid_price_v2_id||r.stripe_price_id;return e(i)?null:i}}))(Ht),{UsageTierSchema:Uc}=((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()}))}))(xe,Mi),{IgnoredFixedPriceMetadataSchema:BI}=(e=>({IgnoredFixedPriceMetadataSchema:e.preprocess(n=>typeof n=="string"?null:n,e.null().or(e.undefined()))}))(xe),{hasCatalogCurrencies:LI}={hasCatalogCurrencies:t=>Object.keys(t??{}).length>0},{usageTiersToComparisonShape:qI}={usageTiersToComparisonShape:t=>t.map((n,r)=>({amount:n.amount,flat_amount:n.flat_amount??0,to:r===t.length-1?null:n.to}))},{normalizedAllocatedBillingBehavior:VI}=(e=>({normalizedAllocatedBillingBehavior:n=>n.allocated_billing_behavior??(n.should_prorate?e.Prorated:e.Arrear)}))(Bn),{getResetUsage:yh}=((e,t,n,r)=>({getResetUsage:({item:a,feature:o})=>{if(a.feature_id)return e(a.reset_usage_when_enabled)&&(t(a)||n(a))&&o?o?.config?.usage_type===r.Single:a.reset_usage_when_enabled}}))($r,go,Dc,Mn),{hasUnlimitedAllowanceType:$I}=(e=>({hasUnlimitedAllowanceType:n=>n.allowance_type===e.Unlimited}))(fo),{normalizedEntitlementInterval:Sh}=(e=>({normalizedEntitlementInterval:n=>n.interval??e.Lifetime}))(Br),{normalizedEntitlementIntervalCount:GI}=((e,t)=>({normalizedEntitlementIntervalCount:r=>e(r)===t.Lifetime?1:r.interval_count??1}))(Sh,Br),{normalizeOptionalId:WI}={normalizeOptionalId:t=>t||null},{rolloversAreSame:KI}=(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}))(kc),{deterministicStringify:Mc}=(()=>{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:HI}={MARKUP_FIELDS:["markup","input_cost","output_cost"]},{expiriesAreSame:QI}={expiriesAreSame:(t,n)=>(t.expiry_duration??null)===(n.expiry_duration??null)&&(t.expiry_length??null)==(n.expiry_length??null)},{itemToFeature:vh}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{isFeaturePriceItem:Hr}=(e=>({isFeaturePriceItem:n=>e(n.feature_id)&&(e(n.price)||e(n.tiers))}))(or),{ProductErrorCode:ZI}={ProductErrorCode:{ProductNotFound:"product_not_found",ProductAlreadyExists:"product_already_exists",InvalidProductItem:"invalid_product_item"}},{buildUsagePriceCurrencies:YI}=(e=>({buildUsagePriceCurrencies:({baseTiers:n,itemTiers:r,flatCurrencies:i})=>{if(r?.length){let a=[...new Set(r.flatMap(s=>(s.additional_currencies??[]).map(c=>e(c.currency))))];if(a.length===0)return;let o={};for(let s of a)o[s]={usage_tiers:n.map((c,u)=>{let l=(r[u]?.additional_currencies??[]).find(d=>e(d.currency)===s);return{to:c.to,amount:l?.amount??0,...l?.flat_amount!==void 0?{flat_amount:l.flat_amount}:{}}})};return o}if(i?.length&&n.length>0){let a={};for(let{currency:o,amount:s}of i)a[e(o)]={usage_tiers:[{to:n[0].to,amount:s}]};return a}}}))(_h),{itemToFeature:JI}={itemToFeature:({item:t,features:n})=>n.find(i=>i.id===t.feature_id)},{shouldProrate:XI}=((e,t)=>({shouldProrate:r=>r?r===e.ProrateNextCycle||r===e.ProrateImmediately||r===t.ProrateImmediately||r===t.ProrateNextCycle:!0}))(Wr,Li),{getBillingType:zI}=((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}}))(Lr,yn,qr,Bi),{stripeResourceFields:eA}={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:tA}={PREVIEW_STRIPE_PRICE_ID_PREFIX:"price_PREVIEW_"},{PREVIEW_STRIPE_PRODUCT_ID_PREFIX:nA}={PREVIEW_STRIPE_PRODUCT_ID_PREFIX:"prod_PREVIEW_"},{normalizeOptionalId:rA}={normalizeOptionalId:t=>t||null},{stripeProductOnlyFields:iA}={stripeProductOnlyFields:["stripe_product_id","stripe_meter_id"]},{copyField:aA}=(e=>({copyField:({fromConfig:n,toConfig:r,field:i})=>!e(r[i])||e(n[i])?!1:(r[i]=n[i],!0)}))(Ht),{stripeResourceFields:oA}={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:sA}={handleCustomProductItems:({newPrices:t,newEnts:n,updatedPrices:r,updatedEnts:i,samePrices:a,sameEnts:o,features:s})=>({prices:[...t,...r,...a],entitlements:[...n,...i,...o].map(c=>({...c,feature:s.find(u=>u.id===c.feature_id)})),customPrices:[...t,...r],customEnts:[...n,...i],features:s})},{validateLicenseBillingMode:cA}=((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})}}))(Et,Ft),{PlanItemMatchPrecision:uA}=(()=>{var e;return(function(t){t.FeatureBillingMethodCadence="feature_billing_method_cadence",t.FeatureCadence="feature_cadence"})(e||(e={})),{PlanItemMatchPrecision:e}})(),{catalogPlanItemIdentity:lA}={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:dA}={applyPrice:(t,n)=>n===void 0?t:n===null?null:{...n}},{planItemMatchesFilter:pA}={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:mA}={isFreeNonResetEntitlement:t=>t.price==null&&t.reset==null},{toApiPlanItemPrice:fA}={toApiPlanItemPrice:t=>t?{...t,billing_units:t.billing_units??1,max_purchase:t.max_purchase??null}:null},{toApiPlanItemRollover:hA}={toApiPlanItemRollover:t=>{if(t)return{...t,max:t.max??null}}},{applyFreeTrial:gA}={applyFreeTrial:(t,n)=>{if(n===void 0)return t;if(n!==null)return{...n}}},{applyLicenseUpsert:bA}={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:xh}=(()=>{var e;return(function(t){t.Identity="identity",t.IdentityAndIncluded="identity_and_included"})(e||(e={})),{PlanItemFilterPrecision:e}})(),{additionalCurrenciesCompatible:Bc}={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:_A}={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:yA}=(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)})}))(Bc),{rolloversEqual:SA}={rolloversEqual:(t,n)=>t==null&&n==null?!0:t==null||n==null?!1:t.expiry_duration_type===n.expiry_duration_type&&(t.expiry_duration_length??null)===(n.expiry_duration_length??null)&&(t.max??null)===(n.max??null)&&(t.max_percentage??null)===(n.max_percentage??null)},{prorationsEqual:vA}={prorationsEqual:(t,n)=>t==null&&n==null?!0:t==null||n==null?!1:(t.on_increase??null)===(n.on_increase??null)&&(t.on_decrease??null)===(n.on_decrease??null)},{creditSchemaFingerprint:xA}=(e=>({creditSchemaFingerprint:n=>e(Object.fromEntries((n??[]).map(r=>[r.metered_feature_id,{...r,billing_units:r.billing_units??1}])))}))(Mc),{toCreatePlanItemParams:IA}={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:AA}=(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}}))(xh),{FreeTrialDuration:wA}=(()=>{var e;return(function(t){t.Day="day",t.Month="month",t.Year="year"})(e||(e={})),{FreeTrialDuration:e}})(),{arraysEqual:PA}={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:CA}={normalizeIntervalCount:({interval:t,intervalCount:n})=>t?n??1:n??""},{hasLicenseCustomize:Ih}={hasLicenseCustomize:t=>t!=null&&(t.price!==void 0||t.add_items!==void 0||t.remove_items!==void 0)},{byLicensePlanId:OA}={byLicensePlanId:(t,n)=>t.license_plan_id.localeCompare(n.license_plan_id)},{variantSettingKeys:EA}={variantSettingKeys:["name","description","group","add_on","config","billing_controls","metadata"]},{valuesEqual:TA}={valuesEqual:(t,n)=>JSON.stringify(t)===JSON.stringify(n)},{omitVariantOwnedSettings:qU}={omitVariantOwnedSettings:({name:t,...n})=>n},{isFreeProductV2:RA}=(e=>({isFreeProductV2:({items:n})=>n.every(r=>e(r.price)&&e(r.tiers))}))(Ht),{isPriceItem:So}=((e,t)=>({isPriceItem:r=>e(r.price)&&t(r.feature_id)}))(or,Ht),{isDefaultTrialV2:VU}=(e=>({isDefaultTrialV2:({freeTrial:n,items:r,isDefault:i})=>n?n.card_required===!1&&i&&!e({items:r}):!1}))(RA),{variantSettingsFields:jA}={variantSettingsFields:["description","group","is_add_on","is_default","config","billing_controls","metadata"]},{sortDeep:Ah}=(()=>{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:kA}={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:DA}={propagatedSettingFields:["description","group","is_add_on","config","billing_controls","metadata"]},{licenseParentTargetKey:NA}={licenseParentTargetKey:({planId:t,version:n})=>`${t}@${n}`},{STRIPE_ZERO_DECIMAL_CURRENCIES:wh}={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:FA}={STRIPE_THREE_DECIMAL_CURRENCIES:new Set(["bhd","jod","kwd","omr","tnd"])},{currencyInputDecimals:Ph}=(e=>({currencyInputDecimals:n=>e.has((n??"usd").toLowerCase())?0:2}))(wh),{entIntervalToValue:UA}=((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)}}))(tn,Br),{intervalToValue:MA}=(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)}))(yn),{normalizeIncludedUsage:Ch}={normalizeIncludedUsage:t=>t??0},{rolloversAreSame:Oh}={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:BA}=((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)}))(Wr,Li),{itemToExplicitAllocatedBillingBehavior:LA}=((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)}))(or,Bn),{additionalCurrenciesAreSame:Lc}={additionalCurrenciesAreSame:(t,n)=>{let r=t??[],i=n??[];if(r.length!==i.length)return!1;let a=(c,u)=>c.currency.localeCompare(u.currency),o=[...r].sort(a),s=[...i].sort(a);return o.every((c,u)=>c.currency===s[u].currency&&(c.amount??null)===(s[u].amount??null)&&(c.flat_amount??null)===(s[u].flat_amount??null))}},{itemPricingTiers:qA}={itemPricingTiers:t=>t.tiers?.length?t.tiers:t.price!=null?[{amount:t.price,to:"inf"}]:null},{priceItemsAreSame:VA}=((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}}))(Ln,Kr,Lc),{calculateProrationAmount:$A}=(e=>({calculateProrationAmount:({periodEnd:n,periodStart:r,now:i,amount:a,allowNegative:o=!1})=>{let s=new e(n).minus(i),c=new e(n).minus(r),u=s.div(c).mul(a);return u.lte(0)&&!o?0:u.toNumber()}}))(tn),{getResetUsage:GA}=((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}}))(Ht,yo,Hr,Mn),{compareDetails:WA}={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:KA}={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:HA}=(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}}))(mo),{sortControls:QA}={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:ZA}={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:YA}={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:JA}={prodOptionsAreSame:({curProduct:t,newProduct:n})=>t.is_default===n.is_default&&t.is_add_on===n.is_add_on},{PurchaseLimitIntervalEnum:XA}=((e,t)=>({PurchaseLimitIntervalEnum:e.enum(t)}))(xe,fI),{entToItemInterval:Eh}=(e=>({entToItemInterval:({entInterval:n})=>!n||n===e.Lifetime?null:n}))(Br),{billingToItemInterval:Th}=(e=>({billingToItemInterval:({billingInterval:n})=>n===e.OneOff?null:n}))(yn),{isContUseFeature:Rh}=(e=>({isContUseFeature:({feature:n})=>n.config?.usage_type===e.Continuous}))(Mn),{getBillingType:qc}=((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}}))(Lr,yn,qr,Bi),{isAllocatedPrice:jh}=((e,t)=>({isAllocatedPrice:r=>r?e(r.config)===t.InArrearProrated:!1}))(qc,qr),{priceToEnt:Vc}=(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}})(bI),{isBooleanFeatureItem:kh}=((e,t)=>({isBooleanFeatureItem:r=>e(r.feature_id)&&(t(r.price)||r.price==0)&&t(r.tiers)&&t(r.interval)&&t(r.included_usage)}))(Gr,$r),{constructBooleanFeature:zA}=((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})}))(Mr,lh,yt),{constructMeteredFeature:e1}=((e,t,n,r)=>({constructMeteredFeature:({featureId:a,name:o,orgId:s,env:c,usageType:u,eventNames:l=[]})=>({internal_id:e("fe"),org_id:s,env:c,created_at:Date.now(),id:a,name:o||t(a),type:n.Metered,config:{filters:[{property:"event_name",operator:"eq",value:[]}],aggregate:{type:r.Sum,property:"value"},usage_type:u},archived:!1,event_names:l,model_markups:null})}))(Mr,lh,yt,yI),{ApiFeatureV0Schema:t1}=((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."})})}))(xe,vI),{CURRENCY_CODES:n1}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(dh,xI,II),{RolloverConfigSchema:r1}=((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()})}))(xe,kc),{EntitlementExpirySchema:i1}=((e,t)=>({EntitlementExpirySchema:e.object({duration:e.enum(t),length:e.number()})}))(xe,AI),{CreditDimensionNameSchema:a1}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(xe,wI,PI),{CreditDimensionBaseSchema:o1}=((e,t)=>({CreditDimensionBaseSchema:e.object({match:t,priority:e.number().int().optional()})}))(xe,fh),{graduatedCreditRateShape:Dh}=((e,t)=>({graduatedCreditRateShape:{credit_amount:e.never().optional(),tier_behavior:e.literal("graduated"),tiers:e.array(t)}}))(xe,CI),{ProviderMarkupsSchema:s1}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(xe,gh),{isAnyCreditSystem:c1}=((e,t)=>({isAnyCreditSystem:r=>r===e.CreditSystem||t(r)}))(yt,Nc),{findCreditTierViolations:u1}=(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}}))(TI),{findAmbiguousCreditDimensions:l1}=((e,t)=>({findAmbiguousCreditDimensions:r=>{let i=Object.entries(r),a=[];for(let[o,[s,c]]of i.entries())for(let[u,l]of i.slice(o+1))e(c,l)&&t(c.match,l.match)&&a.push({names:[s,u],example:{...c.match,...l.match}});return a}}))(RI,bh),{validateMultipliersKeepRatesNonNegative:d1}=((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.`)}}))(DI,NI),{buildFixedPriceCurrencies:p1}=(e=>({buildFixedPriceCurrencies:n=>{if(!n?.length)return;let r={};for(let{currency:i,amount:a}of n)r[e(i)]={amount:a};return r}}))(_h),{PriceCurrencyConfigSchema:Nh}=((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()})}))(xe,Uc),{baseCurrenciesAreCompatible:m1}=(e=>({baseCurrenciesAreCompatible:({base1:n,base2:r,currencies1:i,currencies2:a})=>(n??null)===(r??null)||e(i)!==e(a)}))(LI),{tiersAreSame:Fh}=(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})}}))(qI),{UsagePriceConfigSchema:f1}=((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()})}))(xe,Bi,Uc,yn,Nh,Bn),{toFeature:h1}=((e,t,n,r,i,a,o)=>({toFeature:({item:c,orgId:u,internalFeatureId:l,internalProductId:d,isCustom:p,newVersion:g,feature:m,curEnt:h})=>{let y=m?.type===e.Boolean,w=t({item:c,feature:m}),x={id:c.entitlement_id||h?.id||n("ent"),org_id:u,created_at:c.created_at||Date.now(),is_custom:p,internal_product_id:d||null,internal_feature_id:l,feature_id:c.feature_id,allowance:c.included_usage===r?null:c.included_usage,allowance_type:y?null:c.included_usage===r?i.Unlimited:i.Fixed,interval:y?null:a({item:c}),interval_count:o({item:c}),carry_from_previous:!w,entity_feature_id:c.entity_feature_id,pooled:c.pooled??!1,usage_limit:null,rollover:c.config?.rollover,expiry_duration:c.config?.expiry?.duration,expiry_length:c.config?.expiry?.length,feature_override:c.config?.feature_override};return(p||g)&&(x={...x,id:n("ent"),created_at:Date.now()}),{price:null,ent:x}}}))(yt,yh,Mr,Mi,fo,bo,_o),{creditDimensionRulesEqual:g1}=(e=>({creditDimensionRulesEqual:({left:n,right:r})=>e(n.dimensions??{})===e(r.dimensions??{})&&e(n.multipliers??{})===e(r.multipliers??{})}))(Mc),{markupRecordsAreSame:b1}=(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)))}))(HI),{itemToUsageType:_1}=((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}}))(vh,yt,Sn),{itemToUsageType:y1}=((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}}))(JI,yt,Sn),{isPreviewStripeId:S1}=((e,t)=>({isPreviewStripeId:({stripeId:r})=>r?.startsWith(e)===!0||r?.startsWith(t)===!0}))(tA,nA),{findPairedEntitlement:v1}=(e=>({findPairedEntitlement:({price:n,entitlements:r})=>e({price:n,entitlements:r})}))(Vc),{isConsumablePrice:x1}=((e,t)=>({isConsumablePrice:r=>r?e(r.config)===t.UsageInArrear:!1}))(qc,qr),{validateLicenseLink:$U}=((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})}}))(cA,Et,Ft),{evaluateCatalogItemIdentity:I1}=(e=>({evaluateCatalogItemIdentity:({item:n,recipe:r=e})=>{let i=[];for(let a of r.components){let o;for(let c of a.paths){o=n;for(let u of c.split("."))o=o!==null&&typeof o=="object"?o[u]:void 0;if(o!=null)break}let s=a.defaultWhen&&i[a.defaultWhen.component]?a.defaultWhen.value:a.default;if(o!=null&&typeof o!="string"&&typeof o!="number")throw new Error("Catalog identity components must be strings or numbers");i.push(o??s)}return i}}))(lA),{removeItems:A1}=(e=>({removeItems:(n,r)=>n.filter(i=>!r.some(a=>e({item:i,filter:a})))}))(pA),{toApiPlanItem:w1}=((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)})}))(fA,hA),{applyLicenses:P1}=(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}}))(bA),{pricesEqual:Uh}=(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)}))(Bc),{itemPricesEqual:C1}=((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)}}))(ho,Bc,yA),{featureOverridesEqual:O1}=((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??{})}))(xA,Mc),{freeTrialsEqual:E1}=(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")}))(wA),{planItemFiltersEqual:T1}=(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)}))(CA),{toUpsertLicense:R1}=(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}:{}})}))(Ih),{getVariantSettingsPatch:GU}=((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}}))(EA,TA),{isOneOffProductV2:WU}=((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)}}))(So,Hr,Ln,yn),{canonicalizeBillingControls:j1}=(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))}}))(Ah),{ProductConfigSchema:k1}=((e,t)=>({ProductConfigSchema:e.object({ignore_past_due:e.boolean().default(!1).meta({description:t})})}))(xe,kA),{shouldApplyVariantUpdates:KU}=(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)}))(DA),{resolveLicenseParentTargets:HU}=((e,t,n)=>({resolveLicenseParentTargets:({contexts:i,targets:a,childPlanId:o})=>{let s=new Map(i.map(l=>[e({planId:l.parent.id,version:l.parent.version}),l])),c=new Set,u=[];for(let l of a){let d=e({planId:l.plan_id,version:l.version});if(c.has(d))throw new t({message:`Parent plan target ${d} was selected more than once.`,code:n.InvalidPropagationTarget,statusCode:400});let p=s.get(d);if(!p)throw new t({message:`Plan ${l.plan_id} v${l.version} does not offer ${o} as a license.`,code:n.InvalidPropagationTarget,statusCode:400});c.add(d),u.push(p)}return u}}))(NA,Et,Ft),{stripeMinorUnitFactor:vo}=((e,t)=>({stripeMinorUnitFactor:r=>{let i=(r??"usd").toLowerCase();return e.has(i)?1:t.has(i)?1e3:100}}))(wh,FA),{entIntervalsSame:D1}=(e=>({entIntervalsSame:({intervalA:n,intervalB:r})=>{let i=e(n.interval,n.intervalCount),a=e(r.interval,r.intervalCount);return i.eq(a)}}))(UA),{intervalsDifferent:N1}=((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}}))(Ht,MA),{allocatedBillingBehaviorAreSame:F1}=(e=>({allocatedBillingBehaviorAreSame:({item1:n,item2:r})=>{let i=e(n),a=e(r);return i===a}}))(LA),{tiersAreSame:U1}=(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))}))(Lc),{itemToPriceOrTiers:M1}=(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}}}))($A),{normalizeBillingControls:B1}=((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)]]:[]}))}}))(HA,mo,QA),{AutoTopupPurchaseLimitSchema:L1}=((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."})})}))(xe,XA),{toFeatureItem:q1}=((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}}}))(yt,fo,Mi,Eh),{toPriceItem:V1}=((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}}}))(Th,hI),{isPayPerUsePrice:Mh}=((e,t)=>({isPayPerUsePrice:({price:r})=>{let i=e(r.config);return i===t.UsageInArrear||i===t.InArrearProrated}}))(qc,qr),{createFeaturesFromItems:$1}=((e,t,n,r,i,a,o,s,c,u)=>({createFeaturesFromItems:({items:d,curFeatures:p,orgId:g,env:m})=>{let h=[];for(let y of d){if(!y.feature_id)continue;let w=p.find(x=>x.id===y.feature_id);if(w){if(e(y.feature_type))continue;if(y.feature_type===t.Static){if(y.feature_type===t.Static&&w.type!==n.Boolean)throw new r({message:`Feature ${y.feature_id} already exists but is not a static feature`,code:i.InvalidRequest,statusCode:400})}else if(y.feature_type!==w.config?.usage_type)throw new r({message:`Feature ${y.feature_id} already exists but is not a ${y.feature_type} feature`,code:i.InvalidRequest,statusCode:400});continue}if(a(y.feature_id),o(y)){let x=s({featureId:y.feature_id,orgId:g,env:m});h.push(x)}else{if(!y.feature_type)throw new r({message:`Feature type is required for ${y.feature_id}. Either 'continuous_use' or 'single_use'`,code:i.InvalidRequest,statusCode:400});let x=c({featureId:y.feature_id,orgId:g,env:m,usageType:y.feature_type===t.ContinuousUse?u.Continuous:u.Single});h.push(x)}}return{allFeatures:[...p,...h],newFeatures:h}}}))($r,Sn,yt,Et,Ft,_I,kh,zA,e1,Mn),{SUPPORTED_SET:G1}=(e=>({SUPPORTED_SET:new Set(e)}))(n1),{CreditDimensionSchema:W1}=((e,t,n,r)=>({CreditDimensionSchema:e.union([t.extend(n),t.extend(r)])}))(xe,o1,hh,Dh),{FeatureMarkupsOverrideSchema:K1}=((e,t,n)=>({FeatureMarkupsOverrideSchema:e.strictObject({default_markup:e.number().min(-100).optional(),provider_markups:t,model_markups:n})}))(xe,s1,EI),{validateCreditRate:Bh}=(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}}))(u1),{validateDimensionsAreSeparable:H1}=((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.`)}}))(l1,jI),{validateCreditMultipliers:Q1}=((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,d1),{FixedPriceConfigSchema:Z1}=((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})}))(xe,yn,Nh,Uc,BI),{currenciesAreCompatible:Y1}=(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}}))(Fh),{creditSchemaItemsAreSame:J1}=(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)}))(g1),{markupOverridesAreSame:X1}=(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)}))(b1),{resolveAllocatedBillingBehavior:z1}=((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}}))(or,Bn,Mh,jh),{itemCanBeProrated:ew}=((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}}))(y1,Sn,Vr),{priceHasPreviewStripeId:tw}=((e,t)=>({priceHasPreviewStripeId:({price:r})=>{let i=r.config;return e.some(a=>t({stripeId:i[a]}))}}))(eA,S1),{buildPlanItemKey:nw}=((e,t)=>({buildPlanItemKey:({item:r,matchPrecision:i=e.FeatureBillingMethodCadence})=>{let a=t({item:r});return i===e.FeatureCadence&&a.splice(1,1),a.join("|")}}))(uA,I1),{itemsEqual:Lh}=((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)}))(C1,SA,vA,O1),{licenseCustomizesAreSame:rw}=((e,t,n,r)=>({licenseCustomizesAreSame:({left:a,right:o})=>{let s=a??{},c=o??{},u={price:!e(s.price,c.price),addItems:!t({left:s.add_items,right:c.add_items,equals:n}),removeItems:!t({left:s.remove_items,right:c.remove_items,equals:r})};return!Object.values(u).some(Boolean)}}))(Uh,PA,Lh,T1),{normalizeVariantSettingValue:iw}=((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}}))(j1,k1,Ah),{intervalsSame:aw}=(e=>({intervalsSame:({intervalA:n,intervalB:r})=>!e({intervalA:n,intervalB:r})}))(N1),{sanitizeItems:ow}=((e,t,n,r)=>({sanitizeItems:({items:a,features:o})=>a.map(s=>{let c=s.tiers?.length===1&&s.tiers[0].additional_currencies?.length?{price:void 0,tiers:s.tiers}:e({item:s}),u={...s,reset_usage_when_enabled:t({item:s,feature:o.find(l=>l.id===s.feature_id)}),...c};return u.config||(u.config={on_increase:n.ProrateImmediately,on_decrease:r.ProrateImmediately}),u})}))(M1,GA,Wr,Li),{compareBillingControls:sw}=(e=>({compareBillingControls:({newBillingControls:n,curBillingControls:r})=>e(n)===e(r)}))(B1),{AutoTopupSchema:cw}=((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."})})}))(xe,L1),{toFeaturePriceItem:uw}=((e,t,n,r,i,a,o,s,c,u,l)=>({toFeaturePriceItem:({ent:p,price:g})=>{let m=g.config,h=e(m.currencies,m.usage_tiers.length),y=m.usage_tiers.map((k,I)=>({amount:k.amount,to:k.to===-1?t:k.to,flat_amount:k.flat_amount,...h?.[I]?.length?{additional_currencies:h[I]}:{}})),w={};return g.proration_config&&(w={...g.proration_config}),n({feature:p.feature})&&r({price:g})&&(w.allocated_billing_behavior=m.allocated_billing_behavior??(i(g)?a.Prorated:a.Arrear)),p.rollover&&(w.rollover=p.rollover),p.expiry_duration&&p.expiry_length!=null&&(w.expiry={duration:p.expiry_duration,length:p.expiry_length}),p.feature_override&&(w.feature_override=p.feature_override),m.threshold_billing&&(w.threshold_billing=m.threshold_billing),{feature_id:p.feature.id,feature_type:p.feature.config?.usage_type||o.SingleUse,included_usage:p.allowance,interval:s({entInterval:p.interval}),interval_count:p.interval_count??1,price_interval:c({billingInterval:m.interval}),price_interval_count:m.interval_count??1,price:null,tiers:y,base_currency:m.base_currency??void 0,billing_units:m.billing_units,tier_behavior:g.tier_behavior??null,entity_feature_id:p.entity_feature_id,pooled:p.pooled??!1,reset_usage_when_enabled:!p.carry_from_previous,usage_model:m.bill_when===u.StartOfPeriod||m.bill_when===u.InAdvance?l.Prepaid:l.PayPerUse,created_at:p.created_at,entitlement_id:p.id,price_id:g.id,price_config:g.config,config:Object.keys(w).length>0?w:void 0,usage_limit:p.usage_limit}}}))(gI,Rc,Rh,Mh,jh,Bn,Sn,Eh,Th,Bi,Vr),{isValidCurrencyCode:$c}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(G1),{CreditSchemaItemBaseSchema:qh}=((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()})}))(xe,a1,W1,OI),{GraduatedCreditSchemaItemSchema:lw}=((e,t)=>({GraduatedCreditSchemaItemSchema:e.extend(t)}))(qh,Dh),{validateCreditDimensionRules:dw}=((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})}}))(Bh,H1,Q1),{pricesAreSame:xo}=((e,t,n,r,i,a,o,s)=>({pricesAreSame:(u,l,d=!1)=>{let p=u.config,g=l.config;if(p.type!==g.type)return!1;if(p.type===e.Fixed){let I=t.parse(p),v=t.parse(g),K={amount:I.amount!==v.amount,interval:I.interval!==v.interval,intervalCount:(I.interval_count??1)!==(v.interval_count??1),baseCurrency:!n({base1:I.base_currency,base2:v.base_currency,currencies1:I.currencies,currencies2:v.currencies}),currencies:!r(I.currencies,v.currencies)};return!Object.values(K).some(Boolean)}let m=i.parse(p),h=i.parse(g),y={shouldProrate:(m.should_prorate??!1)!==(h.should_prorate??!1),allocatedBillingBehavior:a(m)!==a(h),billWhen:m.bill_when!==h.bill_when,billingUnits:(m.billing_units??1)!==(h.billing_units??1),thresholdBilling:m.threshold_billing?.threshold!==h.threshold_billing?.threshold,interval:m.interval!==h.interval,intervalCount:(m.interval_count??1)!==(h.interval_count??1),internalFeatureId:m.internal_feature_id!==h.internal_feature_id,featureId:m.feature_id!==h.feature_id,usageTiers:!o(m.usage_tiers,h.usage_tiers),baseCurrency:!n({base1:m.base_currency,base2:h.base_currency,currencies1:m.currencies,currencies2:h.currencies}),currencies:!r(m.currencies,h.currencies)},w=m.usage_tiers.length<=1&&h.usage_tiers.length<=1,x={onIncrease:u.proration_config?.on_increase!=l.proration_config?.on_increase,onDecrease:u.proration_config?.on_decrease!=l.proration_config?.on_decrease,tierBehavior:!w&&(u.tier_behavior??s.Graduated)!==(l.tier_behavior??s.Graduated)},k=Object.values(y).some(Boolean)||Object.values(x).some(Boolean);return k&&d&&console.log("Prices are different",{configDiffs:y,prorationDiffs:x}),!k}}))(Lr,Z1,m1,Y1,f1,VI,Fh,ho),{creditSchemasAreSame:pw}=(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})}))(J1),{itemToAllocatedBillingBehavior:mw}=((e,t,n,r,i,a,o,s,c)=>({itemToAllocatedBillingBehavior:({item:l,features:d,curPrice:p})=>{if(!(e({item:l,features:d})===t.ContinuousUse&&n(l)&&l.usage_model!==r.Prepaid))return null;let h=i({item:l,curPrice:p});if(h===a.Arrear){if(o(l.config?.on_increase)||o(l.config?.on_decrease))throw new s({message:`on_increase / on_decrease are not supported for allocated arrear billing (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400});if(o(l.config?.rollover))throw new s({message:`rollover is not supported for allocated arrear billing because the balance never resets (feature: ${l.feature_id})`,code:c.InvalidProductItem,statusCode:400})}return h}}))(_1,Sn,Hr,Vr,z1,Bn,or,Et,ZI),{composeMatchKey:qi}=(e=>({composeMatchKey:n=>e({item:n})}))(nw),{applyItems:fw}=((e,t,n,r)=>({applyItems:(a,o)=>{let s=[...a];if(o.remove_items&&(s=e(s,o.remove_items)),o.add_items){let c=new Set;for(let u of s)t(u)&&c.add(n(u));for(let u of o.add_items){let l=n(u);t(u)&&c.has(l)||(s.push(r(u)),t(u)&&c.add(l))}}return s}}))(A1,mA,qi,w1),{dedupeItemsByMatchKey:hw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(qi),{planLicensesAreSame:gw}=(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)}}))(rw),{dedupeItemsByMatchKey:bw}=(e=>({dedupeItemsByMatchKey:n=>{let r=new Set;return n.filter(i=>{let a=e(i);return r.has(a)?!1:(r.add(a),!0)})}}))(qi),{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 u=e.find(l=>c[l]===void 0?!1:t({field:l,value:c[l]})!==t({field:l,value:s[l]}));if(u)throw new n({message:`Cannot update ${u} directly on a variant plan.`,code:r.InvalidPropagationTarget,statusCode:400})}}))(jA,iw,Et,Ft),{findSimilarItem:Gc}=((e,t,n,r,i,a,o,s,c)=>({findSimilarItem:({item:l,items:d})=>e(l)?d.find(p=>e(p)&&p.feature_id===l.feature_id&&p.entity_feature_id==l.entity_feature_id&&t({intervalA:{interval:n({item:p}),intervalCount:r({item:p})},intervalB:{interval:n({item:l}),intervalCount:r({item:l})}})):i(l)?d.find(p=>i(p)&&p.feature_id===l.feature_id&&p.entity_feature_id==l.entity_feature_id&&a({intervalA:{interval:o({item:p}),intervalCount:s({item:p})},intervalB:{interval:o({item:l}),intervalCount:s({item:l})}})&&l.usage_model==p.usage_model):c(l)?d.find(p=>c(p)&&p.price==l.price&&o({item:p})==o({item:l})&&s({item:p})==s({item:l})):null}))(yo,D1,bo,_o,Hr,aw,Ln,Kr,So),{stripAutoTopupCountsForStorage:_w}=(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}))}))(cw),{toProductItem:Vh}=((e,t,n,r)=>({toProductItem:({ent:a,price:o})=>e(o)?t({ent:a}):e(a)?n({price:o}):r({ent:a,price:o})}))(Ht,q1,V1,uw),{CurrencyCodeSchema:$h}=((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')."})}))(xe,$c),{AdditionalCurrencyPriceSchema:yw}=((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."})})}))(xe,$h),{FlatCreditSchemaItemSchema:Sw}=((e,t)=>({FlatCreditSchemaItemSchema:e.extend(t)}))(qh,hh),{validateCreditSystem:vw}=((e,t,n,r,i,a,o,s)=>({validateCreditSystem:(u,l=e.CreditSystem)=>{let d=Array.isArray(u?.schema)?u.schema:[],p=x=>{throw new t({message:x,code:n.InvalidFeature,statusCode:r.BAD_REQUEST})};!i(l)&&d.length===0&&p("At least one metered feature is required for credit system"),i(l)&&d.length>0&&p("AI credit systems are leaf features and cannot define a schema. Model rates live in model_markups.");let g=d.map(x=>x.metered_feature_id),m=Array.from(new Set(g));g.length!==m.length&&p("Credit system contains multiple of the same metered_feature_id");let h={...u,schema:d,usage_type:a.Single},y=h.default_markup;if(y!=null){let x=Number(y);if(Number.isNaN(x)||x<-100)throw new t({message:"Default markup must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});h.default_markup=x}let w=h.provider_markups;if(w!=null)for(let[x,k]of Object.entries(w)){let I=Number(k?.markup);if(!x||Number.isNaN(I)||I<-100)throw new t({message:"Provider markups must be -100 or greater (-100 makes usage free)",code:n.InvalidFeature,statusCode:400});k.markup=I}for(let x of h.schema){if(x.feature_amount!==void 0){let k=Number(x.feature_amount);(!Number.isFinite(k)||k<=0)&&p("Billing units must be greater than zero."),x.feature_amount=k}o({rate:x,invalidCreditSystem:p}),s({schemaItem:x,invalidCreditSystem:p})}return h}}))(yt,Et,Ft,Un,Nc,Mn,Bh,dw),{stripePriceIdForInitializedPrice:Gh}=((e,t,n)=>({stripePriceIdForInitializedPrice:({requestedStripePriceId:i,currentPrice:a,newPrice:o})=>{if(!e(i)&&(!a||i!==t({price:a})||n(a,o)))return i}}))(Ht,MI,xo),{featureOverridesAreSame:Wc}=((e,t)=>({featureOverridesAreSame:({override1:r,override2:i})=>e({schema1:r?.schema,schema2:i?.schema})&&t({markups1:r?.markups,markups2:i?.markups})}))(pw,X1),{applyDiff:Wh}=((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}}}))(dA,fw,gA,P1),{diffPlanLicenses:xw}=((e,t,n,r)=>({diffPlanLicenses:({from:a,to:o,includeAdds:s=!1,includeRemoves:c=!1})=>{let u=new Map((a??[]).map(g=>[g.license_plan_id,g])),l=new Map((o??[]).map(g=>[g.license_plan_id,g])),d=[];for(let g of l.values()){let m=u.get(g.license_plan_id);!m&&!s||m&&e({left:m,right:g})||d.push(t({license:g,clearCustomize:m!=null&&n(m.customize)&&!n(g.customize)}))}let p=c?[...u.keys()].filter(g=>!l.has(g)).map(g=>({license_plan_id:g})):[];return{...d.length>0?{upsert_licenses:d.sort(r)}:{},...p.length>0?{remove_licenses:p.sort(r)}:{}}}}))(gw,R1,Ih,OA),{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)}}}))(Wh,bw),{mapToProductItems:Kh}=((e,t,n,r)=>({mapToProductItems:({prices:a,entitlements:o,features:s})=>{let c=[];a??=[],o??=[];for(let u of o){let l=e({ent:u,prices:a}),d=t({ent:u,price:l});c.push(d)}for(let u of a)n({price:u,entitlements:o})||c.push(t({price:u}));for(let u of c)s.find(d=>d.id===u.feature_id)&&(u.feature_type=r({item:u,features:s}));return c}}))(sh,Vh,Vc,ch),{featureItemsAreSame:Iw}=((e,t,n)=>({featureItemsAreSame:({item1:i,item2:a,logDifferences:o=!1})=>{let s={feature_id:{condition:i.feature_id===a.feature_id,message:`Feature ID different: ${i.feature_id} != ${a.feature_id}`},included_usage:{condition:e(i.included_usage)==e(a.included_usage),message:`Included usage different: ${i.included_usage} != ${a.included_usage}`},interval:{condition:i.interval==a.interval,message:`Interval different: ${i.interval} != ${a.interval}`},interval_count:{condition:(i.interval_count||1)==(a.interval_count||1),message:`Interval count different: ${i.interval_count} != ${a.interval_count}`},entity_feature_id:{condition:i.entity_feature_id==a.entity_feature_id,message:`Entity feature ID different: ${i.entity_feature_id} != ${a.entity_feature_id}`},pooled:{condition:(i.pooled??!1)===(a.pooled??!1),message:`Pooled different: ${i.pooled} != ${a.pooled}`},reset_usage_when_enabled:{condition:(i.reset_usage_when_enabled??!1)===(a.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${i.reset_usage_when_enabled} !== ${a.reset_usage_when_enabled}`},rollover_config:{condition:t({rollover1:i.config?.rollover||void 0,rollover2:a.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(i.config?.rollover)} !== ${JSON.stringify(a.config?.rollover)}`},feature_override:{condition:n({override1:i.config?.feature_override,override2:a.config?.feature_override}),message:`Feature override different: ${JSON.stringify(i.config?.feature_override)} !== ${JSON.stringify(a.config?.feature_override)}`},threshold_billing:{condition:(i.config?.threshold_billing?.threshold??null)===(a.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(i.config?.threshold_billing)} !== ${JSON.stringify(a.config?.threshold_billing)}`}},c=Object.values(s).every(u=>u.condition);return!c&&o&&console.log("Feature items different:",Object.values(s).filter(u=>!u.condition).map(u=>u.message)),c}}))(Ch,Oh,Wc),{featurePriceItemsAreSame:Aw}=((e,t,n,r,i,a,o,s,c,u)=>({featurePriceItemsAreSame:({item1:d,item2:p,logDifferences:g=!1})=>{let m={included_usage:{condition:e(d.included_usage)==e(p.included_usage),message:`Included usage different: ${d.included_usage} != ${p.included_usage}`},usage_limit:{condition:d.usage_limit==p.usage_limit,message:`Usage limit different: ${d.usage_limit} !== ${p.usage_limit}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`},proration_config:{condition:t({config1:d.config||void 0,config2:p.config||void 0}),message:`Proration config different: ${JSON.stringify(d.config)} !== ${JSON.stringify(p.config)}`},allocated_billing_behavior:{condition:n({item1:d,item2:p}),message:`Allocated billing behavior different: ${d.config?.allocated_billing_behavior} !== ${p.config?.allocated_billing_behavior}`},rollover_config:{condition:r({rollover1:d.config?.rollover||void 0,rollover2:p.config?.rollover||void 0}),message:`Rollover config different: ${JSON.stringify(d.config?.rollover)} !== ${JSON.stringify(p.config?.rollover)}`},feature_override:{condition:i({override1:d.config?.feature_override,override2:p.config?.feature_override}),message:`Feature override different: ${JSON.stringify(d.config?.feature_override)} !== ${JSON.stringify(p.config?.feature_override)}`},threshold_billing:{condition:(d.config?.threshold_billing?.threshold??null)===(p.config?.threshold_billing?.threshold??null),message:`Threshold billing different: ${JSON.stringify(d.config?.threshold_billing)} !== ${JSON.stringify(p.config?.threshold_billing)}`},entity_feature_id:{condition:d.entity_feature_id==p.entity_feature_id,message:`Entity feature ID different: ${d.entity_feature_id} != ${p.entity_feature_id}`},pooled:{condition:(d.pooled??!1)===(p.pooled??!1),message:`Pooled different: ${d.pooled} != ${p.pooled}`}},h={feature_id:{condition:d.feature_id===p.feature_id,message:`Feature ID different: ${d.feature_id} != ${p.feature_id}`},interval:{condition:a({item:d})==a({item:p}),message:`Billing interval different: ${a({item:d})} != ${a({item:p})}`},interval_count:{condition:o({item:d})==o({item:p}),message:`Billing interval count different: ${o({item:d})} != ${o({item:p})}`},usage_model:{condition:d.usage_model===p.usage_model,message:`Usage model different: ${d.usage_model} != ${p.usage_model}`},pricing:{condition:s(c(d),c(p)),message:`Pricing different: ${JSON.stringify(c(d))} != ${JSON.stringify(c(p))}`},additional_currencies:{condition:u(d.additional_currencies,p.additional_currencies),message:"Additional currencies different"},tier_behavior:{condition:(c(d)?.length??0)<=1&&(c(p)?.length??0)<=1?!0:d.tier_behavior==p.tier_behavior,message:`Tiers type different: ${d.tier_behavior} != ${p.tier_behavior}`},billing_units:{condition:d.billing_units==p.billing_units,message:`Billing units different: ${d.billing_units} !== ${p.billing_units}`},reset_usage_when_enabled:{condition:(d.reset_usage_when_enabled??!1)===(p.reset_usage_when_enabled??!1),message:`Reset usage when enabled different: ${d.reset_usage_when_enabled} !== ${p.reset_usage_when_enabled}`}},y=Object.values(h).every(x=>x.condition)&&Object.values(m).every(x=>x.condition),w=Object.values(h).some(x=>!x.condition);return!y&&g&&console.log("Feature price items different:",Object.values(m).filter(x=>!x.condition).map(x=>x.message),Object.values(h).filter(x=>!x.condition).map(x=>x.message)),{same:y,pricesChanged:w}}}))(Ch,BA,F1,Oh,Wc,Ln,Kr,U1,qA,Lc),{pickBillingControlColumns:ww}=((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}}))(mo,_w),{mapToProductV2:YU}=((e,t,n,r,i)=>({mapToProductV2:({product:o,features:s})=>{let c=[];for(let l of o.entitlements){let d=e({ent:l,prices:o.prices});c.push(t({ent:l,price:d}))}for(let l of o.prices)n({price:l,entitlements:o.entitlements})||c.push(t({price:l}));s||(s=o.entitlements.map(l=>l.feature));for(let l of c)l.feature_type=r({item:l,features:s});return{internal_id:o.internal_id,id:o.id,name:o.name,description:o.description??null,is_add_on:o.is_add_on,is_default:o.is_default,version:o.version,version_slug:o.version_slug??null,active:o.active??!1,group:o.group||null,free_trial:o.free_trial,created_at:o.created_at,env:o.env,items:c,stripe_id:o.processor?.id||null,archived:o.archived||!1,config:o.config??void 0,billing_controls:i(o),metadata:o.metadata??{}}}}))(sh,Vh,Vc,ch,uh),{AdditionalCurrencyTierSchema:Pw}=((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"]})}))(xe,$h),{AdditionalCurrencyPriceArraySchema:Cw}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(xe,yw,ph,mh),{CreditSchemaItemSchema:Ow}=((e,t,n)=>({CreditSchemaItemSchema:e.union([t,n])}))(xe,Sw,lw),{validateItemFeatureOverride:Ew}=((e,t,n,r,i,a,o,s,c)=>({validateItemFeatureOverride:({item:l,feature:d,features:p})=>{let g=l.config?.feature_override;if(!g)return;let m=y=>{throw new e({message:`${y} (feature: ${l.feature_id})`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})};if(!(d&&r(d.type))){m("feature_override is only supported on credit system items");return}if(g.schema&&d.type!==i.CreditSystem&&m("feature_override.credit_schema is not supported on AI credit system items"),g.markups&&!a(d.type)&&m("feature_override.markups is only supported on AI credit system items"),!g.schema)return;let h={schema:g.schema,usage_type:o.Single};s(h,d.type),c({config:h,allFeatures:p});for(let y of g.schema)if(!p.find(x=>x.id===y.metered_feature_id))throw new e({message:`feature_override on ${d.id} references unknown feature ${y.metered_feature_id}`,code:t.InvalidProductItem,statusCode:n.BAD_REQUEST})}}))(Et,Ft,Un,c1,yt,Nc,Mn,vw,FI),{toPrice:Tw}=((e,t,n,r,i,a,o)=>({toPrice:({item:c,orgId:u,internalProductId:l,isCustom:d,newVersion:p,curPrice:g})=>{let m={type:e.Fixed,amount:t(c.price)?c.price:c.tiers[0].amount,interval:n({item:c}),interval_count:r({item:c}),stripe_product_id:null,stripe_price_id:void 0,feature_id:null,internal_feature_id:null},h=i(c.additional_currencies);h&&(m.currencies=h);let y=c.base_currency??(h?g?.config?.base_currency:void 0);y&&(m.base_currency=y);let w={id:c.price_id||g?.id||a("pr"),created_at:c.created_at||Date.now(),org_id:u,internal_product_id:l,is_custom:d,config:m,proration_config:null};return(d||p)&&(w={...w,id:a("pr"),created_at:Date.now()}),m.stripe_price_id=o({requestedStripePriceId:c.stripe_price_id,currentPrice:g,newPrice:w}),{price:w,ent:null}}}))(Lr,Gr,Ln,Kr,p1,Mr,Gh),{entsAreSame:Kc}=((e,t,n,r,i,a,o)=>({entsAreSame:(c,u)=>{if(c.internal_feature_id!==u.internal_feature_id||e(c)!==e(u))return!1;let l=e(c),d={interval:t(c)!==t(u),intervalCount:n(c)!==n(u),allowance:!l&&c.allowance!=u.allowance,carryFromPrevious:(c.carry_from_previous??!1)!==(u.carry_from_previous??!1),entityFeatureId:r(c.entity_feature_id)!==r(u.entity_feature_id),pooled:(c.pooled??!1)!==(u.pooled??!1),usageLimit:c.usage_limit!=u.usage_limit,rollover:!i({rollover1:c.rollover,rollover2:u.rollover}),featureOverride:!a({override1:c.feature_override,override2:u.feature_override}),expiry:!o(c,u)};return!Object.values(d).some(Boolean)}}))($I,Sh,GI,WI,KI,Wc,QI),{toFeatureAndPrice:Rw}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m,h,y,w,x,k,I,v,K,$,we,Te,oe,V)=>({toFeatureAndPrice:({item:Z,orgId:rt,internalFeatureId:de,internalProductId:ie,isCustom:Ut,curPrice:We,curEnt:Mt,newVersion:vn,features:Qt})=>{let Jh=e({item:Z,feature:Qt.find(vt=>vt.id===Z.feature_id)}),Io=t({item:Z,features:Qt,curPrice:We}),zc=Io===n.Arrear,sr={id:Z.entitlement_id||Mt?.id||r("ent"),org_id:rt,created_at:Z.created_at||Date.now(),is_custom:Ut,internal_product_id:ie,internal_feature_id:de,feature_id:Z.feature_id,allowance:Z.included_usage||0,allowance_type:i.Fixed,interval:a({item:Z}),interval_count:o({item:Z}),carry_from_previous:!Jh,entity_feature_id:Z.entity_feature_id,pooled:Z.pooled??!1,usage_limit:Z.usage_limit||null,rollover:Z.config?.rollover,expiry_duration:Z.config?.expiry?.duration,expiry_length:Z.config?.expiry?.length,feature_override:Z.config?.feature_override};(!Mt||Ut&&!s(Mt,sr)||vn)&&(sr={...sr,id:r("ent"),created_at:Date.now()});let Xh=a({item:Z}),Qr={type:c.Usage,bill_when:Z.usage_model===u.Prepaid?l.StartOfPeriod:l.EndOfPeriod,billing_units:Z.billing_units||1,...Z.config?.threshold_billing?{threshold_billing:Z.config.threshold_billing}:{},should_prorate:Xh===d.Lifetime&&!zc,...Io?{allocated_billing_behavior:Io}:{},internal_feature_id:de,feature_id:Z.feature_id,usage_tiers:p(Z.price)?[{amount:Z.price,to:g}]:Z.tiers?.map(vt=>({to:vt.to,amount:vt.amount??0,...vt.flat_amount!=null?{flat_amount:vt.flat_amount}:{}})),interval:m({item:Z}),interval_count:h({item:Z}),stripe_price_id:void 0},eu=y({baseTiers:Qr.usage_tiers,itemTiers:Z.tiers,flatCurrencies:Z.additional_currencies});eu&&(Qr.currencies=eu,Qr.base_currency=Z.base_currency??We?.config?.base_currency??void 0);let zh=w({item:Z,features:Qt})&&!zc,tu=null;if(zh){let vt=Z.config?.on_increase||x.ProrateImmediately,qn=Z.config?.on_decrease||k.Prorate;(I(qn)||qn===k.Prorate)&&(qn=vt===x.ProrateImmediately||vt===x.BillImmediately?k.ProrateImmediately:k.ProrateNextCycle),tu={on_increase:vt,on_decrease:qn}}let pn={id:Z.price_id||We?.id||r("pr"),created_at:Z.created_at||Date.now(),org_id:rt,internal_product_id:ie,is_custom:Ut,config:Qr,entitlement_id:sr.id,proration_config:tu,tier_behavior:Z.tier_behavior??null},nu=v(pn.config);if((nu===K.UsageInArrear||nu===K.InArrearProrated)&&pn.config.interval===$.OneOff)throw new we({message:`Usage prices cannot be one-off if not set to prepaid (feature: ${Z.feature_id})`,code:Te.InvalidPrice,statusCode:400});let eg=We&&!oe(We,pn,!0)||Mt&&!s(Mt,sr);if(We&&(eg||vn)){let vt=pn.config,qn=We.config;vt.stripe_meter_id=qn.stripe_meter_id,vt.stripe_product_id=qn.stripe_product_id,pn.config=vt}return(Ut||vn)&&(pn={...pn,id:r("pr"),created_at:Date.now()}),Qr.stripe_price_id=V({requestedStripePriceId:Z.stripe_price_id,currentPrice:We,newPrice:pn}),{price:pn,ent:sr}}}))(yh,mw,Bn,Mr,fo,bo,_o,Kc,Lr,Vr,Bi,Br,Gr,Rc,Ln,Kr,YI,ew,Wr,Li,XI,zI,qr,yn,Et,Ft,xo,Gh),{getPriceStripeReuseLevel:jw}=((e,t,n,r,i,a)=>({getPriceStripeReuseLevel:({newPrice:s,candidatePrice:c,newEntitlements:u,candidateEntitlements:l})=>{if(e({price:c})||s.config?.type!==c.config?.type)return"none";if(t(c,s,!1)){if(s.config?.type!==n.Usage)return"full";let h=r({price:s,entitlements:u}),y=r({price:c,entitlements:l});if(!h&&!y)return"full";if(!h||!y)return"none";if(i(y,h))return"full"}if(s.config?.type!==n.Usage)return"none";let d=s.config,p=c.config;if(d.feature_id!==p.feature_id)return"none";let g=r({price:s,entitlements:u}),m=r({price:c,entitlements:l});return!g&&!m?"stripeProductOnly":!g||!m||a(g.entity_feature_id)!==a(m.entity_feature_id)?"none":"stripeProductOnly"}}))(tw,xo,Lr,v1,Kc,rA),{applyLicenseCustomizeToBasePlan:JU}=((e,t,n)=>({applyLicenseCustomizeToBasePlan:({basePlan:i,customize:a})=>{let o=new Set((a.add_items??[]).map(u=>e(u))),s={...i,items:i.items.filter(u=>!o.has(e(u)))},c=t({base:s,diff:a});return{...s,...c,items:n(c.items)}}}))(qi,Wh,hw),{diffPlanV1:kw}=((e,t,n,r,i,a,o,s,c)=>({diffPlanV1:({from:l,to:d,includeAdds:p=!1,includeRemoves:g=!1,filterPrecision:m=e.Identity})=>{let h={};t(l.price,d.price)||(h.price=d.price===null?null:n(d.price));let y=new Map(l.items.map(I=>[r(I),I])),w=new Map(d.items.map(I=>[r(I),I])),x=[];for(let I of d.items){let v=y.get(r(I));(!v||!i(v,I))&&x.push(a(I))}x.length>0&&(h.add_items=x);let k=[];for(let I of l.items){let v=w.get(r(I));(!v||!i(I,v))&&k.push(o({item:I,filterPrecision:m}))}if(k.length>0&&(h.remove_items=k),!s(l.free_trial,d.free_trial))if(d.free_trial==null)h.free_trial=null;else{let{on_end:I,...v}=d.free_trial;h.free_trial=I==null?v:{...v,on_end:I}}return Object.assign(h,c({from:l.licenses,to:d.licenses,includeAdds:p,includeRemoves:g})),h}}))(xh,Uh,_A,qi,Lh,IA,AA,E1,xw),{currentItemsOf:Hh}=(e=>({currentItemsOf:({currentFullProduct:n,features:r})=>e({prices:n.prices,entitlements:n.entitlements,features:r})}))(Kh),{itemsAreSame:Qh}=((e,t,n,r,i,a,o,s)=>({itemsAreSame:({item1:u,item2:l,features:d,logDifferences:p=!1})=>{let g=!1,m=!1;if(e(u)){if(!e(l))return{same:!1,pricesChanged:!0};g=t({item1:u,item2:l,logDifferences:p}),m=!1}if(n(u)){if(!n(l))return{same:!1,pricesChanged:!0};let{same:h,pricesChanged:y}=r({item1:u,item2:l,logDifferences:p});g=h,i({item:u,features:d||[]})?.config?.usage_type===a.Continuous?m=!0:m=y}return o(u)&&(g=s({item1:u,item2:l,logDifferences:p}),g||(m=!0)),{same:g,pricesChanged:!g&&m}}}))(yo,Iw,Hr,Aw,vh,Mn,So,VA),{productsAreSame:XU}=((e,t,n,r,i,a,o,s,c,u,l,d,p)=>({productsAreSame:({newProductV1:m,newProductV2:h,curProductV1:y,curProductV2:w,features:x})=>{if(!m&&!h)throw new Error("productsAreSame error: product1 not provided");if(!y&&!w)throw new Error("productsAreSame error: product2 not provided");let k=h?.items||e({prices:m?.prices||[],entitlements:m?.entitlements||[],features:x}),I=w?.items||e({prices:y?.prices||[],entitlements:y?.entitlements||[],features:x});k=t({items:k,features:x}),I=t({items:I,features:x});let v=!0,K=!1,$=!0,we=!0,Te=!0,oe=[],V=[];$=n({newProductV2:h,curProductV2:w}),we=r({newConfig:h?.config,curConfig:w?.config}),Te=i({newBillingControls:h?.billing_controls??(m?a(m):void 0),curBillingControls:w?.billing_controls??(y?a(y):void 0)});let Fe=o({newMetadata:h?.metadata,curMetadata:w?.metadata});k.length!==I.length&&(v=!1),k.length!==I.length&&(v=!1);for(let We of k){let Mt=s({item:We,items:I});if(!Mt){(c(We)||u(We))&&(K=!0),v=!1,oe.push(We);continue}let{same:vn,pricesChanged:Qt}=l({item1:We,item2:Mt,features:x,logDifferences:!1});vn||(v=!1,oe.push(We)),Qt&&(K=!0)}for(let We of I)s({item:We,items:k})||(v=!1,(c(We)||u(We))&&(K=!0),V.push(We));let Z=y?.free_trial||w?.free_trial,rt=m?.free_trial||h?.free_trial,de=d({ft1:Z,ft2:rt}),ie=p({curProduct:w||y,newProduct:h||m});return{itemsSame:v,freeTrialsSame:de,onlyEntsChanged:!K,newItems:oe,removedItems:V,detailsSame:$,optionsSame:ie,configSame:we,billingControlsSame:Te,metadataSame:Fe,same:v&&$&&de&&we&&Fe&&Te}}}))(Kh,ow,WA,KA,sw,uh,ZA,Gc,Hr,So,Qh,YA,JA),{constructProduct:zU}=((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??{}})}))(Mr,ww),{AdditionalCurrencyTierArraySchema:Dw}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(xe,Pw,ph,mh),{FeatureConfigOverrideSchema:Nw}=((e,t,n)=>({FeatureConfigOverrideSchema:e.strictObject({schema:e.array(t).optional(),markups:n.optional()})}))(xe,Ow,K1),{itemToPriceAndEnt:Fw}=((e,t,n,r,i,a,o,s,c,u)=>({itemToPriceAndEnt:({item:d,orgId:p,internalProductId:g,feature:m,curPrice:h,curEnt:y,isCustom:w,newVersion:x,features:k})=>{let I=null,v=null,K=null,$=null,we=null,Te=null;if(e(d)){let{price:oe}=t({item:d,orgId:p,internalProductId:g,isCustom:w,newVersion:x,curPrice:h});!h||x?I=oe:n(h,oe,!0)?we=h:K=oe}else if(r(d)){if(!m)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let oe=m?.type===o.Boolean,{ent:V}=s({item:d,orgId:p,internalFeatureId:m.internal_id,internalProductId:g,isCustom:w,newVersion:x,feature:m,curEnt:y});!y||x?v=V:c(y,V)?Te=y:$=V}else{if(!m)throw new i({message:`Feature ${d.feature_id} not found`,code:a.InvalidRequest});let{price:oe,ent:V}=u({item:d,orgId:p,internalFeatureId:m.internal_id,internalProductId:g,isCustom:w,curPrice:h,curEnt:y,newVersion:x,features:k}),Fe=y&&c(y,V);!h||x?I=oe:!Fe||!n(h,oe,!1)?K=oe:we=h,!y||x?v=V:Fe?Te=y:$=V}return{newPrice:I,newEnt:v,updatedPrice:K,updatedEnt:$,samePrice:we,sameEnt:Te}}}))(Fc,Tw,xo,go,Et,Ft,yt,h1,Kc,Rw),{copyStripeResourcesToMatchingPrice:Uw}=((e,t,n,r,i)=>({copyStripeResourcesToMatchingPrice:({targetPrice:o,candidatePrices:s,targetEntitlements:c,candidateEntitlements:u})=>{let l=s.map(w=>({candidatePrice:w,level:e({newPrice:o,candidatePrice:w,newEntitlements:c,candidateEntitlements:u})})),d=l.find(w=>w.level==="full"),g=(d??l.find(w=>w.level==="stripeProductOnly"))?.candidatePrice,m=d?.candidatePrice,h=o.config,y=[];if(g){let w=g.config;for(let x of t)x==="stripe_meter_id"&&(!n(o)||!n(g))||r({fromConfig:w,toConfig:h,field:x})&&y.push(x)}if(m){let w=m.config;for(let x of i)t.includes(x)||r({fromConfig:w,toConfig:h,field:x})&&y.push(x)}return{copiedFields:y}}}))(jw,iA,x1,aA,oA),{getApiPlanDiff:eM}=(e=>({getApiPlanDiff:({from:n,to:r})=>e({from:n,to:r})}))(kw),{backfillExistingItemIds:Mw}=((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})}}))(Hh,Gc),{PriceTierSchema:Bw}=((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}))}))(xe,Rc,Dw),{ProductItemConfigSchema:Lw}=((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()})}))(xe,Bn,Wr,Li,r1,i1,Nw),{carryForwardStripeResources:qw}=(e=>({carryForwardStripeResources:({targetPrices:n,targetEntitlements:r,candidatePrices:i,candidateEntitlements:a})=>{for(let o of n)e({targetPrice:o,candidatePrices:i,targetEntitlements:r,candidateEntitlements:a})}}))(Uw),{resolveInPlaceEdit:tM}=((e,t,n,r)=>({resolveInPlaceEdit:async({db:a,items:o,currentFullProduct:s,features:c})=>{let u=e({items:o,currentFullProduct:s,features:c}),l=t({currentFullProduct:s,features:c}),d=[],p=[];for(let h of l){let y=n({item:h,items:u}),w=!y,x=y&&!r({item1:y,item2:h,features:c}).same;(w||x)&&(h.entitlement_id&&d.push(h.entitlement_id),h.price_id&&p.push(h.price_id))}let g=new Set([...d,...p]),m=u.map(h=>{let y=h.entitlement_id&&g.has(h.entitlement_id),w=h.price_id&&g.has(h.price_id);return y||w?{...h,entitlement_id:void 0,price_id:void 0}:h});return{retiredEntitlementIds:d,retiredPriceIds:p,items:m,curPrices:s.prices.filter(h=>!g.has(h.id)),curEnts:s.entitlements.filter(h=>!g.has(h.id))}}}))(Mw,Hh,Gc,Qh),{ProductItemSchema:Vw}=((e,t,n,r,i,a,o,s,c,u,l)=>({ProductItemSchema:e.object({type:e.enum(t).nullish().meta({description:"The type of the product item."}),feature_id:e.string().nullish().meta({description:"The feature ID of the product item. Should be null for fixed price items."}),feature_type:e.enum(n).nullish().meta({internal:!0}),feature:r.nullish().meta({internal:!0}),included_usage:e.union([e.number(),e.literal(i)]).nullish().meta({description:"The amount of usage included for this feature (per interval)."}),interval:e.preprocess(p=>{if(p==="")throw new Error("Interval cannot be empty.");return p},e.enum(a).nullish()).meta({description:"The reset or billing interval of the product item. If null, feature will have no reset date, and if there's a price, it will be billed one-off."}),interval_count:e.number().nullish().meta({description:"Interval count of the feature."}),entity_feature_id:e.string().nullish().meta({description:"The feature ID of the entity (like seats) to track sub-balances for."}),pooled:e.boolean().default(!1).optional().meta({description:"Whether entity-level grants contribute to a shared customer balance."}),usage_model:e.enum(o).nullish().meta({description:"Whether the feature should be prepaid upfront or billed for how much they use end of billing period."}),price:e.number().nullish().meta({description:"The price of the product item. Should be null if tiered pricing is set."}),tiers:e.array(s).nullish().meta({description:"Tiered pricing for the product item. Not applicable for fixed price items."}),base_currency:e.string().nullish().meta({internal:!0}),additional_currencies:c.nullish().meta({description:"Amounts in additional currencies for a flat-priced item. Tiered items carry per-currency amounts on each tier."}),billing_units:e.number().nullish().meta({description:"The billing units of the product item (eg $1 for 30 credits)."}),tier_behavior:e.enum(u).nullish().meta({description:"The type of tiered pricing: graduated or volume-based."}),reset_usage_when_enabled:e.boolean().nullish().meta({description:"Whether the usage should be reset when the product is enabled."}),display:e.object({primary_text:e.string(),secondary_text:e.string().nullish()}).nullish().meta({internal:!0}),usage_limit:e.number().nullish().meta({internal:!0}),config:l.nullish().meta({internal:!0}),created_at:e.number().nullish().meta({internal:!0}),entitlement_id:e.string().nullish().meta({internal:!0}),price_id:e.string().nullish().meta({internal:!0}),stripe_price_id:e.string().nullish().meta({internal:!0}),stripe_prepaid_price_v2_id:e.string().nullish().meta({internal:!0}),price_interval:e.enum(a).nullish().meta({internal:!0}),price_interval_count:e.number().nullish().meta({internal:!0}),price_config:e.any().nullish().meta({internal:!0}),_uid:e.string().nullish().meta({internal:!0})})}))(xe,SI,Sn,t1,Mi,jc,Vr,Bw,Cw,ho,Lw),{validateProductItem:$w}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m,h,y,w,x,k)=>({validateProductItem:({item:v,features:K,multiCurrencyEnabled:$,validateRollover:we})=>{v=e.parse(v);let Te=K.find(de=>de.id===v.feature_id);if(t(v.feature_id)&&t(v.price)&&t(v.tiers))throw new n({message:"Either 'feature_id', 'price', or both should be set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let oe=v.pooled&&Te?.type===a.Boolean,V=o(v)||s(v.included_usage)&&v.included_usage!==0||s(v.interval)||s(v.config?.rollover);if(oe&&V)throw new n({message:"Pooled boolean items cannot include balance or pricing fields",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(c({item:v,feature:Te,features:K}),o(v)&&v.included_usage===u)throw new n({message:"Unlimited items cannot include pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(v.pooled&&o(v)&&v.usage_model===l.PayPerUse)throw new n({message:"Pooled items cannot use usage-based pricing",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(v.price)&&s(v.tiers))throw new n({message:"Either 'price' or 'tiers' should be set, not both",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let Fe=(v.additional_currencies?.length??0)>0||(v.tiers?.some(de=>(de.additional_currencies?.length??0)>0)??!1);if(Fe&&!$)throw new n({message:"Multi-currency is not enabled for this organization",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(Fe&&t(v.base_currency))throw new n({message:"'base_currency' is required when 'additional_currencies' are set",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if((v.additional_currencies?.length??0)>0){if(s(v.tiers))throw new n({message:"Tiered items carry 'additional_currencies' on each tier, not at the item level",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(s(v.price)&&v.price<=0)throw new n({message:"'additional_currencies' require a non-zero 'price' \u2014 a plan that is free in the base currency is free in every currency",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST})}if(d(v)&&v.price&&v.price.toString().split(".")[1]?.length>2)throw new n({message:"One off prices can have at most 2 decimal places",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(v)||p(v)){if(typeof v.included_usage!="number"&&v.included_usage!==u&&s(v.included_usage))throw new n({message:`Included usage for feature ${v.feature_id} must be a number or '${u}'`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(t(v.included_usage)&&(v.included_usage=0),typeof v.included_usage=="number"&&v.included_usage<0)throw new n({message:"Included usage must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(v)||d(v)){let de=g({item:v});if(String(de)===m.Day||String(de)===m.Minute||String(de)===m.Hour)throw new n({message:"Price can't have day, minute or hour interval",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(o(v)&&t(v.usage_model))throw new n({message:`Usage model is required for priced features. Please select one for the feature ${v.feature_id}`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(o(v)&&v.tiers){if(v.included_usage===u)throw new n({message:`Included usage can't be '${u}' for tiered prices`,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.billing_units&&v.billing_units<=0)throw new n({message:"Billing units must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.tier_behavior===h.VolumeBased&&v.tiers.length>1&&v.usage_model!==l.Prepaid)throw new n({message:"Volume-based pricing is only supported for prepaid items",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.tiers.some(ie=>ie.flat_amount!=null&&ie.flat_amount>0)){if(v.tier_behavior!==h.VolumeBased)throw new n({message:"flat_amount on tiers is only supported for volume-based pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.tiers.length<=1)throw new n({message:"flat_amount is not supported on single-tier pricing",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(v.tiers.some(ie=>ie.flat_amount!=null&&ie.flat_amount<0))throw new n({message:"flat_amount must be 0 or greater",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}if(v.usage_model===l.Prepaid&&v.config?.on_increase===y.BillImmediately)throw new n({message:"Bill immediately is not supported for prepaid just yet, contact us at hey@useautumn.com if you're interested!",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(v.config?.expiry&&Te&&(Te.type===a.Boolean||w({feature:Te})))throw new n({message:`expiry is only supported on consumable features (feature: ${v.feature_id})`,code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});if(!v.config?.rollover)return;let Z=v.config.rollover;if(Z.duration===x.Forever&&(Z.length=0),!we)return;if(v.included_usage===u)throw new n({message:"Unlimited items cannot have rollover",code:r.InvalidProductItem,statusCode:i.BAD_REQUEST});let rt=k({rollover:Z});if(rt)throw new n({message:rt,code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(Z.duration===x.Month&&(typeof Z.length!="number"||Z.length<0))throw new n({message:"Rollover length must be a positive number for monthly durations",code:r.InvalidInputs,statusCode:i.BAD_REQUEST});if(s(v.usage_limit)&&v.usage_limit<=0)throw new n({message:"Usage limit must be greater than 0",code:r.InvalidInputs,statusCode:i.BAD_REQUEST})}}))(Vw,Ht,Et,Ft,Un,yt,Dc,or,Ew,Mi,Vr,Fc,go,Ln,jc,ho,Wr,Rh,kc,UI),{validateProductItems:Gw}=((e,t,n,r,i,a,o,s,c,u,l,d,p,g,m)=>({validateProductItems:({newItems:y,features:w,orgId:x,env:k,multiCurrencyEnabled:I,validateRollover:v=!0})=>{let{allFeatures:K,newFeatures:$}=e({items:y,curFeatures:w,orgId:x,env:k});w=K;for(let oe=0;oe<y.length;oe++){t({item:y[oe],features:w,multiCurrencyEnabled:I,validateRollover:v});let V=w.find(Fe=>Fe.id===y[oe].feature_id);V&&V.type===n.Metered&&(y[oe].feature_type=V.config?.usage_type)}for(let oe=0;oe<y.length;oe++){let V=y[oe],Fe=r({item:V}),Z=i({item:V});if(a(V)&&y.find((ie,Ut)=>ie.feature_id===V.feature_id&&Ut!==oe&&V.entity_feature_id===ie.entity_feature_id))throw new o({message:`Feature ${V.feature_id} is duplicated`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});let rt=y.find((de,ie)=>de.feature_id===V.feature_id&&ie!==oe&&r({item:de})===Fe&&i({item:de})===Z&&de.entity_feature_id===V.entity_feature_id);if(rt){if(u(rt)&&u(V))throw new 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===rt?.usage_model)throw new o({message:`You're trying to add the same feature (${V.feature_id}), with the same reset interval. You should either change the reset interval of one of the items, or make one of them a prepaid quantity`,code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(l(V)&&y.find((ie,Ut)=>d({item:ie})===d({item:V})&&p({item:ie})===p({item:V})&&Ut!==oe))throw new o({message:"Can't have two fixed prices with the same interval",code:s.InvalidInputs,statusCode:c.BAD_REQUEST})}}let we=y.some(oe=>(l(oe)||g(oe))&&String(d({item:oe}))===m.Week),Te=y.some(oe=>(l(oe)||g(oe))&&String(d({item:oe}))===m.Month);if(we&&Te)throw new o({message:"Can't have both weekly and monthly price items in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});if(y.filter(l).length>1)throw new o({message:"Can't have more than one price item in the same product",code:s.InvalidInputs,statusCode:c.BAD_REQUEST});return{allFeatures:K,newFeatures:$}}}))($1,$w,yt,bo,_o,kh,Et,Ft,Un,go,Fc,Ln,Kr,Dc,jc),{handleNewProductItems:nM}=((e,t,n,r,i)=>({handleNewProductItems:async({db:o,curPrices:s,curEnts:c,newItems:u,features:l,product:d,logger:p,isCustom:g,newVersion:m,saveToDb:h=!0,multiCurrencyEnabled:y})=>{if(!u)return{prices:[],entitlements:[],customPrices:[],customEnts:[],features:l};let{allFeatures:w,newFeatures:x}=e({newItems:u,features:l,orgId:d.org_id,env:d.env,multiCurrencyEnabled:y,validateRollover:!g});l=w;let k=[],I=[],v=[],K=[],$=s.filter(V=>{let Fe=u.find(Z=>Z.price_id===V.id);return Fe?t(Fe):!0}),we=c.filter(V=>!u.some(Fe=>Fe.entitlement_id===V.id)),Te=[],oe=[];for(let V of u){let Fe=l.find(Qt=>Qt.id===V.feature_id),Z=c.find(Qt=>Qt.id===V.entitlement_id),rt=s.find(Qt=>Qt.id===V.price_id),{newPrice:de,newEnt:ie,updatedPrice:Ut,updatedEnt:We,samePrice:Mt,sameEnt:vn}=n({item:V,orgId:d.org_id,internalProductId:d.internal_id,feature:Fe,curPrice:rt,curEnt:Z,isCustom:g,newVersion:m,features:l});de&&k.push(de),ie&&I.push(ie),Ut&&v.push(Ut),We&&K.push(We),Mt&&Te.push(Mt),vn&&oe.push(vn)}return r({targetPrices:[...k,...v],targetEntitlements:[...I,...K,...oe],candidatePrices:s,candidateEntitlements:c}),(g||m)&&h?{...i({newPrices:k,newEnts:I,updatedPrices:v,updatedEnts:K,samePrices:Te,sameEnts:oe,features:l}),samePrices:Te,sameEnts:oe,newFeatures:x,retiredPriceIds:$.map(V=>V.id),retiredEntitlementIds:we.map(V=>V.id)}:{prices:[...k,...v],entitlements:[...I,...K].map(V=>({...V,feature:l.find(Fe=>Fe.id===V.feature_id)})),customPrices:[],customEnts:[],features:l,samePrices:Te,sameEnts:oe,newFeatures:x,retiredPriceIds:$.map(V=>V.id),retiredEntitlementIds:we.map(V=>V.id)}}}))(Gw,yo,Fw,qw,sA);var Ww=tn.clone({precision:40});function Hc(e){if(!$c(e))throw new Error("A supported explicit currency is required");return e.toLowerCase()}function Qc(e){let t=new Ww(e);if(!t.isFinite())throw new Error("Amount must be finite");return t}function oM(e,t){let n=Hc(t),i=Qc(e).toDecimalPlaces(Ph(n),tn.ROUND_HALF_CEIL).mul(vo(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 sM(e,t){let n=Hc(t),r=Qc(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(vo(n)).toString()}function cM(e,t){let n=Qc(e).mul(vo(Hc(t)));if(n.isNegative())throw new Error("Usage unit price must be nonnegative");if(n.decimalPlaces()>12||n.abs().gt(Number.MAX_SAFE_INTEGER))throw new Error("Usage unit amount cannot be represented exactly by the provider");return n.toFixed()}import{z as fe}from"zod";var Kw={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Zc=fe.string().regex(/^[a-f0-9]{64}$/),Yc=fe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Hw=je.extend({environmentId:fe.uuid()}),Zh=fe.strictObject({features:fe.array(fe.string()).max(500),experiments:fe.record(fe.uuid(),fe.array(fe.string()).max(20)),savedGroups:fe.array(fe.string()).max(1e3)}),Qw=fe.strictObject({kind:fe.enum(["funnel","gb_features","gb_page_experiments"]),formatVersion:fe.number().int().positive(),url:fe.string().min(1).max(2048),sha256:Zc,byteLength:fe.number().int().positive().max(Kw.maxArtifactBytes),generation:Zc.optional()}),Zw=fe.strictObject({state:fe.enum(["active","paused","archived"]),controlRevision:Yc,evaluationMode:fe.enum(["local","remote"]),evaluationRevision:Yc,currentVersionId:fe.uuid(),versions:fe.record(fe.uuid(),fe.strictObject({artifact:fe.string(),dependencies:Zh,definitionDigest:Tr.optional(),couponDigests:fe.record(fe.uuid(),Tr).optional()}))}),_M=fe.strictObject({kind:fe.literal("sdk_configuration"),schemaVersion:fe.literal(1),scope:Hw,revision:Yc,generation:Zc,policy:fe.strictObject({refreshIntervalSeconds:fe.number().positive().max(15),maxControlAgeSeconds:fe.number().positive().max(60)}),gb:fe.strictObject({features:fe.string().nullable(),pageExperiments:fe.string().nullable()}),artifacts:fe.record(fe.string(),Qw),funnels:fe.record(fe.uuid(),Zw)}).superRefine((e,t)=>{let n=(r,i)=>{r!==null&&e.artifacts[r]?.kind!==i&&t.addIssue({code:"custom",message:"Missing or wrong-kind configuration artifact"})};n(e.gb.features,"gb_features"),n(e.gb.pageExperiments,"gb_page_experiments");for(let r of Object.values(e.funnels)){r.evaluationMode==="remote"&&Object.keys(r.versions).length&&t.addIssue({code:"custom",message:"Remote Funnel graphs cannot be public"}),r.evaluationMode==="local"&&!r.versions[r.currentVersionId]&&t.addIssue({code:"custom",message:"Current Funnel Version is not retained"});for(let i of Object.values(r.versions))n(i.artifact,"funnel")}});function Jc(e){if(Array.isArray(e))return`[${e.map(Jc).join(",")}]`;if(e!==null&&typeof e=="object")return`{${Object.entries(e).sort(([n],[r])=>n<r?-1:n>r?1:0).map(([n,r])=>`${JSON.stringify(n)}:${Jc(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Yw(e){return Gi(Wi(typeof e=="string"?new TextEncoder().encode(e):e))}function yM(e){return Yw(Jc(e))}function SM(e,t){for(let o of Object.values(e.references))if(o.type==="flag"&&(!Object.hasOwn(t.features,o.key)||t.remoteFeatures.includes(o.key))||o.type==="experiment"&&!Object.hasOwn(t.experiments,o.id)||o.type==="saved_group"&&!Object.hasOwn(t.savedGroups,o.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=Qa(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let o of e.graph.nodes){let s=o.type==="feature"?o.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=o.type==="feature"?e.variables[s]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(d=>[...Object.hasOwn(d,"force")?[d.force]:[],...d.variations??[],...(d.tracks??[]).flatMap(p=>p.experiment.variations)])].some(d=>d===void 0||!Xt(u,d)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of cr(o)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&a(c.condition)}};for(let o of e.graph.nodes)if(o.type==="condition")for(let s of o.cases)a(s.condition);for(let o of Object.values(n.features))for(let s of o.rules??[]){a(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}for(let c of s.tracks??[])a(c.experiment.condition)}for(let o of Object.values(n.experiments)){a(o.condition);for(let s of o.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");a(s.condition)}}for(let o of e.graph.nodes)if(o.type==="split"){let s=n.experiments[o.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!o.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return Zh.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([o,s])=>[o,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function vM(e){return ar.parse(e)}import{z as Le}from"zod";var Jw=32,Xw=522240;function EM(e){if(["entry","condition","feature","split","offering","coupon","coupons"].includes(e.type))return!0;if(e.type!=="end"&&e.type!=="output")return!1;let t=e.type==="end"?e.output:e.value;return t?.type!=="bundle"&&t?.type!=="selection"}var zw=Le.strictObject({nodeId:Le.string().min(1).max(64),visit:Le.number().int().nonnegative(),revision:Le.number().int().nonnegative()}),Xc=Le.record(Le.string(),Ie),eP=Le.strictObject({id:Le.uuid(),nodeId:Le.string().min(1).max(64),visit:Le.number().int().nonnegative(),input:Le.strictObject({schemaVersion:jr.shape.schemaVersion,kind:jr.shape.kind,selector:jr.shape.selector,contract:jr.shape.contract}),context:Xc,removed:Le.array(Le.string()).max(100),attributes:Xc,removedAttributes:Le.array(Le.string()).max(100),result:nf,offeringVersionId:Le.uuid().nullable(),events:Le.strictObject({entered:Le.string().regex(/^[1-9][0-9]{0,18}$/),decision:Le.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),tP=Le.strictObject({schemaVersion:Le.literal(1),mode:Le.enum(["local","remote"]),versionId:Le.uuid(),generation:Le.number().int().positive(),base:zw,context:Xc,steps:Le.array(eP).min(1).max(Jw)}).refine(e=>wt(e)<=Xw,"Segment exceeds its byte budget"),TM=(e,t,n)=>Xm(e,t,`step:${n}`);function Yh(e){return Array.isArray(e)?e.some(t=>Yh(t)):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>(t==="hashAttribute"||t==="fallbackAttribute")&&n==="results"||Yh(n))}function RM(e,t){let n={};for(let[s,c]of Object.entries(t))JSON.stringify(e[s])!==JSON.stringify(c)&&(n[s]=c);let r=e.attributes,i=t.attributes,a={},o=[];if(r&&typeof r=="object"&&!Array.isArray(r)&&i&&typeof i=="object"&&!Array.isArray(i)){for(let[s,c]of Object.entries(i))JSON.stringify(r[s])!==JSON.stringify(c)&&(a[s]=c);o=Object.keys(r).filter(s=>!Object.hasOwn(i,s)),delete n.attributes}return{context:n,removed:Object.keys(e).filter(s=>!Object.hasOwn(t,s)),attributes:a,removedAttributes:o}}function jM(e){let t=tP.parse(e),n=structuredClone(t.context);return t.steps.map(r=>{for(let i of r.removed)delete n[i];if(n={...n,...r.context},Object.keys(r.attributes).length||r.removedAttributes.length){let i=Le.record(Le.string(),Ie).parse(n.attributes);for(let a of r.removedAttributes)delete i[a];n.attributes={...i,...r.attributes}}return{...r,input:jr.parse({...r.input,context:structuredClone(n)})}})}import{z as nP}from"zod";var UM=nP.strictObject({document:ar,configuration:Za.options[0]});var rP=["checkEntitlement","resolveOffering","readHoldings","readLedger","readBillingInvoice","readCreditStatement","readSubscriptionOperation","readSubscriptionUpdate","readPaymentSetup","readRefund","readBillingControls","listBillingInvoices","readSeats","quoteBalance","readUsage","readBalanceSource","listBalanceGrants","readUsageAnalytics","readCreditAnalytics","readUsageBatch","listOffers"];function BM(e){return e.type==="external_page"||e.type==="wait"||e.type==="action"&&!(e.action.type==="api"&&rP.includes(e.action.operation))||e.type==="output"&&e.value.type==="bundle"}export{Xb as a,Ol as b,Yo as c,Rl as d,da as e,t_ as f,Jo as g,n_ as h,jl as i,Xo as j,IP as k,r_ as l,kl as m,AP as n,Dl as o,wP as p,ai as q,es as r,pa as s,RP as t,Fl as u,a_ as v,o_ as w,jP as x,ts as y,ns as z,rs as A,is as B,c_ as C,u_ as D,Ml as E,l_ as F,$P as G,an as H,JP as I,Bl as J,XP as K,Ll as L,d_ as M,ql as N,zP as O,eC as P,p_ as Q,Vl as R,as as S,tC as T,nC as U,oC as V,m_ as W,f_ as X,Wl as Y,pC as Z,mr as _,Yt as $,Kl as aa,h_ as ba,Hl as ca,mC as da,fC as ea,hC as fa,gC as ga,bC as ha,_C as ia,oi as ja,ma as ka,Xl as la,cs as ma,fr as na,b_ as oa,__ as pa,y_ as qa,S_ as ra,An as sa,zl as ta,ed as ua,td as va,nd as wa,fa as xa,rd as ya,id as za,ad as Aa,od as Ba,x_ as Ca,sd as Da,I_ as Ea,A_ as Fa,w_ as Ga,cd as Ha,us as Ia,P_ as Ja,ci as Ka,ud as La,ld as Ma,dd as Na,C_ as Oa,pd as Pa,md as Qa,li as Ra,di as Sa,Wn as Ta,ha as Ua,ds as Va,O_ as Wa,hd as Xa,gd as Ya,pi as Za,ga as _a,bd as $a,UC as ab,MC as bb,BC as cb,LC as db,E_ as eb,qC as fb,VC as gb,ms as hb,KC as ib,HC as jb,yd as kb,T_ as lb,ZC as mb,_d as nb,R_ as ob,vd as pb,hs as qb,k_ as rb,YC as sb,Kn as tb,JC as ub,XC as vb,D_ as wb,N_ as xb,F_ as yb,U_ as zb,nO as Ab,rO as Bb,xd as Cb,gs as Db,dO as Eb,pO as Fb,M_ as Gb,gO as Hb,bO as Ib,B_ as Jb,Cd as Kb,bs as Lb,Od as Mb,Ed as Nb,Td as Ob,L_ as Pb,Rd as Qb,_s as Rb,jd as Sb,TO as Tb,kd as Ub,RO as Vb,jO as Wb,Nd as Xb,Fd as Yb,vs as Zb,V_ as _b,Ud as $b,UO as ac,$_ as bc,G_ as cc,Cn as dc,Bd as ec,W_ as fc,K_ as gc,xs as hc,Is as ic,On as jc,py as kc,As as lc,gr as mc,ip as nc,Zn as oc,qy as pc,Vy as qc,op as rc,hi as sc,br as tc,_a as uc,sp as vc,cp as wc,ws as xc,$y as yc,Gy as zc,Wy as Ac,up as Bc,Ps as Cc,lp as Dc,dp as Ec,pp as Fc,ya as Gc,oE as Hc,sE as Ic,mp as Jc,Sa as Kc,Ky as Lc,bi as Mc,va as Nc,fp as Oc,Qy as Pc,Os as Qc,mE as Rc,gp as Sc,bp as Tc,Zy as Uc,Es as Vc,yp as Wc,Sp as Xc,Ia as Yc,Aa as Zc,Yy as _c,Jy as $c,Xy as ad,vp as bd,xp as cd,Ip as dd,Ap as ed,wp as fd,Pp as gd,Cp as hd,Op as id,ks as jd,zy as kd,eS as ld,_i as md,tS as nd,rS as od,iS as pd,yi as qd,CE as rd,wa as sd,js as td,aS as ud,Tp as vd,Rp as wd,oS as xd,OE as yd,EE as zd,jp as Ad,sS as Bd,TE as Cd,cS as Dd,_r as Ed,kp as Fd,UE as Gd,Dp as Hd,gn as Id,lS as Jd,Ca as Kd,Oa as Ld,mS as Md,fS as Nd,Np as Od,QE as Pd,ZE as Qd,YE as Rd,JE as Sd,Fp as Td,Ea as Ud,Mp as Vd,Ds as Wd,Bp as Xd,Lp as Yd,qp as Zd,$p as _d,Vp as $d,Ns as ae,hS as be,hT as ce,gS as de,Gp as ee,bS as fe,zn as ge,Wp as he,Hp as ie,Qp as je,Zp as ke,Yp as le,Jp as me,_S as ne,Xp as oe,yS as pe,SS as qe,vS as re,xS as se,tm as te,Ms as ue,rm as ve,IS as we,AS as xe,ET as ye,TT as ze,RT as Ae,am as Be,om as Ce,sm as De,cm as Ee,um as Fe,lm as Ge,jT as He,kT as Ie,PS as Je,CS as Ke,DT as Le,NT as Me,sn as Ne,Bs as Oe,OS as Pe,vi as Qe,ES as Re,MT as Se,pm as Te,mm as Ue,BT as Ve,fm as We,hm as Xe,Ls as Ye,qs as Ze,jS as _e,kS as $e,DS as af,LT as bf,Vs as cf,vr as df,ja as ef,bm as ff,xr as gf,Ir as hf,er as if,tr as jf,Ar as kf,_m as lf,NS as mf,FS as nf,$s as of,ym as pf,Sm as qf,vm as rf,Gs as sf,xm as tf,Ws as uf,QT as vf,ZT as wf,Ks as xf,US as yf,Im as zf,MS as Af,Am as Bf,wm as Cf,Pm as Df,Hs as Ef,BS as Ff,Cm as Gf,iR as Hf,Om as If,Qs as Jf,Em as Kf,xi as Lf,Tm as Mf,aR as Nf,LS as Of,KR as Pf,D as Qf,qS as Rf,VS as Sf,$S as Tf,HR as Uf,j as Vf,QR as Wf,Qe as Xf,XR as Yf,Da as Zf,ej as _f,tj as $f,wt as ag,Dm as bg,km as cg,Fa as dg,ij as eg,Nm as fg,lj as gg,WS as hg,KS as ig,dj as jg,pj as kg,Fm as lg,HS as mg,hj as ng,QS as og,Um as pg,Mm as qg,ZS as rg,gj as sg,bj as tg,_j as ug,yj as vg,YS as wg,xj as xg,Ij as yg,Pj as zg,Cj as Ag,Lm as Bg,Rj as Cg,jj as Dg,Pr as Eg,Cr as Fg,XS as Gg,Ma as Hg,Xt as Ig,nr as Jg,Ci as Kg,zS as Lg,Oi as Mg,qm as Ng,Xs as Og,Ei as Pg,$t as Qg,cn as Rg,Or as Sg,Ti as Tg,Vm as Ug,La as Vg,zs as Wg,e0 as Xg,Gm as Yg,Wm as Zg,Qj as _g,Zj as $g,Yj as ah,Jj as bh,Xj as ch,zj as dh,t0 as eh,ek as fh,ec as gh,Ri as hh,qa as ih,Km as jh,tc as kh,Va as lh,Hm as mh,ji as nh,n0 as oh,nc as ph,mk as qh,fk as rh,hk as sh,Qm as th,r0 as uh,vk as vh,xk as wh,Ik as xh,i0 as yh,a0 as zh,rc as Ah,Ck as Bh,o0 as Ch,s0 as Dh,Jm as Eh,kk as Fh,ic as Gh,ac as Hh,l0 as Ih,oc as Jh,sc as Kh,Er as Lh,d0 as Mh,p0 as Nh,Wk as Oh,ki as Ph,zk as Qh,Xm as Rh,Tr as Sh,zm as Th,uD as Uh,lD as Vh,Ga as Wh,uc as Xh,lc as Yh,bD as Zh,_D as _h,tf as $h,wD as ai,pc as bi,mc as ci,jr as di,nf as ei,PD as fi,CD as gi,f0 as hi,Dt as ii,af as ji,ar as ki,h0 as li,g0 as mi,Di as ni,b0 as oi,_0 as pi,zD as qi,eN as ri,tN as si,gc as ti,y0 as ui,S0 as vi,bc as wi,of as xi,gN as yi,SN as zi,sf as Ai,ON as Bi,EN as Ci,uf as Di,Za as Ei,I0 as Fi,A0 as Gi,w0 as Hi,qN as Ii,df as Ji,P0 as Ki,_c as Li,yc as Mi,Sc as Ni,C0 as Oi,O0 as Pi,eF as Qi,tF as Ri,nF as Si,rF as Ti,oF as Ui,uF as Vi,mf as Wi,mF as Xi,fF as Yi,E0 as Zi,T0 as _i,R0 as $i,j0 as aj,k0 as bj,D0 as cj,_F as dj,N0 as ej,yF as fj,SF as gj,AF as hj,F0 as ij,U0 as jj,Ya as kj,M0 as lj,B0 as mj,CF as nj,jF as oj,kF as pj,DF as qj,L0 as rj,NF as sj,BF as tj,LF as uj,tv as vj,nv as wj,rv as xj,zF as yj,Pf as zj,iv as Aj,n2 as Bj,Cf as Cj,s2 as Dj,c2 as Ej,m2 as Fj,f2 as Gj,av as Hj,_2 as Ij,y2 as Jj,Of as Kj,Ef as Lj,P2 as Mj,C2 as Nj,sv as Oj,F2 as Pj,cv as Qj,U2 as Rj,uv as Sj,B2 as Tj,Rf as Uj,L2 as Vj,q2 as Wj,jf as Xj,kf as Yj,K2 as Zj,H2 as _j,lv as $j,z2 as ak,dv as bk,eU as ck,tU as dk,Ff as ek,Uf as fk,oU as gk,sU as hk,cU as ik,uU as jk,Nf as kk,lU as lk,pv as mk,mU as nk,gU as ok,fv as pk,Bf as qk,bU as rk,yU as sk,SU as tk,oM as uk,sM as vk,cM as wk,Kw as xk,Hw as yk,Zh as zk,Qw as Ak,Zw as Bk,_M as Ck,Jc as Dk,Yw as Ek,yM as Fk,SM as Gk,vM as Hk,Jw as Ik,Xw as Jk,EM as Kk,zw as Lk,eP as Mk,tP as Nk,TM as Ok,Yh as Pk,RM as Qk,jM as Rk,UM as Sk,rP as Tk,BM as Uk};
|