@tinkerlandai/longplay-sdk 0.10.8 → 0.10.13
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 +28 -0
- package/README.md +40 -4
- package/README.zh-CN.md +3 -1
- package/dist/{ai-usage-Btwg1nD7.d.ts → ai-usage-C-OZBxgW.d.ts} +1 -1
- package/dist/{api-5gAz4-Sb.d.ts → api-Bf_aRlXs.d.ts} +82 -0
- package/dist/chunk-33FQUT3Z.js +179 -0
- package/dist/chunk-3JDJD4NY.js +1 -0
- package/dist/chunk-ADSQZ7T3.js +1 -0
- package/dist/chunk-AHDMDMHB.js +1 -0
- package/dist/chunk-AY3DAC2V.js +4 -0
- package/dist/chunk-KQ4MS4LR.js +6 -0
- package/dist/chunk-OBZSDWLC.js +1 -0
- package/dist/chunk-OZZMZH7X.js +1 -0
- package/dist/chunk-RGWFBLW4.js +1 -0
- package/dist/chunk-RK6UEQF2.js +1 -0
- package/dist/chunk-VQBQAKJD.js +1 -0
- package/dist/chunk-VSJOHWDL.js +17 -0
- package/dist/chunk-VSMITXQD.js +1 -0
- package/dist/chunk-YT7TSF3I.js +1 -0
- package/dist/{configuration-sync-CywDxRkX.d.ts → configuration-sync-D2n_gGj6.d.ts} +1 -0
- package/dist/content-6JUK2IAJ.js +1 -0
- package/dist/{funnel-local-client-B4Z3dvNf.d.ts → funnel-local-client-DJq2K7an.d.ts} +8869 -93
- package/dist/{funnel-node-evaluation-P5B4fPfJ.d.ts → funnel-node-evaluation-CJSkUkbv.d.ts} +36 -0
- package/dist/{funnel-resource-client-BhbXsB2q.d.ts → funnel-process-client-C_UhTH8g.d.ts} +5132 -41
- package/dist/funnel-runtime-host-X5AMUCP2.js +1 -0
- package/dist/index.d.ts +102 -77
- package/dist/index.js +1 -1
- package/dist/native-shell.js +1 -1
- package/dist/openrouter.d.ts +2 -2
- package/dist/openrouter.js +1 -1
- package/dist/page.d.ts +1 -1
- package/dist/page.js +1 -1
- package/dist/paywall-KSTKKKEA.js +1 -0
- package/dist/popup.js +1 -1
- package/dist/react-native.d.ts +109 -106
- package/dist/react-native.js +1 -1
- package/dist/screen-renderer-NHJ6OQTF.js +1 -0
- package/dist/server.d.ts +10677 -25
- package/dist/server.js +1 -1
- package/dist/{visual-dom-OIXANRP3.js → visual-dom-7IF7ITAK.js} +1 -1
- package/dist/visual.js +1 -1
- package/package.json +10 -9
- package/dist/chunk-5JJZSH23.js +0 -179
- package/dist/chunk-5ZS3TNC4.js +0 -1
- package/dist/chunk-7DXL3LHT.js +0 -1
- package/dist/chunk-7XVAFQEE.js +0 -1
- package/dist/chunk-ACF2FBUB.js +0 -1
- package/dist/chunk-CBVZUTNH.js +0 -1
- package/dist/chunk-DCV6IS2Z.js +0 -4
- package/dist/chunk-EI2VRDYJ.js +0 -1
- package/dist/chunk-G56XGVMS.js +0 -1
- package/dist/chunk-GJRXHH6G.js +0 -1
- package/dist/chunk-R26BYN3U.js +0 -1
- package/dist/chunk-RP2P3FU4.js +0 -1
- package/dist/chunk-SBPTOOYB.js +0 -1
- package/dist/chunk-U4UEOR5W.js +0 -6
- package/dist/chunk-XSVQHPQT.js +0 -17
- package/dist/content-XXVHMKKL.js +0 -1
- package/dist/funnel-runtime-host-PBJ63LOE.js +0 -1
- package/dist/paywall-CDR4GZMX.js +0 -1
- package/dist/screen-renderer-NLB3FAQJ.js +0 -1
- /package/dist/{chunk-AK3IJ6FZ.js → chunk-OJM6ORHE.js} +0 -0
package/dist/chunk-U4UEOR5W.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{$ as gn,A as qi,B as fn,C as as,D as ss,E as cs,F as us,G as ls,H as Pr,I as An,J as ps,K as ds,L as Hn,M as ms,N as hn,O as fs,Q as As,R as hs,S as gs,T as bs,X as Zn,Z as Pt,_ as it,a as Ln,aa as zi,b as La,ba as Tt,c as $a,d as Ga,e as Ka,ea as Ni,f as Ha,g as ce,h as Ti,ha as kr,i as Za,ia as Zt,j as ft,ja as xt,k as we,ka as Fi,l as Mi,m as _t,n as Qa,na as Os,o as Or,p as Ja,q as Wa,qa as ue,r as mn,s as es,t as Gn,u as ts,v as ns,w as rs,x as Kn,y as is,z as os}from"./chunk-ACF2FBUB.js";import{a as ve,b as ys,c as xs,d as Ss,e as Mt,f as vs,g as Cr,h as Is,i as ws}from"./chunk-G56XGVMS.js";import{a as js,b as _s}from"./chunk-7XVAFQEE.js";import{a as me,b as rt,c as Ht,d as Dt,e as _r}from"./chunk-7DXL3LHT.js";import{c as wr,d as jr,e as Xa,f as Bi,g as Ya,h as $n}from"./chunk-XSVQHPQT.js";import{z as y}from"zod";import{z as A}from"zod";var He=A.string().min(1).max(200),et=A.iso.datetime({offset:!0}),De=A.number().int().nonnegative().max(1e8),Rr=A.string().regex(/^[A-Z]{3}$/),ud=["purchase.subscription","purchase.one_time","purchase.prepaid","purchase.trial","purchase.seats","purchase.tiered","tax.automatic","discount.percent.once","discount.percent.repeating","discount.percent.forever","discount.amount.once","discount.amount.repeating","discount.amount.forever","subscription.cancel.immediate","subscription.cancel.renewal","subscription.resume","subscription.plan.immediate","subscription.plan.renewal","subscription.seats","subscription.quantity","subscription.billing_cycle","subscription.proration","refund.full","refund.partial","refund.revoke"],Ps=A.enum(ud),Cs=A.strictObject({priceId:A.uuid(),productVersionId:A.uuid(),productId:He,quantity:A.number().int().min(1).max(1e6),unitAmountMinor:De,totalMinor:De,interval:A.enum(["week","month","year","one_off"]),intervalCount:A.number().int().min(1).max(52),kind:A.enum(["fixed","prepaid","seat"]),tiers:A.strictObject({mode:A.enum(["graduated","volume"]),tiers:A.array(A.strictObject({upTo:A.number().int().positive().nullable(),unitAmountMinor:De,flatAmountMinor:De.optional()})).min(2).max(12)}).nullable()}),ld=A.strictObject({grantId:A.uuid(),couponId:A.uuid(),amountMinor:De,terms:A.discriminatedUnion("type",[A.strictObject({type:A.literal("percent"),percentOff:A.number().gt(0).max(100)}),A.strictObject({type:A.literal("amount"),amountOffMinor:De,currency:Rr})]),duration:A.discriminatedUnion("type",[A.strictObject({type:A.literal("once")}),A.strictObject({type:A.literal("forever")}),A.strictObject({type:A.literal("repeating"),months:A.number().int().min(1).max(36)})])}),$i={provider:A.literal("merchant"),executor:A.literal("merchant"),operationId:A.uuid(),customerId:A.uuid(),configurationRevision:A.number().int().nonnegative(),connectionRevision:A.number().int().nonnegative(),currency:Rr,expiresAt:et},Er=A.strictObject({...$i,type:A.literal("purchase"),mode:A.enum(["payment","subscription"]),lineItems:A.array(Cs).min(1).max(100),catalogAmountMinor:De,discount:ld.nullable(),trialPeriodDays:A.number().int().min(1).max(730).nullable(),automaticTax:A.boolean()}).refine(e=>e.lineItems.reduce((t,n)=>t+n.totalMinor,0)===e.catalogAmountMinor&&(!e.discount||e.discount.amountMinor<=e.catalogAmountMinor)&&new Set(e.lineItems.map(t=>t.priceId)).size===e.lineItems.length,"Purchase lines must retain the original total and unique Price identities"),Dr=A.strictObject({...$i,type:A.literal("subscription_change"),subscriptionId:A.uuid(),merchantSubscriptionId:He,membershipId:A.uuid(),subscriptionAction:A.enum(["update","cancel","schedule","release"]),supersedesOperationId:A.uuid().nullable(),change:A.discriminatedUnion("type",[A.strictObject({type:A.literal("cancel")}),A.strictObject({type:A.literal("uncancel")}),A.strictObject({type:A.literal("plan"),productVersionId:A.uuid()}),A.strictObject({type:A.literal("seats"),licenseKey:He,quantity:A.number().int().nonnegative().max(1e6)}),A.strictObject({type:A.literal("quantity"),internal_feature_id:A.uuid(),quantity:A.number().int().nonnegative().max(1e6)}),A.strictObject({type:A.literal("billing_cycle"),billingCycleAnchor:A.union([A.literal("now"),A.number().int().positive()])})]),timing:A.enum(["immediate","renewal"]),effectiveAt:et,creditMinor:De,debitMinor:De,totalMinor:De,discountMinor:De,taxMinor:De,proration:A.enum(["none","create_prorations","always_invoice"]),lineItems:A.array(Cs.extend({quantity:A.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:A.array(A.uuid()).max(100)}),Tr=A.strictObject({...$i,type:A.literal("refund"),invoiceId:A.uuid(),merchantInvoiceId:He,amountMinor:De.refine(e=>e>0),mode:A.enum(["full","partial"]),entitlementAction:A.enum(["retain","revoke"]),cancelSubscriptions:A.array(He).max(100)}),ks=A.discriminatedUnion("type",[Er,Dr,Tr]);function Zh(e){let t=new Set;if(e.type==="purchase")t.add(e.mode==="subscription"?"purchase.subscription":"purchase.one_time"),e.lineItems.some(n=>n.kind==="prepaid")&&t.add("purchase.prepaid"),e.lineItems.some(n=>n.kind==="seat")&&t.add("purchase.seats"),e.lineItems.some(n=>n.tiers!==null)&&t.add("purchase.tiered"),e.trialPeriodDays!==null&&t.add("purchase.trial"),e.automaticTax&&t.add("tax.automatic"),e.discount&&t.add(`discount.${e.discount.terms.type}.${e.discount.duration.type}`);else if(e.type==="refund")t.add(`refund.${e.mode}`),e.entitlementAction==="revoke"&&t.add("refund.revoke");else{let n=e.change.type;n==="cancel"?t.add(`subscription.cancel.${e.timing}`):n==="uncancel"?t.add("subscription.resume"):n==="plan"?t.add(`subscription.plan.${e.timing}`):t.add(`subscription.${n}`),e.proration!=="none"&&t.add("subscription.proration")}return[...t].sort()}function Qh(e){return e.type==="purchase"?e.mode==="subscription"?["purchase.completed","purchase.closed","subscription.observed","invoice.paid"]:["purchase.completed","purchase.closed"]:e.type==="subscription_change"?["subscription.change.completed","subscription.observed",...e.change.type==="cancel"||e.change.type==="uncancel"?[]:["invoice.paid"]]:["refund.updated",...e.entitlementAction==="revoke"&&e.cancelSubscriptions.length?["subscription.observed"]:[]]}var Qn=A.strictObject({phase:A.enum(["execution","payment","fulfillment","recording"]),code:Ln,reason:$a.optional(),recovery:La,retryable:A.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),Ui={operationId:A.uuid(),customerId:A.uuid(),merchantExecutionId:He,fulfillmentStatus:A.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:A.enum(["not_ready","pending","accepted","failed"]),updatedAt:et,problem:Qn.nullable(),pollAfterMs:A.number().int().min(1e3).max(6e4).nullable()},Qt=A.discriminatedUnion("type",[A.strictObject({...Ui,type:A.literal("purchase"),merchantOrderId:He.nullable(),paymentStatus:A.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:A.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:et.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),A.strictObject({...Ui,type:A.literal("subscription_change"),status:A.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:He,scheduledFor:et.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),A.strictObject({...Ui,type:A.literal("refund"),status:A.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:He.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),Rs=A.discriminatedUnion("lookup",[A.strictObject({lookup:A.literal("found"),operationId:A.uuid(),customerId:A.uuid(),execution:Qt,readAt:et}),A.strictObject({lookup:A.literal("not_received"),operationId:A.uuid(),customerId:A.uuid(),execution:A.null(),readAt:et})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),Vi=A.strictObject({merchantSubscriptionId:He,revision:A.number().int().positive(),status:A.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:et,periodEndsAt:et,cancelAtPeriodEnd:A.boolean(),hasDiscounts:A.boolean(),items:A.array(A.strictObject({merchantItemId:He,priceId:A.uuid(),quantity:A.number().int().positive().max(1e6)})).min(1).max(100)}).refine(e=>Date.parse(e.periodEndsAt)>Date.parse(e.periodStartsAt)&&new Set(e.items.map(t=>t.priceId)).size===e.items.length,"Subscription periods and Price identities must be unambiguous"),Li=A.strictObject({merchantInvoiceId:He,currency:Rr,subtotalMinor:De,discountMinor:De,taxMinor:De,totalMinor:De,paidMinor:De,periodStartsAt:et.nullable(),periodEndsAt:et.nullable(),lines:A.array(A.strictObject({merchantLineId:He,priceId:A.uuid(),quantity:A.number().int().nonnegative().max(1e6),subtotalMinor:A.number().int().min(-1e8).max(1e8),discountMinor:De,taxMinor:De,totalMinor:A.number().int().min(-1e8).max(2e8),periodStartsAt:et.nullable(),periodEndsAt:et.nullable()}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&(e.subtotalMinor<0?e.discountMinor===0&&e.taxMinor===0:e.discountMinor<=e.subtotalMinor),"Invoice line amounts must retain the complete debit or credit")).min(1).max(100)}).refine(e=>e.subtotalMinor-e.discountMinor+e.taxMinor===e.totalMinor&&e.discountMinor<=e.subtotalMinor&&e.paidMinor===e.totalMinor&&new Set(e.lines.map(t=>t.merchantLineId)).size===e.lines.length&&e.lines.reduce((t,n)=>t+n.subtotalMinor,0)===e.subtotalMinor&&e.lines.reduce((t,n)=>t+n.discountMinor,0)===e.discountMinor&&e.lines.reduce((t,n)=>t+n.taxMinor,0)===e.taxMinor&&e.lines.reduce((t,n)=>t+n.totalMinor,0)===e.totalMinor,"A paid Invoice retains the complete financial amounts"),bn={provider:A.literal("merchant"),eventId:A.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:A.uuid(),occurredAt:et},Es=A.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),Ds=A.discriminatedUnion("type",[A.strictObject({...bn,type:A.literal("purchase.completed"),operationId:A.uuid(),merchantOrderId:He,paymentStatus:A.enum(["paid","trialing","no_payment_required"]),invoice:Li.nullable(),subscription:Vi.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),A.strictObject({...bn,type:A.literal("purchase.closed"),operationId:A.uuid(),status:A.enum(["failed","expired","canceled"])}),A.strictObject({...bn,type:A.literal("subscription.observed"),operationId:A.uuid().nullable(),subscription:Vi}),A.strictObject({...bn,type:A.literal("subscription.change.completed"),operationId:A.uuid(),status:A.enum(["scheduled","applied"]),scheduledFor:et.nullable(),subscription:Vi,invoice:Li.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),A.strictObject({...bn,type:A.literal("invoice.paid"),merchantSubscriptionId:He,invoice:Li}),A.strictObject({...bn,type:A.literal("refund.updated"),operationId:A.uuid(),merchantRefundId:He,status:A.enum(["pending","succeeded","failed"]),amountMinor:De.refine(e=>e>0),currency:Rr})]);import{z as Jt}from"zod";var Bt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,qt=Jt.object({customerId:Jt.uuid(),sessionId:Jt.uuid(),accessToken:Jt.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Jt.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Jt.iso.datetime(),refreshExpiresAt:Jt.iso.datetime()});var yn=3,Ms="/integrations/indiana",ng="X-Indiana-Merchant-Bridge-Version",pd=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],dd=y.enum(pd),rg={session:{command:"session.create",authority:"merchant_user"},catalog:{command:"catalog.read",authority:"merchant_catalog_reader"},customer_commerce:{command:"customer.commerce.read",authority:"merchant_user"},presentation:{command:"presentation.resolve",authority:"merchant_user"},presentation_events:{command:"presentation.report",authority:"merchant_user"},purchases:{command:"purchase.execute",authority:"merchant_user"},operation_status:{command:"operation.read",authority:"merchant_user"},billing_records:{command:null,authority:"indiana_server_key"},subscription_changes:{command:"subscription.change",authority:"merchant_user"},refunds:{command:"refund.execute",authority:"merchant_refund_authority"}},Bs=y.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),qs=y.string().regex(/^[A-Za-z0-9_-]{1,64}$/),md=y.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Ki=y.strictObject({keyId:qs,signingSecret:md}),fd=y.string().max(300).superRefine((e,t)=>{try{let n=new URL(e);if(n.protocol!=="https:"||n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.port&&n.port!=="443"||!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.[a-z]{2,63}$/.test(n.hostname)||/(?:^|\.)(?:localhost|local|internal)$/.test(n.hostname))throw new Error("invalid origin")}catch{t.addIssue({code:"custom",message:"Use an exact public HTTPS origin"})}}).transform(e=>new URL(e).origin),zs=y.array(dd).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Ns=y.strictObject({bridgeVersion:y.literal(yn),projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"]),capabilities:zs,catalog:y.enum(["endpoint","static","none"]),billingEvents:y.array(Es).max(6),profiles:y.array(Ps).max(32).refine(e=>new Set(e).size===e.length,"Profiles must be unique")}).superRefine((e,t)=>{let n=r=>e.capabilities.includes(r);n("catalog")!==(e.catalog!=="none")&&t.addIssue({code:"custom",path:["catalog"],message:"Catalog declaration differs from its capability"}),(n("billing_records")!==e.billingEvents.length>0||new Set(e.billingEvents).size!==e.billingEvents.length)&&t.addIssue({code:"custom",path:["billingEvents"],message:"Declare the unique supported billing events"})}),Fs=y.strictObject({origin:fd,requiredCapabilities:zs}),Ad=y.strictObject({revision:y.number().int().nonnegative(),checkedAt:y.iso.datetime(),outcome:y.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:y.strictObject({ping:y.enum(["passed","failed","not_checked"]),authentication:y.enum(["passed","failed","not_checked"]),catalog:y.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Ns.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),ig=y.strictObject({projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"]),execution:y.enum(["indiana","record_only"]),accountId:y.string().nullable(),revision:y.number().int().nonnegative(),authentication:y.strictObject({keyId:qs}).nullable(),secretStoreConfigured:y.boolean().optional(),connection:Fs.nullable(),check:Ad.nullable()});var Ts=y.strictObject({projectId:y.uuid(),environmentId:y.uuid()}),og=y.discriminatedUnion("action",[Ts.extend({action:y.literal("save"),revision:y.number().int().nonnegative(),connection:Fs,authentication:Ki.optional()}),Ts.extend({action:y.literal("check"),revision:y.number().int().nonnegative()})]),Br=y.strictObject({projectId:y.uuid(),environmentId:y.uuid(),environment:y.enum(["sandbox","live"])});function ag(e){return y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),command:Bs,scope:Br,data:e})}var hd=y.strictObject({nativeUserId:y.string().min(1).max(128),session:qt.strict()}),gd=y.strictObject({nativeUserId:y.string().min(1).max(128),presentation:y.strictObject({customerId:y.uuid(),decisionId:y.uuid(),offeringVersionId:y.uuid(),paywallVersionId:y.uuid(),variant:y.string().min(1).max(128)}).nullable()}),bd=y.strictObject({decisionId:y.uuid(),eventId:y.uuid()}),Mr=y.strictObject({operationId:y.uuid(),customerId:y.uuid()}),qr=y.strictObject({scope:Br,operationId:y.uuid(),customerId:y.uuid(),confirmedAt:y.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:y.boolean(),instruction:ks}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),Gi=Qt,Ct=y.string().min(1).max(120),yd=y.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),xd=y.strictObject({revision:Ct,updatedAt:y.iso.datetime(),provider:y.literal("merchant"),items:y.array(y.strictObject({merchantProductId:Ct,productVersionId:y.uuid(),name:y.string().min(1).max(255),kind:y.enum(["subscription","credit_pack"]),merchantPriceId:Ct,currency:y.string().regex(/^[a-z]{3}$/),amountMinor:y.number().int().nonnegative().max(1e8),interval:y.enum(["one_time","month","year"]),intervalCount:y.literal(1),includedCredits:y.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:y.enum(["none","month"]),creditPolicyId:Ct,available:y.boolean()}).superRefine((e,t)=>{(e.kind==="credit_pack"&&(e.interval!=="one_time"||e.creditReset!=="none")||e.kind==="subscription"&&e.interval==="one_time"||e.available&&e.amountMinor===0)&&t.addIssue({code:"custom",message:"Unsupported version 1 catalog terms"})})).max(500)}),Sd=y.strictObject({customerId:y.uuid(),revision:y.string().min(1).max(128),observedAt:y.iso.datetime(),subscriptions:y.array(y.strictObject({merchantSubscriptionId:Ct,merchantProductId:Ct,productVersionId:y.uuid().nullable(),status:y.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:y.iso.datetime().nullable(),currentPeriodEndsAt:y.iso.datetime().nullable(),cancelAtPeriodEnd:y.boolean(),scheduledChange:y.strictObject({effectiveAt:y.iso.datetime(),merchantProductId:Ct}).nullable()})).max(100),purchaseHistory:y.strictObject({complete:y.boolean(),hasPaidPurchase:y.boolean(),lastPaidAt:y.iso.datetime().nullable()}),balances:y.array(y.strictObject({bucketId:Ct,key:Ct,available:yd,expiresAt:y.iso.datetime().nullable(),nextResetAt:y.iso.datetime().nullable()})).max(100)}),sg=y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),command:y.string().min(1).max(64),scope:Br,error:y.strictObject({code:y.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:y.string().min(1).max(500),retryable:y.boolean(),recovery:y.string().min(1).max(80)})}),Jn=y.strictObject({}),vd={"bridge.ping":y.strictObject({challenge:y.uuid()}),"bridge.describe":Jn,"session.create":Jn,"catalog.read":Jn,"customer.commerce.read":Jn,"presentation.resolve":Jn,"presentation.report":bd,"purchase.execute":Mr,"operation.read":Mr,"subscription.change":Mr,"refund.execute":Mr},cg={"bridge.ping":y.strictObject({challenge:y.uuid()}),"bridge.describe":Ns,"session.create":hd,"catalog.read":xd,"customer.commerce.read":Sd,"presentation.resolve":gd,"presentation.report":y.strictObject({queued:y.literal(!0)}),"purchase.execute":Gi,"operation.read":Rs,"subscription.change":Gi,"refund.execute":Gi},ug=y.strictObject({bridgeVersion:y.literal(yn),requestId:y.uuid(),scope:Br,command:Bs,data:y.unknown()}).superRefine((e,t)=>{vd[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var Us="X-Indiana-Bridge-Signature",Vs="X-Indiana-Bridge-Key-Id";function Id(e){return new TextEncoder().encode(e)}function Ls(e){return Uint8Array.from(atob(e.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0))}function $s(e,t,n){return Id(`indiana-merchant-bridge:${yn}
|
|
2
|
-
${t}
|
|
3
|
-
POST
|
|
4
|
-
${Ms}
|
|
5
|
-
${n}
|
|
6
|
-
${e}`)}async function Gs(e){let t=Ki.parse(e);return crypto.subtle.importKey("raw",Ls(t.signingSecret),{name:"HMAC",hash:"SHA-256"},!1,["sign","verify"])}async function dg(e,t,n,r=Date.now()){let i=String(Math.floor(r/1e3)),a=new Uint8Array(await crypto.subtle.sign("HMAC",await Gs(t),$s(e,n,i))),s=btoa(String.fromCharCode(...a)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"");return{[Vs]:t.keyId,[Us]:`t=${i},v1=${s}`}}async function mg(e,t,n,r,i=Date.now()){try{if(t.get(Vs)!==n.keyId)return!1;let a=/^t=([0-9]{1,12}),v1=([A-Za-z0-9_-]{43})$/.exec(t.get(Us)??"");return!a||Math.abs(i/1e3-Number(a[1]))>300?!1:await crypto.subtle.verify("HMAC",await Gs(n),Ls(a[2]),$s(e,r,a[1]))}catch{return!1}}var Ks={"zh-Hans":{merchandise:"\u51CF {discount}\uFF08\u5355\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u51CF {discount}",repeating:"\u524D {months} \u4E2A\u6708\u6BCF\u6708\u51CF {discount}",forever:"\u6BCF\u671F\u51CF {discount}"},"zh-Hant":{merchandise:"\u6E1B {discount}\uFF08\u55AE\u6B21\u4F7F\u7528\uFF09",once:"\u9996\u671F\u6E1B {discount}",repeating:"\u524D {months} \u500B\u6708\u6BCF\u6708\u6E1B {discount}",forever:"\u6BCF\u671F\u6E1B {discount}"},en:{merchandise:"{discount} off \xB7 one use",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:{merchandise:"{discount} \u5272\u5F15\uFF081\u56DE\u306E\u307F\uFF09",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:{merchandise:"{discount} \uD560\uC778 \xB7 1\uD68C \uC0AC\uC6A9",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:{merchandise:"{discount} de descuento \xB7 un uso",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:{merchandise:"{discount} de r\xE9duction \xB7 une utilisation",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:{merchandise:"{discount} Rabatt \xB7 einmalig",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:{merchandise:"{discount} de desconto \xB7 um uso",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:{merchandise:"{discount} di sconto \xB7 un utilizzo",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:{merchandise:"\u0421\u043A\u0438\u0434\u043A\u0430 {discount} \xB7 \u043E\u0434\u043D\u043E \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435",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:{merchandise:"Gi\u1EA3m {discount} \xB7 d\xF9ng m\u1ED9t l\u1EA7n",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:{merchandise:"\u0E25\u0E14 {discount} \xB7 \u0E43\u0E0A\u0E49\u0E44\u0E14\u0E49\u0E04\u0E23\u0E31\u0E49\u0E07\u0E40\u0E14\u0E35\u0E22\u0E27",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:{merchandise:"Diskon {discount} \xB7 sekali pakai",once:"Diskon {discount} untuk pembayaran pertama",repeating:"Diskon {discount} setiap bulan selama {months} bulan pertama",forever:"Diskon {discount} untuk setiap pembayaran"},ar:{merchandise:"\u062E\u0635\u0645 {discount} \xB7 \u0627\u0633\u062A\u062E\u062F\u0627\u0645 \u0648\u0627\u062D\u062F",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"}};function Hi(e){let t=es(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=Ks[r];return i?{locale:t,copy:i}:{locale:"en",copy:Ks.en}}function Od(e,t,n="zh-CN"){let r=Ti(t);return Za(e,t,Hi(n).locale,{currencyDisplay:"narrowSymbol",minimumFractionDigits:e%10**r===0?0:r,maximumFractionDigits:r})}function wd(e,t="zh-CN"){let n=Hi(t).locale;return e.type==="percent"?new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:2}).format(e.percentOff/100):Od(e.amountOffCents,e.currency,n)}var Hs={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 gg(e,t="zh-CN",n="month"){let r=Hi(t),i=wd(e.discount,r.locale);if(e.appliesTo?.type==="merchandise")return r.copy.merchandise.replace("{discount}",i);let a=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale).format(e.duration.months):"",s=r.locale.split("-")[0]??"en",c=s==="zh"&&/(?:Hant|TW|HK|MO)/.test(r.locale)?"zh-Hant":s,u=e.duration.type==="repeating"&&n!=="month"?Hs[c]??Hs.en:e.duration.type==="repeating"&&e.duration.months===1?r.copy.repeatingOne??r.copy.repeating:r.copy[e.duration.type],d=e.duration.type==="repeating"?new Intl.NumberFormat(r.locale,{style:"unit",unit:"month",unitDisplay:"long"}).format(e.duration.months):"";return u.replace("{discount}",i).replace("{months}",a).replace("{period}",d)}import{z as Y}from"zod";import{z as $e}from"zod";var Te=$e.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"),Zi=$e.strictObject({type:$e.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:$e.boolean(),enum:$e.array($e.string().max(255)).min(1).max(100).optional()}),xn=Zi.extend({type:$e.enum([...Zi.shape.type.options,"array"]),items:Zi.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"})}),Sn=xn.safeExtend({source:$e.discriminatedUnion("type",[$e.strictObject({type:$e.literal("input")}),$e.strictObject({type:$e.literal("node")}),$e.strictObject({type:$e.enum(["parameter","attribute"]),key:Te})])}),jd=$e.record(Te,Sn),zr=$e.record(Te,Te).refine(e=>Object.keys(e).length<=20);function lt(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=>lt(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&&$e.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 Qi(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&&Qi(e.items,t.items)}function Wn(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,s=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,c=a.type==="parameter"||a.type==="attribute"?a.key:r,u=Object.hasOwn(s,c),d=s[c];if(a.type==="attribute"&&c.includes(".")&&(!u||c.startsWith("merchandise."))){d=s,u=!0;for(let f of c.split(".")){if(!d||typeof d!="object"||!Object.hasOwn(d,f)||Array.isArray(d)&&(!/^(0|[1-9]\d*)$/.test(f)||Number(f)>=d.length)){u=!1;break}d=d[f]}}if(!(!u||d===void 0)){if(!lt(i,d))throw new Error(`Invalid variable value: ${r}`);n[r]=d}}return n}function Wt(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 Ji(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"||!lt(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")}import{z as Xt}from"zod";var At=Xt.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"),St=Xt.discriminatedUnion("source",[Xt.strictObject({source:Xt.literal("literal"),value:me}),Xt.strictObject({source:Xt.literal("variable"),key:Xt.string().min(1).max(255),path:At.optional()})]);function Zs(e,t){if(!t)return e;for(let n of At.parse(t).split(".")){if(Array.isArray(e)){if(!/^(0|[1-9]\d*)$/.test(n)||Number(n)>=e.length)return;e=e[Number(n)];continue}if(e===null||typeof e!="object"||!Object.hasOwn(e,n))return;e=Reflect.get(e,n)}return e}function Wi(e,t){if(e.source==="literal")return structuredClone(e.value);let n=Wn(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(me.parse(Zs(n[e.key],e.path)))}function Xi(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&&!At.safeParse(r).success?null:{key:n,path:r}}function Yi(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Pt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(fs))]}function Nr(e){return Yi(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function ot(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 s=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let c=t.slice(s,i+1);if(!/[eE]/.test(c))continue;let[u="",d]=c.split(/[eE]/),f=u.replace(/^-/,""),x=f.replace(".","").length,k=(f.includes(".")?f.indexOf("."):x)+Number(d),S=k<=0?2-k+x:k>=x?k:x+1;n+=S+(u.startsWith("-")?1:0)-c.length}}return n}var zt=Y.enum(["page","popup","banner"]),_d=3e5,Qs=Y.strictObject({type:Y.enum(["string","number","boolean","strings","json"]),nullable:Y.boolean()}),Pd=Y.strictObject({inputs:Y.record(Zn,Qs.extend({required:Y.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Y.record(Zn,Qs).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Cd=Y.strictObject({kind:zt,schemaVersion:Y.literal(1),name:Y.string().trim().min(1).max(80),screen:it,contract:Pd}),Fr=Cd.superRefine((e,t)=>{let n=(i,a)=>t.addIssue({code:"custom",message:i,path:a});e.screen.surface!==e.kind&&n("Content surface must match its domain",["screen","surface"]),e.screen.name!==e.name&&n("Content has one editable name",["screen","name"]),e.kind==="banner"&&e.screen.presentation.type!=="inline"&&n("Banner requires an inline container",["screen","presentation"]),e.kind!=="banner"&&e.screen.presentation.type==="inline"&&n("Inline presentation belongs to Banner",["screen","presentation"]),e.screen.actions.some(i=>i.type!=="event"&&i.type!=="navigate")&&n("Content actions must emit host intents or navigate locally",["screen","actions"]);let r=new Set(e.screen.actions.filter(i=>i.type==="event").map(i=>i.id));(Object.keys(e.contract.outputs).some(i=>!r.has(i))||[...r].some(i=>!Object.hasOwn(e.contract.outputs,i)))&&n("Every event needs exactly one output declaration",["contract","outputs"]),ot(e)>_d&&n("Content document exceeds its byte budget",[])});function kd(e,t){if(e===null)return t.nullable;switch(t.type){case"json":return!0;case"string":return typeof e=="string";case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"strings":return Array.isArray(e)&&e.every(n=>typeof n=="string")}}var Rd=Fr.superRefine((e,t)=>{for(let n of Nr(e.screen))Object.keys(e.contract.inputs).some(r=>n===r||n.startsWith(r+"."))||t.addIssue({code:"custom",path:["contract","inputs"],message:"Declare every reusable input read"});for(let n of e.screen.actions){if(n.type!=="event")continue;let r=e.contract.outputs[n.id],i=Object.hasOwn(n.properties,"value")?n.properties.value:n.properties;r&&!kd(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Tt(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Js=Y.strictObject({id:Y.uuid(),kind:zt,projectId:Y.uuid(),environmentId:Y.uuid(),name:Y.string(),revision:Y.number().int().nonnegative(),status:Y.enum(["draft","published","archived"]),publishedVersionId:Y.uuid().nullable(),createdAt:Y.iso.datetime({offset:!0}),updatedAt:Y.iso.datetime({offset:!0})}),Mg=Js.extend({draft:Fr}),Bg=Y.strictObject({rows:Y.array(Js).max(200),nextCursor:Y.uuid().nullable()}),eo=Y.strictObject({id:Y.uuid(),kind:zt,resourceId:Y.uuid(),projectId:Y.uuid(),environmentId:Y.uuid(),version:Y.number().int().positive(),sourceRevision:Y.number().int().nonnegative(),document:Rd,createdAt:Y.iso.datetime({offset:!0})}),qg=eo.omit({document:!0}),zg=Y.discriminatedUnion("action",[Y.strictObject({action:Y.literal("create"),kind:zt,id:Y.uuid(),document:Fr}),Y.strictObject({action:Y.literal("save"),kind:zt,id:Y.uuid(),revision:Y.number().int().nonnegative(),document:Fr}),Y.strictObject({action:Y.enum(["publish","archive"]),kind:zt,id:Y.uuid(),revision:Y.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as vn}from"zod";var Ur=vn.strictObject({items:vn.array(vn.strictObject({productVersionId:vn.string().min(1).max(200),label:vn.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:vn.string().min(1).max(200).nullable(),grouping:hs.optional()});function Vg(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 fe}from"zod";var Xn=fe.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Ws=fe.enum(["unknown","denied","provisional","granted"]),Xs=fe.enum(["ios","android"]),Vr=fe.strictObject({installationId:fe.uuid(),publicKey:fe.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:fe.iso.datetime({offset:!0}),signature:fe.string().regex(/^[A-Za-z0-9_-]{86}$/)}),to=fe.string().regex(/^[a-f0-9]{64}$/),Ys=Vr.extend({sequence:Xn,platform:Xs,credentialDigest:to}),ec=Vr.extend({credentialDigest:to}),Gg=Vr.extend({sequence:Xn,platform:Xs}),Lr=Vr.extend({sequence:Xn,credentialDigest:to,connectionId:fe.uuid().nullable(),kind:fe.enum(["fcm_token","apns_token"]).nullable(),token:fe.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Ws}),Kg=Lr,Hg=Lr.extend({challenge:fe.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),Zg=fe.strictObject({requested:fe.literal(!0),expiresAt:fe.iso.datetime({offset:!0})}),$r=fe.strictObject({installationId:fe.uuid(),bound:fe.boolean(),identitySeq:Xn,bindingGeneration:Xn,addressSeq:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:fe.uuid().nullable(),addressStatus:fe.enum(["active","invalid"]).nullable(),permission:Ws}),no=fe.strictObject({channel:fe.enum(["email","sms","voice","push"]),state:fe.enum(["unknown","allowed","denied"]),revision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:fe.iso.datetime({offset:!0}).nullable()}),Qg=fe.strictObject({state:fe.enum(["allowed","denied"]),revision:fe.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Jg(e,t,n){let r=["indiana_push_v1",e,t.projectId,t.environment,n.installationId,n.publicKey,n.issuedAt];e==="bind"?r.push(n.sequence,n.platform,n.credentialDigest):e==="detach"?r.push(n.sequence,n.platform):e==="read"?r.push(n.credentialDigest):r.push(n.sequence,n.credentialDigest,n.connectionId,n.kind,n.token,n.permission),e==="recovery_confirm"&&r.push(n.challenge);let i=JSON.stringify(r);if([...i].some(a=>a.charCodeAt(0)>127))throw new Error("Push proof fields must be ASCII");return Uint8Array.from(i,a=>a.charCodeAt(0))}var ro="X-Indiana-Protocol",tc="X-Indiana-SDK-Version";var io={current:"0.10"};import{z as In}from"zod";var Gr=In.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"),tb=In.object({amountCents:In.number().int().min(0).max(1e8),currency:ce,interval:In.enum(["free","month","year"]),currencyOptions:In.partialRecord(ce,In.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");import{z as v}from"zod";var Ed=v.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),ic=v.enum(["single_use","continuous_use"]),oo=v.record(v.string(),v.union([v.string(),v.number(),v.boolean()]).transform(String).pipe(v.string())),nc=v.string().min(1).max(64).refine(e=>!e.includes("::")),oc={credit_amount:v.number(),tier_behavior:v.never().optional(),tiers:v.never().optional()},ac={credit_amount:v.never().optional(),tier_behavior:v.literal("graduated"),tiers:v.array(v.strictObject({to:v.union([v.number(),v.literal("inf")]),credit_amount:v.number()}))},Dd=v.union([v.strictObject({match:oo,priority:v.number().int().optional(),...oc}),v.strictObject({match:oo,priority:v.number().int().optional(),...ac})]),Td=v.strictObject({match:oo,factor:v.number().positive().optional(),add:v.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),rc={metered_feature_id:v.string(),feature_amount:v.number().optional(),dimensions:v.record(nc,Dd).optional(),multipliers:v.record(nc,Td).optional()},ao=v.union([v.strictObject({...rc,...oc}),v.strictObject({...rc,...ac})]),Hr=v.number().min(-100),sc=v.record(v.string(),v.strictObject({markup:Hr})).nullish(),Zr=v.record(v.string().regex(/.+\/.+/),v.strictObject({markup:Hr.optional(),input_cost:v.number().min(0).optional(),output_cost:v.number().min(0).optional()})).nullish(),Md=v.strictObject({default_markup:Hr.optional(),provider_markups:sc,model_markups:Zr}),ib=v.strictObject({schema:v.array(ao).optional(),markups:Md.optional()}),Bd=v.strictObject({filters:v.array(v.strictObject({property:v.string(),operator:v.string(),value:v.array(v.string())})),aggregate:v.strictObject({type:v.string(),property:v.string().nullable()}),usage_type:ic}),cc=v.strictObject({schema:v.array(ao).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:v.boolean().optional(),usage_type:ic.default("single_use").overwrite(()=>"single_use"),default_markup:Hr.optional(),provider_markups:sc}),so=cc.safeExtend({schema:v.array(ao).length(0)}),Kr={id:Ed,name:v.string().min(1),display:v.strictObject({singular:v.string().optional(),plural:v.string().optional()}).nullish(),event_names:v.array(v.string()).default([]),model_markups:Zr,stripe_meter:v.strictObject({id:v.string(),event_name:v.string()}).nullish(),stripe_product_id:v.string().nullish()},co=e=>v.discriminatedUnion("type",[v.strictObject({...Kr,...e,type:v.literal("boolean"),config:v.null()}),v.strictObject({...Kr,...e,type:v.literal("metered"),config:Bd}),v.strictObject({...Kr,...e,type:v.literal("credit_system"),config:cc}),v.strictObject({...Kr,...e,type:v.literal("ai_credit_system"),config:so})]),ob=co({}),qd=v.strictObject({id:v.boolean(),type:v.boolean(),usage_type:v.boolean()}),zd={internal_id:v.uuid(),org_id:v.uuid(),created_at:v.number(),env:v.enum(["sandbox","live"]),archived:v.boolean(),project_id:v.uuid(),environment_id:v.uuid(),revision:v.number().int().nonnegative(),update_rules:qd},uc=co(zd),ab=v.strictObject({rows:v.array(uc).max(200),nextCursor:v.uuid().nullable()}),sb=v.strictObject({features:v.array(uc).max(500),limited:v.boolean()}),cb=v.union([co({action:v.literal("save"),internal_id:v.uuid().nullable(),revision:v.number().int().nonnegative()}),v.strictObject({action:v.enum(["archive","restore","delete"]),internal_id:v.uuid(),revision:v.number().int().nonnegative()})]);import{z as l}from"zod";import{z as N}from"zod";import{z as Ne}from"zod";function Nt(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,s){if(n(a))for(let[c,u]of Object.entries(a))c==="$elemMatch"?i(u,s):c==="$not"?r(u,s):c==="$all"&&Array.isArray(u)&&u.forEach(d=>r(d,s))}function i(a,s=""){if(n(a)){for(let[c,u]of Object.entries(a))if(["$and","$or","$nor"].includes(c)&&Array.isArray(u))u.forEach(d=>i(d,s));else if(c==="$not")i(u,s);else if(c==="$savedGroup"&&n(u))typeof u.attributeKey=="string"&&t.add(u.attributeKey);else if(!c.startsWith("$")){let d=s?`${s}.${c}`:c;t.add(d),r(u,d)}}}return i(e),[...t]}var Nd=Ne.enum(["active","inactive"]),Fd=Ne.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(s=>r(s,a+1));else if(i&&typeof i=="object")for(let[s,c]of Object.entries(i))["__proto__","constructor","prototype"].includes(s)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(c,a+1)}}return r(e,0),e},rt),Ud=Ne.strictObject({id:Ne.string().trim().min(1).max(255),name:Ne.string().trim().min(1).max(255),status:Nd,metadata:Fd}),fb=Ud.extend({internal_id:Ne.uuid(),project_id:Ne.uuid(),environment_id:Ne.uuid(),created_at:Ne.iso.datetime({offset:!0}),updated_at:Ne.iso.datetime({offset:!0})}),pc=Ne.union([Ne.strictObject({id:Ne.string().trim().min(1).max(255)}),Ne.strictObject({internalId:Ne.uuid()})]),Ab=Ne.enum(["customer","merchandise","context"]),hb=Ne.enum(["system","stored","request"]),gb=Ne.enum(["customer","merchandise","mixed"]),lc=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function uo(e,t={},n=new Set){if(Nt(e).some(lc))return!0;for(let r of Dt(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&lc(i.attributeKey)||i?.type==="condition"&&uo(i.condition,t,n))return!0}return!1}var Ib=N.enum(["draft","active","paused","archived"]),Ft=N.discriminatedUnion("type",[N.object({type:N.literal("percent"),percentOff:N.number().min(1).max(100).multipleOf(.01)}).strict(),N.object({type:N.literal("amount"),amountOffCents:N.number().int().min(1).max(1e8),currency:ce}).strict()]),at=N.discriminatedUnion("type",[N.object({type:N.literal("once")}).strict(),N.object({type:N.literal("repeating"),months:N.number().int().min(1).max(36)}).strict(),N.object({type:N.literal("forever")}).strict()]),dc=[N.object({type:N.literal("all")}).strict(),N.object({type:N.literal("plans"),planIds:N.array(N.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],Vd=N.discriminatedUnion("type",[...dc,N.strictObject({type:N.literal("merchandise"),scope:N.discriminatedUnion("type",[N.strictObject({type:N.literal("all")}),N.strictObject({type:N.literal("selected"),merchandiseIds:N.array(N.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),N.strictObject({type:N.literal("condition"),condition:Ht})])})]),lo=N.discriminatedUnion("type",[...dc,N.strictObject({type:N.literal("merchandise"),scope:N.strictObject({type:N.enum(["all","selected","condition"])})})]),Ld=N.strictObject({firstPurchaseOnly:N.boolean(),condition:Ht}),Ob=N.object({name:N.string().trim().min(1).max(80),description:N.string().max(500),discount:Ft,duration:at,appliesTo:Vd,eligibility:Ld,selfClaimEnabled:N.boolean().default(!1),startsAt:N.iso.datetime().nullable(),endsAt:N.iso.datetime().nullable(),totalLimit:N.number().int().min(1).max(1e6).nullable(),perCustomerLimit:N.number().int().min(1).max(10),grantWindowHours:N.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"]}).refine(e=>!uo(e.eligibility.condition),{message:"Customer eligibility cannot read merchandise; use merchandise applicability",path:["eligibility","condition"]}).refine(e=>e.appliesTo.type!=="merchandise"||e.duration.type==="once",{message:"Merchandise Coupons apply to one purchase",path:["duration"]}).refine(e=>e.appliesTo.type!=="merchandise"||!e.eligibility.firstPurchaseOnly,{message:"Merchant purchase eligibility requires trusted targeting attributes",path:["eligibility","firstPurchaseOnly"]}),wb=N.object({code:N.string().trim().transform(e=>e.toUpperCase()).pipe(N.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:N.number().int().min(1).max(1e6).nullable(),expiresAt:N.iso.datetime().nullable(),firstPurchaseOnly:N.boolean(),minimumAmountCents:N.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:ce.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Yn=N.object({id:N.uuid(),couponId:N.uuid(),status:N.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:N.iso.datetime(),expiresAt:N.iso.datetime(),coupon:N.object({name:N.string(),discount:Ft,duration:at,appliesTo:lo}).strict()}).strict(),mc=N.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var bc=l.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),po=l.string().regex(/^(0|[1-9]\d{0,14})$/),On=l.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),$d=l.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),er=$d,kt=we.refine(e=>/[1-9]/.test(e)),Ze=l.iso.datetime({offset:!0}),Qr=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"))},Gd=l.array(l.object({upTo:kt.nullable(),unitAmountMinor:bc,flatAmountMinor:l.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&&Qr(t.upTo)>Qr(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Kd=l.discriminatedUnion("kind",[l.object({kind:l.literal("flat"),units:kt,unitAmountMinor:bc}).strict(),l.object({kind:l.enum(["graduated","volume"]),units:kt,tiers:Gd}).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"),Hd=l.strictObject({interval:l.enum(["month","year"]),count:l.number().int().min(1).max(12),anchor:l.enum(["membership","calendar"])}),tr=l.object({currency:ce,pricing:Kd,billingCycle:Hd.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var fc={requestId:l.uuid(),productVersionId:l.uuid(),internal_feature_id:l.uuid(),currency:ce},yc=l.strictObject({interval:l.enum(["hour","day","week","month"]),intervalCount:l.number().int().min(1).max(12),limit:l.number().int().min(1).max(1e6)}),xc=l.discriminatedUnion("kind",[l.object({...fc,kind:l.literal("auto_topup"),threshold:Mi,quantity:kt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:yc.optional()}).strict(),l.object({...fc,kind:l.literal("postpaid"),maxAmountMinorPerPeriod:er,maxOutstandingMinor:er}).strict()]),Ac={productVersionId:l.uuid(),internal_feature_id:l.uuid(),currency:ce},Sc=l.discriminatedUnion("kind",[l.object({...Ac,kind:l.literal("auto_topup"),threshold:Mi,quantity:kt.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:yc.optional(),purchaseAmountMinor:er,purchaseUnits:kt}).strict(),l.object({...Ac,kind:l.literal("postpaid"),maxAmountMinorPerPeriod:er,maxOutstandingMinor:er,cashPrice:tr}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Jr=l.object({id:l.uuid(),terms:Sc,status:l.enum(["prepared","active","revoked","blocked"]),createdAt:Ze,acceptedAt:Ze.nullable(),effectiveAt:Ze.nullable(),revokedAt:Ze.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"),vc=l.object({authorizationId:l.uuid(),terms:Sc,setupUrl:l.url().nullable()}).strict(),Ic=l.object({authorizationId:l.uuid(),accepted:l.literal(!0)}).strict(),Oc=l.object({authorizationId:l.uuid(),requestId:l.uuid()}).strict(),wc=l.object({internal_feature_id:l.uuid(),entityId:l.uuid().nullable(),interval:l.enum(["day","week","month","year"]),anchor:l.enum(["billing_cycle","utc"]).optional(),basis:l.enum(["usage","credits"]),filter:_t.optional(),limit:we.nullable(),thresholds:l.array(l.number().positive().max(1)).max(8),includedThresholds:l.array(l.number().positive().max(1)).max(8).optional(),absoluteThresholds:l.array(kt).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&&Qr(t)>Qr(i)}),"Notification thresholds must increase"),Zd=wc.safeExtend({requestId:l.uuid()}),hc={control:l.literal("overage"),requestId:l.uuid(),internal_feature_id:l.uuid(),entityId:l.uuid().nullable()},Qd=l.discriminatedUnion("action",[l.strictObject({...hc,action:l.literal("set"),allowed:l.boolean().nullable(),overageLimit:we.nullable(),skipOverageBilling:l.boolean()}),l.strictObject({...hc,action:l.literal("remove")})]),jc=l.union([Zd,Qd]),Jd=l.strictObject({internal_feature_id:l.uuid(),entityId:l.uuid().nullable(),allowed:l.boolean().nullable(),overageLimit:we.nullable(),skipOverageBilling:l.boolean(),interval:l.enum(["day","week","month","year"]),startsAt:Ze,endsAt:Ze,used:l.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:l.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:l.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Wd=l.object({internal_feature_id:l.uuid(),entityId:l.uuid().nullable(),interval:l.enum(["day","week","month","year"]),anchor:l.enum(["billing_cycle","utc"]).optional(),basis:l.enum(["usage","credits"]),filter:_t.optional(),startsAt:Ze,endsAt:Ze,used:ft,reserved:ft,limit:we.nullable(),thresholds:l.array(l.number().positive().max(1)).max(8),notifiedThresholds:l.array(l.number().positive().max(1)).max(1024),includedThresholds:l.array(l.number().positive().max(1)).max(8).optional(),includedAllowance:l.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:l.array(l.number().positive().max(1)).max(1024).optional(),absoluteThresholds:l.array(kt).max(8).optional(),notifiedAbsoluteThresholds:l.array(kt).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||we.safeParse(e.used).success&&we.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Xd=l.object({authorizationId:l.uuid(),status:l.enum(["idle","pending","blocked"]),taskId:l.uuid().nullable(),invoiceId:l.uuid().nullable(),hostedInvoiceUrl:l.url().nullable(),purchaseCount:l.number().int().nonnegative(),purchaseWindowEndsAt:Ze.nullable(),attemptCount:l.number().int().nonnegative(),failedAttemptCount:l.number().int().nonnegative(),suspendedAt:Ze.nullable(),nextAttemptAt:Ze.nullable(),failureReason:l.string().min(1).max(240).nullable()}).strict(),_c=l.object({internal_feature_id:l.uuid().optional(),entityId:l.uuid().optional()}).strict(),mo=l.object({authorizations:l.array(Jr).max(100),limits:l.array(wc).max(100),overages:l.array(Jd).max(100).optional(),windows:l.array(Wd).max(200),autoTopups:l.array(Xd).max(100),limited:l.boolean()}).strict(),Yd=l.object({id:l.uuid(),internal_feature_id:l.uuid(),productVersionId:l.uuid(),authorizationId:l.uuid(),entityId:l.uuid().nullable(),units:we,amountMinor:On,cashPrice:tr}).strict(),nr=l.object({id:l.uuid(),sourceKind:l.enum(["product","usage","manual"]),providerInvoiceId:l.string().min(1).max(240).nullable(),status:l.enum(["accruing","open","pending","paid","failed","void"]),currency:ce,startsAt:Ze.nullable(),endsAt:Ze.nullable(),amountMinor:l.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:l.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:po,paidAmountMinor:po,refundedAmountMinor:po,createdAt:Ze,hostedInvoiceUrl:l.url().nullable(),adjustment:l.object({originalInvoiceId:l.uuid(),amountMinor:l.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:Ze.nullable(),reason:l.string().min(1).max(500).optional()}).strict().nullable(),lines:l.array(Yd).max(100),linesLimited:l.boolean()}).strict(),Pc=l.object({invoiceId:l.uuid(),accepted:l.literal(!0)}).strict(),Cc=l.strictObject({requestId:l.uuid(),originalInvoiceId:l.uuid(),amountMinor:l.string().regex(/^[1-9]\d{0,8}$/).refine(e=>/^[1-9]\d{0,8}$/.test(e)&&BigInt(e)<=200000000n,"Supplemental amount exceeds the bounded minor amount"),reason:l.string().trim().min(1).max(500)}),kc=l.object({after:l.uuid().nullable(),limit:l.number().int().min(1).max(100)}).strict(),Rc=l.object({rows:l.array(nr).max(100),nextCursor:l.uuid().nullable()}).strict(),gc=l.strictObject({id:l.string(),coupon:l.string(),start:l.number().nonnegative(),end:l.number().nullable()}),em=l.strictObject({subscriptionId:l.string(),customerId:l.string(),accountId:l.string(),sourceItems:l.array(l.strictObject({id:l.string(),price_id:l.string(),quantity:l.number().int(),discounts:l.array(gc).optional()})).max(100),items:l.array(l.strictObject({id:l.string(),price:l.string(),quantity:l.number().int(),discounts:l.array(l.strictObject({coupon:l.string().optional(),terms:l.strictObject({id:l.string(),name:l.string().optional(),percent_off:l.number().optional(),amount_off:l.number().optional(),currency:l.string().optional(),duration:l.enum(["once","forever","repeating"]),duration_in_months:l.number().optional()}).optional(),discount:l.string().optional(),receipt:gc.optional()})).max(20)})).max(100)}),Ec=l.strictObject({membershipId:l.uuid(),requestId:l.uuid(),grantIds:l.array(l.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Dc=l.strictObject({membershipId:l.uuid(),operationId:l.uuid(),status:l.enum(["pending","effective"]),execution:em.nullable(),grants:l.array(l.strictObject({id:l.uuid(),couponId:l.uuid(),name:l.string(),discount:Ft,duration:at,startedAt:Ze.nullable()})).max(20)});import{z as rr}from"zod";var Tc=rr.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Mc=rr.number().int().min(1).max(1e3),Wr=rr.object({cap:we.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:rr.number().positive().max(1e4).nullable(),cycles:rr.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as Ut}from"zod";var Bc=Ut.strictObject({itemKey:Ut.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:Ut.uuid(),includedAmount:Ut.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Ut.number().int().min(0).max(1e4),terms:Ja,pricing:Qa.optional(),unitAmountMinor:Ut.number().int().min(0).max(1e8),productId:Ut.string().min(1).max(255).nullable(),priceId:Ut.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{Wa(e.includedAmount,e.terms.units,e.quantity),Or({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 ae}from"zod";var Yt=ae.iso.datetime({offset:!0}),qc=we.refine(e=>/[1-9]/.test(e)),zc=ae.strictObject({interval:Tc.exclude(["lifetime"]),count:Mc}),tm=ae.strictObject({action:ae.literal("create"),requestId:ae.uuid(),internal_feature_id:ae.uuid(),entityId:ae.uuid().nullable(),amount:qc.nullable(),expiresAt:Yt.nullable(),reset:zc.nullable(),rollover:Wr.nullable(),nextResetAt:Yt.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"),Nc=ae.discriminatedUnion("action",[tm,ae.strictObject({action:ae.literal("update"),requestId:ae.uuid(),grantId:ae.uuid(),revision:ae.number().int().nonnegative(),amount:qc.nullable(),expiresAt:Yt.nullable(),rollover:Wr.nullable(),nextResetAt:Yt.nullable()}),ae.strictObject({action:ae.enum(["add","subtract","set_remaining"]),requestId:ae.uuid(),grantId:ae.uuid(),revision:ae.number().int().nonnegative(),amount:we}),ae.strictObject({action:ae.literal("revoke"),requestId:ae.uuid(),grantId:ae.uuid(),revision:ae.number().int().nonnegative()})]),fo=ae.strictObject({id:ae.uuid(),internal_feature_id:ae.uuid(),entityId:ae.uuid().nullable(),amount:we.nullable(),reset:zc.nullable(),rollover:Wr.nullable(),nextResetAt:Yt.nullable(),startsAt:Yt,expiresAt:Yt.nullable(),revision:ae.number().int().nonnegative(),revoked:ae.boolean(),available:ft,held:ft,spent:ft}),Fc=ae.strictObject({customerId:ae.uuid(),after:ae.uuid().nullable(),limit:ae.number().int().min(1).max(100)}),Uc=ae.strictObject({rows:ae.array(fo).max(100),nextCursor:ae.uuid().nullable()});import{z as F}from"zod";var vt=F.iso.datetime({offset:!0}),Vc=F.strictObject({invoiceId:F.uuid(),after:F.string().min(1).max(180).nullable(),limit:F.number().int().min(1).max(100)}),nm=F.strictObject({kind:F.literal("product"),key:F.string(),productVersionId:F.uuid(),productName:F.string(),itemKey:F.string(),entityId:F.uuid().nullable(),quantity:F.number().positive(),subtotalMinor:F.string().regex(/^-?\d+$/),discountMinor:F.string().regex(/^\d+$/),taxMinor:F.string().regex(/^-?\d+$/).nullable(),totalMinor:F.string().regex(/^-?\d+$/),startsAt:vt.nullable(),endsAt:vt.nullable(),providerLineId:F.string().nullable(),providerItemId:F.string()}),Lc=F.strictObject({invoice:nr,items:F.array(F.discriminatedUnion("kind",[nm,F.strictObject({kind:F.literal("invoice_credit"),key:F.string(),internal_feature_id:F.uuid(),internal_credit_feature_id:F.uuid(),name:F.string(),units:we,reserved:we,amountMinor:On,grossAmountMinor:On,creditsAppliedMinor:On,properties:_t,cashPrice:tr,providerItemId:F.string().nullable(),creditProviderItemId:F.string().nullable()}),F.strictObject({kind:F.literal("usage"),key:F.string(),internal_feature_id:F.uuid(),name:F.string(),units:we,reserved:we,amountMinor:On,cashPrice:tr})])).max(100),nextCursor:F.string().min(1).max(180).nullable()}),rm=F.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Ao=F.strictObject({from:vt,to:vt,entityId:F.uuid().optional(),snapshotAt:vt.nullable(),after:F.strictObject({at:vt,id:F.uuid(),position:F.number().int().nonnegative()}).nullable(),limit:F.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"),$c=F.strictObject({customerId:F.uuid(),entityId:F.uuid().nullable(),from:vt,to:vt,snapshotAt:vt,totals:F.array(F.strictObject({internal_credit_feature_id:F.uuid(),name:F.string(),consumed:ft,refunded:ft,net:rm})).max(1e3),rows:F.array(F.strictObject({operationId:F.uuid(),position:F.number().int().nonnegative(),kind:F.enum(["consume","confirm","refund"]),originalId:F.uuid().nullable(),occurredAt:vt,internal_feature_id:F.uuid(),entitlementName:F.string(),sourceId:F.uuid(),internal_credit_feature_id:F.uuid(),creditName:F.string(),units:ns,amount:ft,pricing:F.array(ts).max(12),properties:_t})).max(100),nextCursor:Ao.shape.after});import{z as K}from"zod";var Kc=K.object({customerId:K.uuid()}).strict(),Hc=K.discriminatedUnion("action",[K.object({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("assign"),poolId:K.uuid(),memberCustomerId:K.uuid()}).strict(),K.strictObject({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("assign_entity"),poolId:K.uuid(),entityId:K.uuid()}),K.object({customerId:K.uuid(),requestId:K.uuid(),action:K.literal("release"),poolId:K.uuid(),slotId:K.uuid()}).strict()]),ir=K.number().int().nonnegative(),ho=K.iso.datetime({offset:!0}),go=K.strictObject({internalId:K.uuid(),id:K.string(),name:K.string().nullable(),version:K.number().int().positive()}),Gc=K.enum(["active","past_due"]),bo=K.strictObject({customerId:K.uuid(),licenses:K.array(K.strictObject({id:K.uuid(),linkId:K.uuid(),parent:K.strictObject({customerProductId:K.uuid(),status:Gc,product:go}),product:go,planLicense:K.strictObject({id:K.uuid(),prepaidOnly:K.boolean(),isCustom:K.boolean()}).nullable(),granted:ir,included:ir,paidQuantity:ir,usage:ir,remaining:ir,createdAt:ho}).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:K.array(K.strictObject({id:K.uuid(),linkId:K.uuid(),status:Gc,product:go,entity:K.strictObject({internalId:K.uuid(),id:K.string().nullable(),name:K.string().nullable()}).nullable(),beneficiary:K.strictObject({internalId:K.uuid(),id:K.string().nullable(),name:K.string().nullable()}).nullable(),startedAt:ho.nullable(),endedAt:ho.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:K.boolean()});import{z as G}from"zod";var or=G.enum(["email","sms","voice","push"]),Wb=G.enum(["resend","twilio","fcm","apns"]);var Xb=G.string().regex(/^\+[1-9]\d{1,14}$/),im=G.enum(["email_recipient","sms_segment","voice_second","push_device"]);var om=G.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),am=G.strictObject({subject:om,html:G.string().min(1).max(131072).optional(),text:G.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),sm=G.strictObject({body:G.string().min(1).max(1600).refine(e=>e.trim().length>0)}),cm=G.strictObject({text:G.string().trim().min(1).max(4e3),language:G.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:G.number().int().min(1).max(900)}),um=G.record(G.string().min(1).max(64),G.string().max(256)).refine(e=>Object.keys(e).length<=20&&Object.keys(e).every(t=>!/^(?:indiana_|google\.|gcm\.)/i.test(t)&&t!=="aps"),"Push data contains reserved fields or too many entries"),lm=G.strictObject({title:G.string().trim().min(1).max(200),body:G.string().trim().min(1).max(2e3),url:G.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:um.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Zc=G.discriminatedUnion("channel",[G.strictObject({channel:G.literal("email"),content:am}),G.strictObject({channel:G.literal("sms"),content:sm}),G.strictObject({channel:G.literal("voice"),content:cm}),G.strictObject({channel:G.literal("push"),content:lm})]),Qc=G.strictObject({requestId:G.uuid(),customerId:G.uuid(),connectionId:G.uuid().optional(),message:Zc,expiresAt:G.iso.datetime({offset:!0})}),pm=G.array(G.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),dm=G.discriminatedUnion("kind",[G.strictObject({kind:G.literal("all")}),G.strictObject({kind:G.literal("customers"),customerIds:pm})]),Yb=G.strictObject({name:G.string().trim().min(1).max(120),connectionId:G.uuid().optional(),message:Zc,audience:dm,frequencyLimit:G.number().int().min(1).max(100)}),Jc=G.strictObject({requestId:G.uuid(),channel:or,state:G.enum(["allowed","denied"]),expectedRevision:G.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),Wc=G.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Xc=G.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),ey=G.strictObject({meter:im,estimatedUnits:G.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:G.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Yc}from"zod";var wn={funnelId:Yc.uuid().optional(),funnelVersionId:Yc.uuid().optional()};import{z as je}from"zod";import{z as le}from"zod";import{z as xe}from"zod";var oy=xe.discriminatedUnion("action",[xe.strictObject({action:xe.literal("create"),couponId:xe.uuid(),productBindingId:xe.uuid(),storeOfferId:xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:xe.enum(["introductory","promotional"])}),xe.strictObject({action:xe.literal("set_enabled"),id:xe.uuid(),revision:xe.number().int().nonnegative(),enabled:xe.boolean()})]),ay=xe.array(xe.strictObject({id:xe.uuid(),couponId:xe.uuid(),productBindingId:xe.uuid(),storeOfferId:xe.string().min(1).max(255).nullable(),storeOfferType:xe.enum(["introductory","promotional"]),enabled:xe.boolean(),revision:xe.number().int().nonnegative()})).max(500),jn=xe.strictObject({offerKind:xe.enum(["none","introductory","promotional"]),offerId:xe.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:xe.number().int().min(0).max(1e8),trialDays:xe.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"})}),sy=xe.record(xe.uuid(),jn).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var yo=le.object({type:le.literal("native_purchase"),receiptId:le.uuid(),orderId:le.uuid(),productVersionId:le.uuid(),provider:le.enum(["apple","google"]),productId:le.string().min(1).max(255),productKind:ls,replacement:le.strictObject({sourceOrderId:le.uuid(),sourceProductId:le.string().min(1).max(255),policy:le.enum(["apple_store","google_full_price"]),sourceAccountTokens:le.array(le.uuid()).max(50)}).nullable(),appAccountToken:le.uuid().optional(),obfuscatedAccountId:le.string().min(1).max(64).optional(),obfuscatedProfileId:le.uuid().optional(),basePlanId:le.string().min(1).max(255).optional(),offerId:le.string().min(1).max(255).optional(),offerKind:le.enum(["none","introductory","promotional"]),currency:ce,catalogAmountMinor:le.number().int().nonnegative().max(1e8),discountMinor:le.number().int().nonnegative().max(1e8),trialDays:le.number().int().min(1).max(730).nullable(),seatBundle:le.array(le.strictObject({key:le.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:le.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:le.strictObject({offerId:le.string().min(1).max(255),keyId:le.string().min(1).max(255),nonce:le.uuid(),signature:le.string().min(1).max(1024),timestamp:le.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 o}from"zod";import{z as ee}from"zod/v4";import{z as mm}from"zod/v4";var fm=mm.registry(),{BillingInterval:eu}=(()=>{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:Am}=(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')."})})}))(ee),{withSpecDefault:hm}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(fm),{COMMON:tu}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:gm}={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:bm}=(e=>({COMMON_SET:new Set(e)}))(tu),{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:ru}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:ym}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(ee),{Infinite:xm}={Infinite:"inf"},{TierBehavior:Sm}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:iu}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:vm}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Im}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Om}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:wm}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(ee),{ApiCreditTierSchema:ou}=(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."})})}))(ee),{VIOLATION_MESSAGES:jm}={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:au}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(ee),{ModelMarkupsSchema:_m}=((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()}))(ee,au),{InvoiceUsageEntrySchema:Pm}=(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()}))(ee),{AttachDiscountSchema:su}=(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."})}))(ee),{CustomLineItemSchema:Cm}=(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."})})}))(ee),{UnixMsTimestampSchema:km}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(ee),{CreateInvoicePreviewLineSchema:Rm}=(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()})}))(ee),{ReissueInvoiceParamsSchema:cu}=(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."})})}))(ee),{InvoiceModeParamsSchema:en}=(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."})}))(ee),{InvoiceTemplateSchema:Em}=(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."})})}))(ee),{BasePriceSchema:Dm}=((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."})})}))(ee,eu,Am),{CURRENCY_CODES:Tm}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(tu,gm,bm),{ApiPriceProcessorsSchema:uu}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(ee,ym),{AllocatedBillingFieldSchema:Mm}=((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'."})}))(ee,vm),{CreditDimensionNameSchema:Bm}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(ee,Im,Om),{ApiCreditMatchSchema:lu}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(wm),{findCreditTierViolations:qm}=(e=>({findCreditTierViolations:n=>{let r=[],i=(s,c)=>r.push({index:s,reason:c,message:e[c]}),a=0;for(let[s,c]of n.entries()){let u=s===n.length-1;if(c==="inf"){u||i(s,"non_final_infinity");continue}(!Number.isFinite(c)||c<=a)&&i(s,"not_increasing"),a=c,u&&i(s,"final_not_infinity")}return r}}))(jm),{ApiCreditMultiplierSchema:zm}=((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."})}))(ee,lu),{ProviderMarkupsSchema:Nm}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(ee,au),{InvoiceFeatureQuantitySchema:pu}=((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."})}))(ee,iu,Pm),{CreateInvoicePreviewSchema:xo}=((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()})}))(ee,Rm),{SUPPORTED_SET:Fm}=(e=>({SUPPORTED_SET:new Set(e)}))(Tm),{ApiCreditDimensionBaseSchema:Um}=((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."})})}))(ee,lu),{refineGraduatedTiers:du}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:s}of i)r.addIssue({code:"custom",message:s,path:["tiers",a,"to"]})}}))(qm),{ApiFeatureMarkupsOverrideSchema:Vm}=((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."})})}))(ee,Nm,_m),{isValidCurrencyCode:Lm}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Fm),{ApiCreditDimensionSchema:$m}=((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()])}))(ee,Um,ou,du),{CurrencyCodeSchema:mu}=((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')."})}))(ee,Lm),{AdditionalCurrencyTierSchema:Gm}=((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"]})}))(ee,mu),{ApiCreditSchemaItemBaseSchema:fu}=((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."})})}))(ee,Bm,$m,zm),{ApiFlatCreditSchemaItemSchema:Km}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(fu,ee),{AdditionalCurrencyPriceSchema:Hm}=((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."})})}))(ee,mu),{AdditionalCurrencyTierArraySchema:Zm}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(ee,Gm,nu,ru),{ApiGraduatedCreditSchemaItemSchema:Qm}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(fu,ee,ou,du),{AdditionalCurrencyPriceArraySchema:Au}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(ee,Hm,nu,ru),{ApiUsageTierWithCurrenciesSchema:Jm}=((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()}))}))(ee,xm,Zm),{ApiCreditSchemaItemSchema:Wm}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(ee,Qm,Km),{BasePriceParamsSchema:Xm}=((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."})}))(Dm,hm,ee,Au),{PlanItemPriceParamsSchema:Ym}=((e,t,n,r,i,a,s)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(u=>u??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:s,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."})})}))(ee,Au,Jm,Sm,eu,iu,Mm),{ApiFeatureOverrideSchema:ef}=((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."})})}))(ee,Wm,Vm),{InvoiceBasePriceParamsSchema:hu}=((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()}))(Xm,uu),{InvoiceItemPriceParamsSchema:tf}=((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()}))(Ym,uu),{InvoiceLicenseQuantitySchema:nf}=((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()}))(ee,hu,pu),{InvoiceCustomizeItemSchema:rf}=((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()}))(ee,tf,ef),{InvoiceCustomizeSchema:of}=((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."})}))(ee,hu,rf),{InvoicePlanParamsSchema:af}=((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()}))(ee,of,pu,nf,su),{CreateInvoiceParamsSchema:_n}=((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(s=>s.period_start===void 0==(s.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(s=>s.period_start===void 0||s.period_end===void 0||s.period_end>s.period_start,{message:"period_end must be after period_start."})}))(ee,af,Cm,su,km);var yu=o.strictObject({requestId:o.uuid(),predecessorOperationId:o.uuid().optional(),invoiceMode:en.optional(),entityId:o.uuid().optional(),billingSubscriptionId:o.uuid().optional(),newBillingSubscription:o.literal(!0).optional(),offerId:o.uuid().optional(),nativeOffer:jn.optional(),plans:o.array(o.strictObject({productVersionId:o.uuid(),seatQuantities:o.record(Gr,o.number().int().min(0).max(1e4)).optional(),featureQuantities:o.record(o.uuid(),o.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:o.enum(["stripe","apple","google","merchant"]),currency:ce}).refine(e=>!e.offerId||!e.billingSubscriptionId&&(["stripe","merchant"].includes(e.provider)||e.nativeOffer!==void 0),"Held offers apply to new purchases; existing subscriptions use billing coupons").refine(e=>!e.nativeOffer||["apple","google"].includes(e.provider)&&e.plans.length===1,"A store selection applies to exactly one native SKU").refine(e=>!e.newBillingSubscription||["stripe","merchant"].includes(e.provider)&&!e.billingSubscriptionId,"A new billing subscription has no existing subscription target").refine(e=>!e.invoiceMode?.enabled||e.provider==="stripe"&&!e.entityId,"Invoice mode requires a Stripe subscription without an Entity target"),nn=o.strictObject({operationId:o.uuid()}),Fe=o.number().int().min(0).max(1e8),sf=o.strictObject({lineId:o.uuid(),productVersionId:o.uuid(),productName:o.string().min(1).max(80),interval:o.enum(["free","week","month","year","one_time"]),intervalCount:o.number().int().min(1).max(156).optional(),baseAmountMinor:Fe,seats:o.array(o.strictObject({key:Gr,quantity:o.number().int().min(0).max(1e4),includedQuantity:o.number().int().min(0).max(1e4),maximumQuantity:o.number().int().min(0).max(1e4),unitAmountMinor:Fe})).max(20),prepaid:o.array(Bc).max(100).optional(),catalogAmountMinor:Fe,trial:o.strictObject({days:o.number().int().min(1).max(730),cardRequired:o.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+Or({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"),xu=o.string().regex(/^[A-Za-z0-9_-]{1,200}$/),cf=o.strictObject({id:xu,name:o.string().min(1).max(40),percent_off:o.number().gt(0).max(100).optional(),amount_off:o.number().int().positive().optional(),currency:o.string().regex(/^[a-z]{3}$/).optional(),duration:o.enum(["once","repeating","forever"]),duration_in_months:o.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"),uf=o.strictObject({subscriptionId:o.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:o.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:o.array(o.strictObject({id:o.string(),price_id:o.string(),quantity:o.number().int().nonnegative(),discounts:o.array(o.strictObject({id:o.string(),coupon:o.string(),start:o.number(),end:o.number().nullable()})).optional()})).min(1).max(100),prorationDate:o.number().int().nonnegative(),amountMinor:o.number().int().positive(),periodStartMs:o.number(),periodEndMs:o.number()}),Su=o.strictObject({invoiceMode:en.optional(),append:uf.optional(),provider:o.literal("stripe"),executor:o.enum(["indiana","merchant"]),accountId:o.string().regex(/^acct_[A-Za-z0-9]+$/),mode:o.enum(["payment","subscription"]),lineItems:o.array(o.strictObject({price:o.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:o.number().int().min(1).max(1e4),priceId:o.uuid(),productName:o.string().min(1).max(80),amountMinor:o.number().int().min(0).max(1e8),currency:o.string().regex(/^[a-z]{3}$/),interval:o.enum(["week","month","year","one_off"]),intervalCount:o.number().int().min(1).max(52),slot:o.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:o.strictObject({mode:o.enum(["graduated","volume"]),tiers:o.array(o.strictObject({upTo:o.number().int().min(1).max(1e6).nullable(),unitAmountMinor:o.number().int().min(0).max(1e8),flatAmountMinor:o.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:o.array(o.strictObject({coupon:xu,terms:cf})).max(1),trialPeriodDays:o.number().int().min(1).max(730).nullable(),metadata:o.strictObject({grooveCheckoutId:o.uuid(),grooveCustomerId:o.uuid()}),expiresAt:o.iso.datetime({offset:!0})}),Pn=o.strictObject({operationId:o.uuid(),entityId:o.uuid().nullable(),billingSubscriptionId:o.uuid().nullable(),discount:o.strictObject({offerId:o.uuid(),couponId:o.uuid(),discount:Ft,duration:at,amountMinor:Fe,allocations:o.array(o.strictObject({productVersionId:o.uuid(),amountMinor:Fe})).min(1).max(20),expiresAt:o.iso.datetime({offset:!0})}).nullable(),charge:o.strictObject({effectiveAt:o.iso.datetime({offset:!0}),periodEndsAt:o.iso.datetime({offset:!0}),debitMinor:Fe,discountMinor:Fe,taxMinor:Fe,totalMinor:Fe}).nullable(),expiresAt:o.iso.datetime({offset:!0}),provider:o.enum(["stripe","apple","google","merchant"]),nativeOffer:jn.optional(),currency:ce,lines:o.array(sf).min(1).max(20),catalogAmountMinor:Fe,automaticTax:o.boolean(),execution:o.union([Su,Er]).nullable()}).refine(e=>e.provider==="merchant"?e.execution?.provider==="merchant"&&e.execution.operationId===e.operationId&&e.execution.catalogAmountMinor===e.catalogAmountMinor&&e.execution.currency===e.currency&&Date.parse(e.execution.expiresAt)<=Date.parse(e.expiresAt)&&e.execution.trialPeriodDays===(e.lines[0]?.trial?.days??null)&&e.execution.discount?.grantId===e.discount?.offerId:e.provider==="stripe"?e.execution?.provider!=="merchant"&&(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&&(["stripe","merchant"].includes(e.provider)||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)&&(["stripe","merchant"].includes(e.provider)?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"),Cn=o.strictObject({operationId:o.uuid(),orderId:o.uuid(),append:o.boolean().optional(),invoiceMode:o.boolean().optional(),status:o.enum(["pending","complete","cancelled","failed"]),executor:o.enum(["indiana","merchant"]),checkoutUrl:o.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:o.union([Su,Er]).nullable(),currency:ce,catalogAmountMinor:Fe,taxMinor:Fe,totalMinor:o.number().int().min(0).max(2e8).nullable(),quoteFinalized:o.boolean(),nativePurchase:yo.nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),quote:Pn.optional(),merchantExecution:Qt.nullable().optional(),problem:Qn.nullable().optional(),authority:qr.optional()}).refine(e=>(e.checkoutUrl===null||e.executor==="indiana"||e.merchantExecution?.type==="purchase")&&(e.execution===null||e.executor==="merchant"),"Only Indiana-executed purchases carry a Checkout URL and only record-only purchases carry execution instructions"),Yr=o.strictObject({enabled:o.literal(!0),featureIds:o.array(o.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),vu=o.strictObject({requestId:o.uuid(),invoiceMode:en.optional(),membershipId:o.uuid(),carryOverBalances:Yr.optional(),carryOverUsages:Yr.optional(),membershipIds:o.array(o.uuid()).min(1).max(20).optional(),prorationBehavior:o.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:o.enum(["immediate","renewal","store"]),change:o.discriminatedUnion("type",[o.strictObject({type:o.literal("plan"),productVersionId:o.uuid()}),o.strictObject({type:o.literal("seats"),licenseKey:Gr,quantity:o.number().int().min(0).max(1e4)}),o.strictObject({type:o.literal("quantity"),internal_feature_id:o.uuid(),quantity:o.number().int().min(0).max(1e4)}),o.strictObject({type:o.literal("cancel")}),o.strictObject({type:o.literal("uncancel")}),o.strictObject({type:o.literal("billing_cycle"),billingCycleAnchor:o.union([o.literal("now"),o.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"),Xr=o.string().regex(/^price_[A-Za-z0-9]+$/),gu=o.strictObject({grooveUpdateId:o.uuid(),grooveCustomerId:o.uuid()}),bu=o.strictObject({price:Xr.nullable(),priceId:o.uuid().optional(),quantity:o.number().int().min(0).max(1e4)}),Iu=o.strictObject({provider:o.literal("stripe"),invoiceMode:en.optional(),executor:o.enum(["indiana","merchant"]),accountId:o.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:o.string().regex(/^sub_[A-Za-z0-9]+$/),action:o.enum(["update","cancel","schedule","release"]),update:o.strictObject({items:o.array(bu).max(20),remove:o.array(Xr).max(20),restoreItems:o.array(o.strictObject({price:Xr,quantity:o.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:o.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:o.number().int().positive().optional(),paymentBehavior:o.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:o.boolean().optional(),clearCancelAt:o.literal(!0).optional(),billingCycleAnchorNow:o.literal(!0).optional(),metadata:gu}).nullable(),cancel:o.strictObject({prorate:o.literal(!1),invoiceNow:o.literal(!1)}).nullable(),schedule:o.strictObject({currentItems:o.array(o.strictObject({price:Xr,quantity:o.number().int().min(0).max(1e4)})).max(20),nextItems:o.array(bu).min(1).max(20),switchAt:o.number().int().positive(),interval:o.enum(["week","month","year"]),intervalCount:o.number().int().min(1).max(52),resetBillingCycleAnchor:o.literal(!0).optional(),metadata:gu}).nullable(),release:o.strictObject({schedule:o.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:o.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"),ei=o.strictObject({carryOverBalances:Yr.optional(),carryOverUsages:Yr.optional(),operationId:o.uuid(),membershipId:o.uuid(),productVersionId:o.uuid(),timing:o.enum(["immediate","renewal"]),effectiveAt:o.iso.datetime({offset:!0}),expiresAt:o.iso.datetime({offset:!0}),currency:ce,creditMinor:Fe,debitMinor:Fe,discountMinor:Fe,taxMinor:Fe,totalMinor:Fe,retainedProductVersionIds:o.array(o.uuid()).max(19),execution:o.union([Iu,Dr])}),lf=o.strictObject({operationId:o.uuid(),invoiceMode:o.boolean().optional(),membershipId:o.uuid(),productVersionId:o.uuid(),status:o.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:o.enum(["immediate","renewal"]),effectiveAt:o.iso.datetime({offset:!0}),checkoutUrl:o.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:o.enum(["indiana","merchant"]),execution:o.union([Iu,Dr]).nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Qt.nullable().optional(),problem:Qn.nullable().optional(),quote:ei.optional(),authority:qr.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),pf=o.strictObject({operationId:o.uuid(),membershipId:o.uuid(),productVersionId:o.uuid(),timing:o.literal("store"),effectiveAt:o.null(),expiresAt:o.iso.datetime({offset:!0}),currency:ce,creditMinor:o.null(),debitMinor:o.null(),discountMinor:o.null(),taxMinor:o.null(),totalMinor:o.null(),retainedProductVersionIds:o.array(o.uuid()).max(19),store:o.strictObject({provider:o.enum(["apple","google"]),productId:o.string().min(1).max(255),catalogAmountMinor:Fe,policy:o.enum(["apple_store","google_full_price"])})}),df=o.strictObject({operationId:o.uuid(),membershipId:o.uuid(),productVersionId:o.uuid(),status:o.enum(["prepared","pending","effective","cancelled","failed"]),timing:o.literal("store"),effectiveAt:o.iso.datetime({offset:!0}).nullable(),checkoutUrl:o.null(),nativePurchase:yo.nullable()}),Ou=o.union([ei,pf]),So=o.union([lf,df]),ar=o.number().int().positive().max(2e8),tn=o.number().int().min(0).max(2e8),wu=o.strictObject({requestId:o.uuid(),invoiceId:o.uuid(),mode:o.enum(["full","partial"]),amountMinor:ar.optional(),entitlementAction:o.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),ju=o.strictObject({provider:o.literal("stripe"),executor:o.enum(["indiana","merchant"]),accountId:o.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:o.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:ar,currency:o.string().regex(/^[a-z]{3}$/),metadata:o.strictObject({indianaRefundId:o.uuid()}),idempotencyKey:o.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:o.array(o.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),vo=o.strictObject({operationId:o.uuid(),invoiceId:o.uuid(),providerInvoiceId:o.string().min(1).max(200),currency:ce,paidMinor:tn,refundedMinor:tn,pendingMinor:tn,amountMinor:ar,mode:o.enum(["full","partial"]),entitlementAction:o.enum(["retain","revoke"]),revokes:o.strictObject({customerProductIds:o.array(o.uuid()).max(100),subscriptionIds:o.array(o.string().min(1).max(200)).max(20)}),execution:o.union([ju,Tr]),expiresAt:o.iso.datetime({offset:!0})}).refine(e=>e.amountMinor<=e.paidMinor-e.refundedMinor-e.pendingMinor&&e.execution.amountMinor===e.amountMinor&&(e.execution.provider==="merchant"?e.execution.merchantInvoiceId===e.providerInvoiceId&&e.execution.operationId===e.operationId&&e.execution.currency===e.currency: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"),ti=o.strictObject({operationId:o.uuid(),invoiceId:o.uuid(),providerInvoiceId:o.string().min(1).max(200),status:o.enum(["quoted","pending","succeeded","failed","expired"]),executor:o.enum(["indiana","merchant"]),currency:ce,amountMinor:ar,mode:o.enum(["full","partial"]),entitlementAction:o.enum(["retain","revoke"]),refundId:o.string().min(1).max(200).nullable(),quote:vo.optional(),execution:o.union([ju,Tr]).nullable(),confirmedAt:o.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Qt.nullable().optional(),problem:Qn.nullable().optional(),authority:qr.optional(),failureReason:o.string().min(1).max(200).nullable(),createdAt:o.iso.datetime({offset:!0}),completedAt:o.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"),_y=o.strictObject({invoiceId:o.uuid(),currency:ce,paidMinor:tn,refundedMinor:tn,pendingMinor:tn,refundableMinor:tn,executor:o.enum(["indiana","merchant"]).nullable(),canRefund:o.boolean(),operations:o.array(ti).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),Py=o.strictObject({requestId:o.uuid(),mode:o.enum(["full","partial"]),amountMinor:ar.optional(),entitlementAction:o.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 _u=je.strictObject({requestId:je.uuid(),targets:je.array(je.strictObject({membershipId:je.uuid(),action:je.enum(["cancel","uncancel"]),timing:je.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"),ni=je.strictObject({batchId:je.uuid()}),mf=je.strictObject({operationId:je.uuid(),membershipIds:je.array(je.uuid()).min(1).max(20),provider:je.enum(["stripe","apple","google"]),action:je.enum(["cancel","uncancel"]),timing:je.enum(["immediate","renewal"]),status:je.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ei.nullable(),managementUrl:je.url().nullable(),failureCode:je.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),sr=je.strictObject({batchId:je.uuid(),ready:je.boolean(),status:je.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:je.iso.datetime({offset:!0}),acceptedAt:je.iso.datetime({offset:!0}).nullable(),groups:je.array(mf).min(1).max(100)});import{z as re}from"zod";var ff=re.string().trim().min(1).max(240),Io={requestId:re.uuid(),reason:ff},ri=re.discriminatedUnion("action",[re.strictObject({...Io,action:re.literal("start"),productVersionId:re.uuid(),entityId:re.uuid().optional(),days:re.number().int().min(1).max(730).optional()}),re.strictObject({...Io,action:re.literal("extend"),membershipId:re.uuid(),days:re.number().int().min(1).max(730)}),re.strictObject({...Io,action:re.literal("end"),membershipId:re.uuid()})]),Pu=re.strictObject({operationId:re.uuid()}),Cu=re.iso.datetime({offset:!0}),Af=re.strictObject({provider:re.literal("stripe"),executor:re.enum(["indiana","merchant"]),accountId:re.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:re.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:re.union([re.literal("now"),Cu]),prorationBehavior:re.literal("none")}),Oo=re.strictObject({operationId:re.uuid(),action:re.enum(["start","extend","end"]),status:re.enum(["pending","effective"]),managedBy:re.enum(["indiana","stripe"]),membershipIds:re.array(re.uuid()).min(1).max(20),endsAt:Cu.nullable(),execution:Af.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"),Ty=re.strictObject({groupId:re.uuid(),productVersionId:re.uuid(),enabled:re.boolean()});import{z as be}from"zod";var ku=be.strictObject({requestId:be.uuid(),currency:ce,makeDefault:be.boolean()}),Ru=be.strictObject({setupId:be.uuid()}),hf=be.strictObject({provider:be.literal("stripe"),executor:be.literal("merchant"),accountId:be.string().regex(/^acct_[A-Za-z0-9]+$/),mode:be.literal("setup"),currency:be.string().regex(/^[a-z]{3}$/),customer:be.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:be.uuid(),metadata:be.strictObject({grooveProjectId:be.uuid(),grooveEnvironmentId:be.uuid(),grooveCustomerId:be.uuid(),groovePaymentSetupId:be.uuid()}),setDefaultPaymentMethod:be.boolean(),expiresAt:be.iso.datetime({offset:!0})}),wo=be.strictObject({id:be.uuid(),provider:be.literal("stripe"),status:be.enum(["prepared","complete","expired"]),currency:ce,makeDefault:be.boolean(),url:be.url().nullable(),createdAt:be.iso.datetime({offset:!0}),expiresAt:be.iso.datetime({offset:!0}),completedAt:be.iso.datetime({offset:!0}).nullable(),execution:hf.nullable()});import{z as Ue}from"zod";var Eu=Ue.union([Ue.string(),Ue.number(),Ue.boolean(),Ue.null()]),Du=Ue.strictObject({customerId:Ue.uuid()}),Tu=Ue.strictObject({customerId:Ue.uuid(),provider:Ue.literal("stripe"),checkedAt:Ue.iso.datetime({offset:!0}),status:Ue.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ue.number().int().nonnegative(),differences:Ue.array(Ue.strictObject({subscriptionId:Ue.string().startsWith("sub_"),itemId:Ue.string().nullable(),field:Ue.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:Eu,actual:Eu})).max(1e4)});import{z as J}from"zod";var ii=J.iso.datetime({offset:!0}),oi=J.strictObject({createdAt:ii,id:J.uuid()}),ai=J.strictObject({customerId:J.uuid().optional(),entityId:J.uuid().optional(),productId:J.string().min(1).max(256).optional(),provider:J.enum(["stripe","apple","google","merchant","free"]).optional(),status:J.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:oi.optional(),limit:J.number().int().min(1).max(100).optional()}),jo={id:J.uuid(),customerId:J.uuid(),entityId:J.uuid().nullable(),productId:J.string().min(1).max(256),productVersionId:J.uuid(),name:J.string().min(1).max(120),provider:J.enum(["stripe","apple","google","merchant","free"]),createdAt:ii},gf=J.strictObject({...jo,status:J.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:J.boolean(),billingSubscriptionId:J.uuid().nullable()}),bf=J.strictObject({...jo,status:J.enum(["active","ended","refunded"]),orderId:J.uuid().nullable(),transactionId:J.uuid().nullable(),currency:ce.nullable(),amountMinor:J.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),yf=J.strictObject({...jo,status:J.enum(["blocked","resolved"]),conflict:J.strictObject({detectedAt:ii,blockingMembershipIds:J.array(J.uuid()).min(1).max(100),transactionId:J.uuid()}),resolvedAt:ii.nullable()}),Mu=ai.extend({status:J.enum(["blocked","resolved"]).optional()}),Bu=J.strictObject({customerId:J.uuid(),orderId:J.uuid()}),qu=J.strictObject({orderId:J.uuid(),status:J.enum(["blocked","resolved"])}),zu=J.strictObject({items:J.array(gf).max(100),nextCursor:oi.nullable()}),Nu=J.strictObject({items:J.array(bf).max(100),nextCursor:oi.nullable()}),Fu=J.strictObject({items:J.array(yf).max(100),nextCursor:oi.nullable()});import{z as Ie}from"zod";var Uu=Ie.union([Ie.strictObject({intent:Ie.literal("read"),requestId:Ie.uuid(),purchaseIntentId:Ie.uuid()}),Ie.strictObject({requestId:Ie.uuid(),provider:Ie.literal("apple"),purchaseIntentId:Ie.uuid(),productId:Ie.string().min(1).max(255).optional(),signedTransaction:Ie.string().min(1).max(131072)}),Ie.strictObject({requestId:Ie.uuid(),provider:Ie.literal("google"),purchaseIntentId:Ie.uuid(),productId:Ie.string().min(1).max(255).optional(),purchaseToken:Ie.string().min(1).max(16384)})]),Vu=Ie.strictObject({requestId:Ie.uuid(),orderId:Ie.uuid(),purchaseIntentId:Ie.uuid(),status:Ie.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:ce,refunded:Ie.boolean(),completion:Ie.strictObject({transactionIds:Ie.array(Ie.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ie.boolean()}).nullable()});import{z as P}from"zod";var Po=P.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),xf=P.record(P.string(),P.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Sf=3,cr=20,vf=Sf*cr,_o=P.strictObject({type:P.literal("product"),productId:Po}),Lu={type:P.literal("group"),key:P.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:P.string().trim().min(1).max(80)},If=P.discriminatedUnion("type",[_o,P.strictObject({...Lu,items:P.array(_o).max(cr)})]),Of=P.discriminatedUnion("type",[_o,P.strictObject({...Lu,items:P.array(If).max(cr)})]),wf=P.array(Of).max(cr).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(s){for(let c of s){i++;let u=c.type==="product"?n:r,d=c.type==="product"?c.productId:c.key;u.has(d)&&t.addIssue({code:"custom",message:c.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),u.add(d),c.type==="group"&&a(c.items)}}a(e),(n.size>cr||i>vf)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Co(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Co(t))}var kn=P.strictObject({lookupKey:P.string().trim().min(1).max(200),displayName:P.string().trim().min(1).max(1500),items:wf,metadata:xf}),jf=P.strictObject({product:P.record(P.string(),P.json()),prices:P.array(P.record(P.string(),P.json())),entitlements:P.array(P.record(P.string(),P.json())),freeTrials:P.array(P.record(P.string(),P.json())),licenses:P.array(P.record(P.string(),P.json()))}),$u=kn.extend({id:P.uuid(),projectId:P.uuid(),environmentId:P.uuid(),state:P.enum(["active","archived"]),isCurrent:P.boolean(),revision:P.number().int().nonnegative(),publishedVersionId:P.uuid().nullable(),createdAt:P.iso.datetime({offset:!0})}).superRefine((e,t)=>{e.isCurrent&&(e.state!=="active"||!e.publishedVersionId)&&t.addIssue({code:"custom",message:"Current Offering must be active and published"})}),Gu=P.strictObject({id:P.uuid(),offeringId:P.uuid(),projectId:P.uuid(),environmentId:P.uuid(),version:P.number().int().positive(),document:kn,productEvidence:P.record(Po,jf),createdAt:P.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Co(e.document);(!n.length||Cf(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"})}),_f=P.strictObject({rows:P.array($u).max(200),versions:P.array(Gu).max(500)}),Zy=P.discriminatedUnion("action",[P.strictObject({action:P.literal("create"),document:kn}),P.strictObject({action:P.literal("save"),id:P.uuid(),revision:P.number().int().nonnegative(),document:kn}),P.strictObject({action:P.enum(["publish","set_current","archive","restore"]),id:P.uuid(),revision:P.number().int().nonnegative()})]),Qy=P.strictObject({record:$u,version:Gu.nullable()}),Ku=P.discriminatedUnion("type",[P.strictObject({type:P.literal("current")}),P.strictObject({type:P.literal("id"),id:P.uuid()}),P.strictObject({type:P.literal("lookup_key"),lookupKey:P.string().min(1).max(200)}),P.strictObject({type:P.literal("version"),versionId:P.uuid()})]),Pf=P.strictObject({internalId:Po,id:P.string(),name:P.string().nullable(),version:P.number().int().positive(),archived:P.boolean()}),Jy=_f.extend({products:P.array(Pf).max(500),pagination:P.strictObject({rows:P.string().nullable(),versions:P.string().nullable(),products:P.string().nullable()}).optional()});function Cf(e){let t=[];Co(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 si}from"zod";var Hu=si.strictObject({id:si.uuid(),offeringId:si.uuid(),version:si.number().int().positive(),document:kn});import{z as Be}from"zod";import{z as H}from"zod";import{z as Me}from"zod";var kf=Me.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ci=Me.discriminatedUnion("type",[Me.object({type:Me.literal("fixed"),productVersionId:Me.string().min(1).max(200)}).strict(),Me.object({type:Me.literal("picker"),pickerId:kf,allowedProductVersionIds:Me.array(Me.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")]),Rt=Me.discriminatedUnion("type",[Me.object({type:Me.literal("modal"),size:Me.enum(["sm","md","lg"])}).strict(),Me.object({type:Me.literal("sheet"),size:Me.enum(["sm","md","lg"])}).strict(),Me.object({type:Me.literal("fullscreen")}).strict(),Me.object({type:Me.literal("inline")}).strict()]);var ko=H.discriminatedUnion("type",[H.strictObject({type:H.literal("event"),event:H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),H.strictObject({type:H.literal("open_url"),url:H.url().refine(e=>new URL(e).protocol==="https:")})]),Rf=it,Ef=H.discriminatedUnion("type",[H.object({type:H.literal("checkout"),product:ci}).strict(),H.object({type:H.literal("close")}).strict(),H.object({type:H.literal("action"),action:ko}).strict()]),Rn=H.object({schemaVersion:H.literal(3),kind:H.literal("paywall"),name:H.string().trim().min(1).max(80),presentation:Rt,requirement:An.optional(),products:Ur,offeringVersionId:H.uuid().nullable(),offeringId:H.uuid(),screen:Rf,buttons:H.record(H.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ef)}).strict(),lx=Rn.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 Tf(e))t.addIssue({code:"custom",message:r});for(let r of Df(e))t.addIssue({code:"custom",message:r});Tt(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 Df(e){let t=e.products.items.map(a=>a.productVersionId),n=As(e.screen),r=new Set,i=[];(!t.length||!e.products.defaultProductVersionId||!t.includes(e.products.defaultProductVersionId))&&i.push("products"),e.offeringVersionId||i.push("offering"),e.products.grouping&&(!gs(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(s=>s.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let s=a.product;if(s.type==="fixed")r.add(s.productVersionId);else{s.allowedProductVersionIds.forEach(d=>r.add(d));let c=!1,u=n[s.pickerId];u&&(c=!0,(s.allowedProductVersionIds.some(d=>!u.ids.includes(d))||u.ids.some(d=>!s.allowedProductVersionIds.includes(d)))&&i.push("picker")),Pt(e.screen,d=>{if(d.id!==s.pickerId||d.type!=="plan_picker")return;c=!0,(JSON.stringify(d.planIds)!==JSON.stringify(t)||JSON.stringify(s.allowedProductVersionIds)!==JSON.stringify(t)||d.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let f=d.grouping?{tiers:d.grouping.tiers,assignments:d.grouping.assignments}:void 0;JSON.stringify(f)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),c||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Pt(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(s=>!t.includes(s)))&&i.push("binding")}),[...new Set(i)]}function Tf(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let c of e.screen.pages)r.set(c.id,[]),gn(c.root,u=>{let d=u.type==="button"?u.action:u.type==="stack"?u.purchaseAction:void 0;if(d){let f=e.screen.actions.find(k=>k.id===d);f?.type==="navigate"&&r.get(c.id).push(f.pageId);let x=e.buttons[d];c.id!==n.id&&x&&x.type!=="close"&&t.push(`purchaseScreen:${u.id}`)}c.id!==n.id&&(u.type==="plan_picker"||u.type==="stack"&&u.productSlot)&&t.push(`packageScreen:${u.id}`)});let i=new Set;function a(c){if(!i.has(c)){i.add(c);for(let u of r.get(c)??[])a(u)}}let s=e.screen.initialPageId??e.screen.pages[0]?.id;s?a(s):t.push("initialPage");for(let c of e.screen.pages)i.has(c.id)||t.push(`unreachableScreen:${c.id}`);return[...new Set(t)]}var Zu=H.object({id:H.uuid(),projectId:H.uuid(),environmentId:H.uuid(),revision:H.number().int().nonnegative(),state:H.enum(["active","archived"]),publishedVersionId:H.uuid().nullable(),updatedAt:H.iso.datetime({offset:!0}),draft:Rn}).strict(),px=H.object({rows:H.array(Zu).max(200),nextCursor:H.uuid().nullable()}).strict(),dx=Zu.omit({draft:!0}).extend({name:H.string(),productCount:H.number().int().nonnegative()}).strict(),mx=H.discriminatedUnion("action",[H.object({action:H.literal("save"),id:H.uuid().nullable(),revision:H.number().int().nonnegative(),document:Rn}).strict(),H.object({action:H.enum(["publish","archive"]),id:H.uuid(),revision:H.number().int().nonnegative()}).strict()]),fx=H.object({paywalls:H.array(H.object({id:H.uuid(),paywallId:H.uuid(),version:H.number().int().positive(),name:H.string().min(1).max(80),presentation:Rt,buttons:Rn.shape.buttons}).strict()).max(500),limited:H.boolean()}).strict();import{z as te}from"zod";import{z as Qe}from"zod";var En=Qe.string().regex(/^[a-f0-9]{64}$/),Mf=ms.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Qu=Qe.strictObject({couponDigests:Qe.record(Qe.uuid(),En),variables:Qe.record(mn,Qe.record(Qe.uuid(),Qe.partialRecord(Qe.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Qe.string()))),locales:Qe.record(mn,hn.extend({nodes:Qe.record(Qe.string(),Qe.strictObject({base:Mf})),plans:Qe.object({}).strict(),pickers:Qe.object({}).strict()}).omit({paywall:!0}))});import{z as pe}from"zod";import{z as ui}from"zod";var Ro=ui.strictObject({eventsEnabled:ui.boolean(),experimentViewsEnabled:ui.boolean(),featureUsageEnabled:ui.boolean()}),Sx=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function vx(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var Eo=Mt.extend({analyticsConfig:Ro,remoteFeatures:pe.array(pe.string().min(1).max(255)).max(500)}),Bf=Eo.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"})}),Ju=pe.strictObject({attributes:rt,features:pe.array(pe.string().min(1).max(255)).max(500).optional(),customerId:pe.uuid().optional()}),qf=pe.strictObject({value:me,source:pe.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:pe.boolean(),off:pe.boolean(),ruleId:pe.string(),experimentResult:xs.optional()}),Wu=pe.strictObject({generation:Mt.shape.generation,evaluatedAt:Mt.shape.evaluatedAt,expiresAt:Mt.shape.expiresAt,features:pe.record(pe.string(),qf),merchandiseContext:pe.strictObject({merchandiseId:pe.uuid(),merchandise:rt}).optional()}),Xu=pe.strictObject({customerId:pe.uuid().optional(),events:pe.array(pe.strictObject({eventUuid:pe.uuid(),timestamp:pe.iso.datetime({offset:!0}),name:pe.string().min(1).max(255),merchandise:pc.optional(),properties:pe.record(pe.string(),me).default({}),deviceId:pe.string().min(1).max(255).optional(),sessionId:pe.string().min(1).max(255).optional()})).min(1).max(100)}),Yu=pe.strictObject({inserted:pe.number().int().nonnegative(),duplicates:pe.number().int().nonnegative(),rejected:pe.number().int().nonnegative(),skipped:pe.number().int().nonnegative(),analyticsConfig:Ro});import{z as C}from"zod";function Do(e,t=[]){let n=[];Pt(e,i=>{i.hidden&&n.push("Hidden components must not be delivered"),t.includes(i.type)&&n.push(`Node type ${i.type} cannot be delivered`)});let r=new Set(zi(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let s of Object.keys(a))r.has(s)||n.push(`Unused string ${s} must not be delivered (${i})`);return n}function el(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>el(t)??[])}}function zf(e){let t=e.pages.map(i=>{let a=el(i.root);return a?.type==="stack"?{...i,root:a}:{...i,root:{type:"stack",id:i.root.id,...i.root.name===void 0?{}:{name:i.root.name},direction:"vertical",align:"stretch",justify:"start",children:[]}}}),n=new Set(zi({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([s])=>n.has(s)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function tl(e,t=[]){let n=it.parse(structuredClone(zf(e))),r=a=>a.type!=="stack"||a.interaction!==void 0||a.children.some(r);for(let a of n.pages)if(!r(a.root))throw new Error(`Page ${a.id} has no visible content`);let i=Do(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as T}from"zod";import{z as Dn}from"zod";var nl=Dn.strictObject({id:Dn.uuid(),name:Dn.string().trim().min(1).max(80),client:Is,source:Cr,event:Dn.enum(["screen_enter","button_click"]),cooldownSeconds:Dn.number().int().min(0).max(2592e3),behavior:Dn.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as Ae}from"zod";var To=me,Nf=["parameters","answers","results","variables"];function Mo(e){return Nf.some(t=>e===t||e.startsWith(t+"."))}function Bo(e){let t={};for(let[r,i]of Object.entries(Wn(e.declarations,e))){let a=r.split(".");if(a.some(u=>["__proto__","constructor","prototype"].includes(u)))throw new Error("Reserved result path");let s=t;for(let u of a.slice(0,-1)){Object.hasOwn(s,u)||(s[u]={});let d=s[u];if(!d||typeof d!="object"||Array.isArray(d))throw new Error("Ambiguous result path");s=d}let c=a.at(-1);if(c===void 0)throw new Error("Empty result path");s[c]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Mo(r))),variables:t}}import{z as Ff}from"zod";var li=Ff.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var qo=Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),rl=Ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),il=xt.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),zo=Ae.record(qo,Ae.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),Uf=St,ol=Ae.strictObject({type:Ae.literal("external_task"),endpointId:Ae.uuid(),taskKey:qo,inputs:Ae.record(qo,Uf).refine(e=>Object.keys(e).length<=20),outputs:zo}),al=Ae.strictObject({maxAttempts:Ae.number().int().min(1).max(5),retryDelaySeconds:Ae.number().int().min(1).max(30),backoff:Ae.enum(["fixed","exponential"]),requestTimeoutSeconds:Ae.number().int().min(1).max(10),timeoutSeconds:Ae.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var Hx=Ae.strictObject({outcome:Ae.enum(["success","failure"]),data:il});var Zx=Ae.discriminatedUnion("operation",[Ae.strictObject({operation:Ae.literal("signal"),runId:Ae.uuid(),nodeId:rl,eventName:li,eventId:Ae.uuid(),data:il}),Ae.strictObject({operation:Ae.literal("read_results"),runId:Ae.uuid()})]),Qx=Ae.strictObject({scope:ve,runId:Ae.uuid(),eventId:Ae.uuid(),accepted:Ae.boolean()}),Vf=Ae.record(rl,To),Jx=Ae.strictObject({scope:ve,runId:Ae.uuid(),results:Vf});var ht={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},sl="00000000-0000-0000-0000-000000000000";import{z as M}from"zod";import{z as ye}from"zod";var nS=ye.enum(["local","remote"]),No=ye.strictObject({port:ye.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:me.optional(),sticky:ye.array(ye.strictObject({expected:_r.nullable(),next:_r})).max(100),exposures:ye.array(me).max(100),features:ye.array(me).max(100)}),cl=ye.strictObject({type:ye.literal("evaluate"),receiptId:ye.uuid(),environmentId:ye.uuid(),policyRevision:ye.number().int().nonnegative(),attributes:rt,sticky:ye.record(ye.string(),_r)}),ul=cl.extend({runId:ye.uuid(),versionId:ye.uuid(),nodeId:ye.string().min(1).max(64),visit:ye.number().int().nonnegative(),revision:ye.number().int().nonnegative()}),Fo=cl.omit({type:!0,receiptId:!0}).extend({type:ye.literal("evaluate_segment")}),ll=ye.strictObject({nodeId:ye.string().min(1).max(64),result:No}),pl=Fo.extend({runId:ye.uuid(),versionId:ye.uuid(),nodeId:ye.string().min(1).max(64),visit:ye.number().int().nonnegative(),revision:ye.number().int().nonnegative(),parameters:xt,answers:Zt,variables:ye.record(ye.string(),me)});import{z as $}from"zod";var Uo=$.array($.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"),pi=$.intersection(rt,$.looseObject({tags:Uo.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),di=$.string().trim().max(80),mi=$.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),fi=$.union([$.email().max(254),$.literal("")]),Ai=$.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),dl=$.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),ml=$.object({externalUserId:dl.optional(),name:di.default(""),email:fi.default(""),phone:mi.optional(),attributes:pi.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Tn=$.discriminatedUnion("type",[$.strictObject({type:$.literal("id"),value:$.uuid()}),$.strictObject({type:$.literal("externalUserId"),value:dl})]),Mn=$.strictObject({name:di.optional(),email:fi.optional(),phone:mi.optional(),attributes:pi.optional(),fingerprint:Ai.optional()}),rn=e=>!e.customerData||e.customer?.type==="externalUserId",on="customerData requires an externalUserId customer",Bn=$.object({id:$.uuid(),externalUserId:$.string().min(1).max(255).nullable(),name:di,email:fi,phone:mi.optional(),attributes:pi,createdAt:$.iso.datetime()}).strict(),fl=$.object({customer:Bn,changed:$.boolean(),replayed:$.boolean()}).strict(),Lf=$.discriminatedUnion("type",[$.object({type:$.literal("id"),value:$.uuid()}).strict(),$.object({type:$.literal("externalUserId"),value:$.string().trim().min(1).max(255)}).strict()]),$f=$.object({name:di.optional(),email:fi.optional(),phone:mi.optional(),attributes:pi.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:$.array($.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:$.strictObject({add:Uo,remove:Uo}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Vo=$.object({lookup:Lf}).strict(),Al=Vo.extend({requestId:$.uuid(),patch:$f}).strict(),hl=$.object({search:$.string().trim().max(200).default(""),tag:$.string().trim().max(40).default(""),planId:$.string().max(200).default(""),versionId:$.string().max(200).default(""),holdingStatus:$.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:$.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:$.union([$.iso.datetime(),$.literal("")]).default(""),createdUntil:$.union([$.iso.datetime(),$.literal("")]).default(""),offset:$.coerce.number().int().min(0).max(1e5).default(0),limit:$.coerce.number().int().min(1).max(100).default(50)}).strict(),gl=$.object({customers:Bn.array(),hasMore:$.boolean(),total:$.number().int().nonnegative().nullable(),evaluatedAt:$.iso.datetime()}).strict();var ur=M.discriminatedUnion("type",[M.strictObject({type:M.literal("literal"),value:me}),M.strictObject({type:M.literal("variable"),key:Te,path:At.optional()}),M.strictObject({type:M.literal("feature"),featureKey:M.string().min(1).max(128)})]),Gf=M.strictObject({requestId:M.uuid(),decisionId:M.uuid(),customerId:M.uuid(),externalUserId:M.string().min(1).max(255).nullable(),versionId:M.uuid(),receiptId:M.uuid(),value:me}),Lo={funnelId:M.uuid(),requestId:M.uuid(),customer:Tn,customerData:Mn.optional(),attributes:rt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},fS=M.discriminatedUnion("operation",[M.strictObject({operation:M.literal("decide"),...Lo}).refine(rn,on),M.strictObject({operation:M.literal("read_decision"),decisionId:M.uuid()}),M.strictObject({operation:M.literal("evaluate_decision"),decisionId:M.uuid(),requestId:M.uuid(),nodeId:M.string().min(1).max(64),visit:M.number().int().nonnegative(),revision:M.number().int().nonnegative(),receiptId:M.uuid(),policyRevision:M.number().int().nonnegative(),generation:M.string().min(1).max(256),result:No}),M.strictObject({operation:M.literal("feature_config"),funnelId:M.uuid()}),M.strictObject({operation:M.literal("commit_decision_segment"),decisionId:M.uuid(),requestId:M.uuid(),nodeId:M.string().min(1).max(64),visit:M.number().int().nonnegative(),revision:M.number().int().nonnegative(),policyRevision:M.number().int().nonnegative(),generation:M.string().min(1).max(256),steps:M.array(ll).max(32),boundary:M.strictObject({nodeId:M.string().min(1).max(64),visit:M.number().int().nonnegative()}).optional()}),M.strictObject({operation:M.literal("segment_configuration"),funnelId:M.uuid(),versionId:M.uuid()}),M.strictObject({operation:M.literal("configuration"),funnelId:M.uuid(),versionId:M.uuid().optional()}),M.strictObject({operation:M.literal("local_configuration"),funnelId:M.uuid()}),M.strictObject({operation:M.literal("report_used"),decisionId:M.uuid(),eventId:M.uuid(),occurredAt:M.iso.datetime({offset:!0}),reference:M.string().min(1).max(128).optional()})]),AS=M.strictObject({scope:ve,decisionId:M.uuid(),requestId:M.uuid(),status:M.enum(["pending","completed","failed"]),decision:Gf.nullable(),evaluation:M.discriminatedUnion("type",[ul,pl]).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"),hS=M.strictObject({scope:ve,decisionId:M.uuid(),eventId:M.uuid(),source:M.literal("caller_reported")});import{z as Ve}from"zod";var bl=Ve.strictObject({type:Ve.literal("bundle"),paywall:St.optional(),offering:St.optional(),coupons:St,data:St}),Kf=e=>Ve.strictObject({type:Ve.literal(e),id:Ve.uuid()}),vS=Ve.strictObject({type:Ve.literal("bundle"),paywallVersionId:Ve.uuid().optional(),offeringVersionId:Ve.uuid().optional(),couponIds:Ve.array(Ve.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:me});var IS=Ve.strictObject({type:Ve.literal("bundle"),offering:Kf("offering_version").nullable(),paywall:Ve.strictObject({versionId:Ve.uuid(),paywallId:Ve.uuid(),offeringVersionId:Ve.uuid()}).nullable(),coupons:Ve.array(Yn).max(20),data:me});import{z as gt}from"zod";import{z as pt}from"zod";var yl=pt.union([pt.string(),pt.number().finite(),pt.boolean(),pt.null()]),Hf=pt.union([yl,pt.array(yl).min(1).max(20)]),Zf=pt.record(At,Hf).refine(e=>Object.keys(e).length<=10),xl=pt.strictObject({path:At,type:pt.enum(["string","number","boolean","strings"]),nullable:pt.boolean().optional(),aggregation:pt.enum(["count","exists"]).optional(),where:Zf.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"})});var Qf=["sendMessage","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"],Sl=gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Jf=St,vl=gt.discriminatedUnion("type",[ol,gt.strictObject({type:gt.literal("claim_offer"),coupon:St}),gt.strictObject({type:gt.literal("event"),event:Sl}),gt.strictObject({type:gt.literal("api"),operation:gt.enum(Qf),inputs:gt.record(At,Jf).refine(e=>Object.keys(e).length<=40),outputs:gt.record(Sl,xl).refine(e=>Object.keys(e).length<=20)})]);var Pe=li,Wf=T.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),st={id:Pe,name:T.string().trim().min(1).max(80),position:T.strictObject({x:T.number().finite(),y:T.number().finite()}).optional()},Xf={success:Pe,cancel:Pe,unavailable:Pe,failure:Pe},$o=T.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Go=T.enum(["same_window","new_window"]),Yf=T.discriminatedUnion("type",[T.strictObject({...st,type:T.literal("entry"),next:Pe,triggers:T.array(nl).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),T.strictObject({...st,type:T.literal("screen"),screenId:Pe,presentation:Rt,outputs:T.record(Pe,Pe),offering:T.discriminatedUnion("source",[T.strictObject({source:T.literal("variable"),key:Te}),T.strictObject({source:T.literal("fixed"),versionId:T.uuid()})]).optional()}),T.strictObject({...st,type:T.literal("offering"),configuration:T.discriminatedUnion("source",[T.strictObject({source:T.literal("fixed"),versionId:T.uuid()}),T.strictObject({source:T.literal("feature"),featureKey:T.string().min(1).max(128)})]),writes:T.strictObject({value:Te}),next:Pe}),T.strictObject({...st,type:T.literal("coupon"),couponId:T.uuid(),writes:T.strictObject({value:Te}),next:Pe}),T.strictObject({...st,type:T.literal("coupons"),couponIds:T.array(T.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:T.strictObject({value:Te}),next:Pe}),T.strictObject({...st,type:T.literal("output"),value:T.discriminatedUnion("type",[...ur.options,bl,T.strictObject({type:T.literal("selection"),screenId:Pe,offeringKey:Te})])}),T.strictObject({...st,type:T.literal("condition"),cases:T.array(T.strictObject({condition:Ht,target:Pe})).min(1).max(50),default:Pe}),T.strictObject({...st,type:T.literal("feature"),featureKey:T.string().min(1).max(128),writes:T.strictObject({value:Te}),next:Pe}),T.strictObject({...st,type:T.literal("split"),experimentId:T.uuid(),applyPageExperiment:T.literal(!0).optional(),routes:T.record(Wf,Pe).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:Pe}),T.strictObject({...st,type:T.literal("action"),...Xf,execution:al,action:vl,writes:zr.optional()}),T.strictObject({...st,type:T.literal("external_page"),appManifest:Cr.optional(),url:$o,openIn:Go,opened:Pe,failed:Pe}),T.strictObject({...st,type:T.literal("end"),outcome:T.enum(["completed","closed","ineligible","failed"]),output:ur.optional()}),T.strictObject({...st,type:T.literal("wait"),writes:zr.optional(),wait:T.discriminatedUnion("type",[T.strictObject({type:T.literal("duration"),delaySeconds:T.number().int().min(1).max(2592e3),elapsed:Pe}),T.strictObject({type:T.literal("event"),eventName:Pe,outputs:zo,timeoutSeconds:T.number().int().min(1).max(2592e3),received:Pe,timeout:Pe})])})]),Ko=T.strictObject({version:T.literal(5),entry:Pe,nodes:T.array(Yf).min(1).max(ht.flowNodes)}),Ho=Ko.superRefine((e,t)=>{eA(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function hi(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 eA(e,t){let n=[],r=new Map(e.nodes.map(f=>[f.id,f])),i=(f,x,k)=>{n.push(f),t?.({message:f,reason:x,path:k?["nodes",e.nodes.indexOf(k)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(f=>f.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(f=>f.type==="screen").length>ht.pages||e.nodes.filter(f=>!["screen","entry","end","output"].includes(f.type)).length>ht.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let f of e.nodes){for(let x of hi(f))x===e.entry&&i("An entry cannot be a transition target","entryTarget",f),r.has(x)||i(`Missing target ${x}`,"missingTarget",f);f.type==="screen"&&(a.has(f.screenId)&&i("Every screen has exactly one node owner","screenOwner",f),a.add(f.screenId))}let s=new Set,c=new Set,u=new Set;function d(f){if(s.has(f)){i("Flow edges must not form a cycle","cycle",r.get(f));return}if(!(c.has(f)||!r.has(f))){s.add(f),u.add(f);for(let x of hi(r.get(f)))d(x);s.delete(f),c.add(f)}}d(e.entry);for(let f of e.nodes)u.has(f.id)||i("Every node must be reachable from Entry","unreachable",f);return[...new Set(n)]}var Zo={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Il(e,t,n){let r=[...t].sort((c,u)=>u.length-c.length),i=new Set,a=(c,u=!1)=>{let d=r.find(f=>c===f||u&&c.startsWith(f+"."));i.add(d??c)};if(e.type==="condition"){let c=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let u of e.cases.slice(0,c+1))for(let d of Nt(u.condition))d.startsWith("variables.")&&a(d.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 c of Object.values(e.action.inputs))c.source==="variable"&&a(c.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let s=e.type==="output"?e.value:e.type==="end"?e.output:null;if(s?.type==="variable"&&a(s.key),s?.type==="bundle")for(let c of[s.paywall,s.offering,s.coupons,s.data])c?.source==="variable"&&a(c.key);return s?.type==="selection"&&a(s.offeringKey),[...i]}import{z as I}from"zod";var qn=I.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),gi=e=>I.record(I.string(),me).refine(t=>ot(t)<=e,"Funnel evidence exceeds its byte budget"),ev=I.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Jo=I.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Wo=I.discriminatedUnion("type",[I.strictObject({type:I.literal("flag"),key:I.string().min(1).max(128)}),I.strictObject({type:I.literal("experiment"),id:I.uuid()}),I.strictObject({type:I.literal("saved_group"),id:I.uuid()}),I.strictObject({type:I.literal("config"),key:I.string().min(1).max(128)}),I.strictObject({type:I.literal("constant"),key:I.string().min(1).max(128)}),I.strictObject({type:I.literal("paywall_version"),id:I.uuid()}),I.strictObject({type:I.literal("offering_version"),id:I.uuid()}),I.strictObject({type:I.literal("reward"),id:I.uuid()})]),lr=I.strictObject({schemaVersion:I.literal(1),kind:Jo,selector:Wo.nullable(),context:gi(131072),contract:I.strictObject({version:I.number().int().positive(),evaluator:I.string().min(1).max(128),policyRevision:I.number().int().nonnegative()})}).refine(e=>ot(e)<=131072,"Node input exceeds its byte budget"),Ol=I.strictObject({schemaVersion:I.literal(1),kind:Jo,outcome:I.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:gi(131072),route:I.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:gi(131072)}).refine(e=>ot(e)<=131072,"Node result exceeds its byte budget"),tv=I.strictObject({schemaVersion:I.literal(1),operations:I.record(qn,I.strictObject({attempts:I.number().int().nonnegative(),maxAttempts:I.number().int().min(1).max(5),deadlineAt:I.iso.datetime({offset:!0}),retryAt:I.iso.datetime({offset:!0}).nullable(),error:I.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:I.strictObject({type:qn,id:I.uuid()}).nullable()}))}).refine(e=>ot(e)<=65536,"Execution state exceeds its byte budget"),an={receiptId:I.uuid()},Qo=I.iso.datetime({offset:!0}),nv=I.discriminatedUnion("type",[I.strictObject({type:I.literal("node_entered"),details:I.strictObject({kind:Jo})}),I.strictObject({type:I.literal("presentation_shown"),details:I.strictObject({...an,source:I.literal("client"),occurredAt:Qo.optional()})}),I.strictObject({type:I.literal("decision_accepted"),details:I.strictObject(an)}),I.strictObject({type:I.literal("signal_received"),details:I.strictObject({signalId:I.uuid(),nodeId:qn,eventName:qn,data:gi(8192),source:I.literal("server"),occurredAt:Qo})}),I.strictObject({type:I.literal("signal_consumed"),details:I.strictObject({...an,signalId:I.uuid()})}),I.strictObject({type:I.literal("wait_elapsed"),details:I.strictObject(an)}),I.strictObject({type:I.literal("wait_timeout"),details:I.strictObject(an)}),I.strictObject({type:I.literal("operation_completed"),details:I.strictObject({...an,operation:qn,reference:I.strictObject({type:qn,id:I.uuid()}).nullable()})}),I.strictObject({type:I.literal("execution_recovered"),details:I.strictObject({generation:I.number().int().positive(),reason:I.enum(["interrupted","expired_lease","delivery_failed"])})}),I.strictObject({type:I.literal("execution_failed"),details:I.strictObject({generation:I.number().int().positive(),code:I.string().regex(/^[a-z_]{1,64}$/)})}),I.strictObject({type:I.literal("run_completed"),details:I.strictObject({outcome:I.enum(["completed","ineligible","failed"])})}),I.strictObject({type:I.literal("run_closed"),details:I.strictObject({source:I.enum(["client","server","expiry"])})}),I.strictObject({type:I.literal("treatment_used"),details:I.strictObject({...an,source:I.enum(["client","server"]),occurredAt:Qo,reference:I.string().min(1).max(128).optional()})})]);var dt=C.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),tA=C.discriminatedUnion("type",[C.strictObject({id:dt,type:C.literal("owned"),publicData:Qu.optional(),document:it.refine(e=>["page","popup","onboarding"].includes(e.surface)&&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")}),C.strictObject({id:dt,type:C.literal("paywall"),paywallVersionId:C.uuid()})]),Xo={kind:C.literal("funnel"),schemaVersion:C.literal(4),screens:C.array(tA).max(ht.pages),references:C.record(dt,Wo).refine(e=>Object.keys(e).length<=500),inputs:C.array(C.strictObject({variable:dt,screenId:dt,componentId:dt,required:C.boolean()})).max(ht.questions),variables:C.record(Te,Sn).refine(e=>Object.keys(e).length<=ht.logicNodes),outputSchema:xn,execution:C.strictObject({runTimeoutSeconds:C.number().int().min(1).max(Zo.runTimeoutSeconds),maxTransitions:C.number().int().min(1).max(Zo.maxTransitions)})},Sv=C.strictObject({...Xo,graph:Ko});function nA(e,t){let n=!1,r=(i,a)=>{let s=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(c=>c[i.text]?.includes("{{offer."))&&!(s&&t(s))&&(n=!0),i.type==="stack"&&i.children.forEach(c=>r(c,s))};for(let i of e.pages)r(i.root);return n}function yi(e){return Array.isArray(e)?e.some(yi):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===sl:yi(n))}function rA(e){let t=[],n=new Set(Object.values(e.references).flatMap(r=>r.type==="reward"?[r.id]:[]));for(let[r,i]of e.screens.entries()){if(i.type!=="owned")continue;let a;try{a=tl(i.document)}catch(s){t.push({message:s instanceof Error?s.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[s,c]of e.inputs.entries())c.screenId===i.id&&!Ni(a,c.componentId)&&t.push({message:`Local Funnel input ${c.variable} targets hidden component ${c.componentId} on screen ${c.screenId}`,reason:"inputBinding",path:["inputs",s]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],s=i.type==="screen"?e.screens.find(c=>c.id===i.screenId):void 0;s?.type==="owned"&&(s.document.actions.some(c=>typeof c.properties.templateKey=="string"&&c.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),nA(s.document,c=>n.has(c))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&yi(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&yi(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function wl(e,t){for(let{message:n,reason:r,path:i}of rA(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function jl(e,t){let n=(S,p,b=[])=>t.addIssue({code:"custom",message:S,path:b,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(S=>[S.id,S])),a=(S,p)=>r.some(b=>b.type===S&&("id"in b?b.id:b.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let s=e.graph.nodes.filter(S=>S.type==="screen");(s.length!==i.size||s.some(S=>!i.has(S.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let c=new Map,u=Object.keys(e.variables);u.some(S=>u.some(p=>S!==p&&p.startsWith(S+".")))&&n("Variable paths must not overlap","variable");function d(S,p){Object.hasOwn(e.variables,S)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let b=c.get(S)??new Set;b.add(p.id),c.set(S,b)}for(let[S,p]of e.graph.nodes.entries()){let b=["graph","nodes",S],R=p.type==="feature"?p.featureKey:p.type==="offering"&&p.configuration.source==="feature"?p.configuration.featureKey:p.type==="output"&&p.value.type==="feature"?p.value.featureKey:p.type==="end"&&p.output?.type==="feature"?p.output.featureKey:null;R&&!a("flag",R)&&n("Flag selectors require an explicit GB resource reference","feature",b);let Q=p.type==="feature"||p.type==="offering"||p.type==="coupon"||p.type==="coupons"||p.type==="action"&&p.action.type==="api"?["value"]:p.type==="action"&&p.action.type==="external_task"?Object.keys(p.action.outputs):p.type==="wait"&&p.wait.type==="event"?Object.keys(p.wait.outputs):[],ne="writes"in p?p.writes??{}:{};(Q.length!==Object.keys(ne).length||Q.some(q=>!Object.hasOwn(ne,q))||new Set(Object.values(ne)).size!==Object.values(ne).length)&&n("Node writes must map every named output exactly once","variable",b);for(let[q,ie]of Object.entries(ne)){d(ie,p);let oe=e.variables[ie],L=p.type==="offering"?"offering_version":p.type==="coupon"?"reward":p.type==="action"&&p.action.type==="api"?"json":p.type==="action"&&p.action.type==="external_task"?p.action.outputs[q]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[q]:void 0;(oe?.source.type!=="node"||L&&oe.type!==L)&&n("Node writer source or output type does not match declaration","variable",b)}if(p.type==="coupons"){let q=e.variables[p.writes.value];(q?.type!=="array"||q.items?.type!=="reward"||q.items.nullable||q.nullable)&&n("Coupons output requires a non-null Reward array","variable",b);for(let ie of p.couponIds)a("reward",ie)||n("Coupons require Reward references","coupon",b)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",b),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",b),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let q=p.action.coupon.value;(!q||typeof q!="object"||Array.isArray(q)||q.type!=="reward"||typeof q.id!="string"||Object.keys(q).length!==2||!a("reward",q.id))&&n("Coupon claims require a Reward reference","coupon",b)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",b),p.type==="screen"&&p.offering?.source==="variable"&&e.variables[p.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",b),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="variable"&&(e.variables[p.action.coupon.key]?.type!=="reward"||p.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",b),p.type==="screen"){let q=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",b),q?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",b),q?.type==="paywall"&&!a("paywall_version",q.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",b),q?.type==="owned"){let ie=q.document.pages[0];if(!ie){n("Owned screen requires a page","screen",b);continue}Tt(q.document).some(L=>!L.complete)&&n("Owned screens require complete local content","translations",b);let oe=new Set(q.document.actions.map(L=>L.id));(oe.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(L=>!oe.has(L)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",b),gn(ie.root,L=>{!p.offering&&(L.type==="plan_picker"||(L.type==="stack"||L.type==="button")&&L.bind?.plan||L.type==="customer_data"&&["customer_plans","credit_packs"].includes(L.data.source))&&n("Product presentation requires an Offering Version","offering",b),L.type==="customer_data"&&Object.values(L.data.outputs??{}).some(Xe=>Xe!==void 0&&!oe.has(Xe))&&n("Customer components require declared screen outcomes","componentOutput",b)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",b),p.type==="end"&&p.output?.type==="literal"&&!lt(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",b),p.type==="output"&&p.value.type==="literal"&&!lt(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",b);let Se=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(Se?.type==="variable"&&!Se.path){let q=e.variables[Se.key];q&&!Qi(q,e.outputSchema)&&n("Variable output does not match outputSchema","output",b)}if(p.type==="screen"){let q=i.get(p.screenId);if(q?.type==="owned")for(let ie of Yi(q.document))(/^(input|params)\./.test(ie)||ie.startsWith("variables.")&&!Xi(ie.slice(10),u))&&n("Screen values must reference registered variables","variable",b)}if(p.type==="condition")for(let q of p.cases){for(let ie of Dt(q.condition))a("saved_group",ie)||n("Conditions require explicit Saved Group references","savedGroup",b);for(let ie of Nt(q.condition))ie.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",b)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",b);for(let[q,ie]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let oe=p.value[q];if(oe)if(oe.source==="literal"){let L=q==="coupons"?oe.value:[oe.value];(!Array.isArray(L)||L.length>20||L.some(Xe=>!lt({type:ie,nullable:!1},Xe)||!a(ie,Xe.id))||q==="coupons"&&new Set(L.map(Xe=>Xe.id)).size!==L.length)&&n("Bundle requires distinct scoped resource references",q==="coupons"?"coupon":q==="paywall"?"paywall":"offering",[...b,"value",q])}else{let L=e.variables[oe.key];(oe.path||!L||L.nullable||(q==="coupons"?L.type!=="array"||L.items?.type!=="reward"||L.items.nullable:L.type!==ie))&&n("Bundle binding type does not match its slot","output",b)}}}}for(let[S,p]of e.graph.nodes.entries()){let b=p.type==="screen"?i.get(p.screenId):void 0,R=[...Il(p,u),...b?.type==="owned"?Nr(b.document).map(Q=>Xi(Q,u)?.key??Q):[]];for(let Q of new Set(R)){let ie=function(oe){if(oe===p.id)return!0;if(q.has(oe))return!1;q.add(oe);let L=e.graph.nodes.find(Ye=>Ye.id===oe);return L?(Se.has(oe)?L.type==="action"?[L.cancel,L.unavailable,L.failure]:L.type==="wait"&&L.wait.type==="event"?[L.wait.timeout]:[]:hi(L)).some(ie):!1};var k=ie;if(!Object.hasOwn(e.variables,Q)){n("Consumed variable is undeclared","variable",["graph","nodes",S]);continue}let ne=e.variables[Q];if(p.type==="screen"&&ne.source.type==="input"&&e.inputs.some(oe=>oe.screenId===p.screenId&&oe.variable===Q)||ne.source.type==="parameter"||ne.source.type==="attribute")continue;let Se=ne.source.type==="input"?new Set(e.inputs.filter(oe=>oe.variable===Q&&oe.required).flatMap(oe=>s.filter(L=>L.screenId===oe.screenId).map(L=>L.id))):c.get(Q)??new Set,q=new Set;(!Se.size||ie(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",S])}}(new Set(e.inputs.map(S=>S.variable)).size!==e.inputs.length||new Set(e.inputs.map(S=>`${S.screenId}:${S.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[S,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",S]);let b=i.get(p.screenId),R=b?.type==="owned"?Ni(b.document,p.componentId):null;if((R?.type!=="stack"||!R.interaction||!["input","toggle","select","multiselect","tabs"].includes(R.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",S]),R?.type==="stack"&&R.interaction){let Q=R.interaction.type==="toggle"?"boolean":R.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==Q&&n("Input variable type does not match component","inputBinding",["inputs",S]);let ne=e.variables[p.variable]?.enum;ne&&!R.children.filter(Se=>!Se.hidden).every(Se=>ne.includes(Se.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",S])}}for(let[S,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",S]),p.source.type==="input"&&!e.inputs.some(b=>b.variable===S)&&n("Input variable requires a component binding","inputBinding",["variables",S]);let f=0,x=0;for(let S of e.screens)if(S.type==="owned"){for(let p of S.document.pages)gn(p.root,()=>{f++});x+=S.document.actions.length}(f>ht.components||x>ht.actions||ot(e)>ht.documentBytes)&&n("Funnel document exceeds its budget","budget")}var iA=C.strictObject({...Xo,graph:Ho}).superRefine(jl),Vt=C.strictObject({...Xo,graph:Ho,displayName:C.string().trim().min(1).max(80)}).superRefine(jl),vv=Vt.superRefine(wl),Iv=iA.superRefine(wl),bi=C.string().regex(Bt),pr={requestId:C.uuid(),nodeId:dt,visit:C.number().int().nonnegative(),revision:C.number().int().nonnegative(),customerToken:bi.optional()},oA=C.discriminatedUnion("type",[C.strictObject({type:C.literal("screen"),output:dt,answers:Zt,selection:C.record(dt,C.union([C.string().max(200),C.boolean(),C.number().int().min(0).max(1e4)])).optional()}),C.strictObject({type:C.literal("paywall_quote"),featureQuantities:C.record(C.uuid(),C.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:dt,productVersionId:C.uuid(),offerId:C.uuid().optional(),nativeOffer:jn.optional(),predecessor:C.strictObject({operationId:C.uuid().nullable(),generation:C.number().int().positive()}).optional()}),C.strictObject({type:C.literal("paywall_confirm"),operationId:C.uuid()}),C.strictObject({type:C.literal("paywall_cancel"),operationId:C.uuid()}),C.strictObject({type:C.literal("client_action"),receiptId:C.uuid(),outcome:C.enum(["success","cancel","failure","opened","failed"])})]),aA=C.object({nodeId:dt,visit:C.number().int().nonnegative(),revision:C.number().int().nonnegative(),components:C.record(dt,C.object({resourceKey:C.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:C.number().int().min(1).max(1e5),after:kr.nullable(),filter:C.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Ov=C.discriminatedUnion("operation",[C.strictObject({operation:C.literal("start"),funnelId:C.uuid(),requestId:C.uuid(),customer:Tn.optional(),customerData:Mn.optional(),locale:C.string().min(1).max(35),parameters:xt}).refine(rn,on),C.strictObject({operation:C.literal("get"),settlementRequestId:C.uuid().optional(),data:aA.optional(),purchase:C.strictObject({receiptId:C.uuid(),operationId:C.uuid()}).optional(),customerToken:bi.optional()}),C.strictObject({operation:C.literal("resume"),requestId:C.uuid(),customerToken:bi.optional()}),C.strictObject({operation:C.literal("submit"),...pr,input:oA}),C.strictObject({operation:C.literal("back"),...pr}),C.strictObject({operation:C.literal("shown"),...pr}),C.strictObject({operation:C.literal("close"),...pr}),C.strictObject({operation:C.literal("commit_segment"),...pr,policyRevision:C.number().int().nonnegative(),generation:C.string().min(1).max(256)}),C.strictObject({operation:C.literal("review"),receiptId:C.uuid().optional(),customerToken:bi.optional()})]);function xi(e,t){let n=new Set,r=new Set,i=new Set,a=[],s=new Map,c=new Map,u=new Map;function d(p){for(let b of Dt(p))f(b)}function f(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let b=t.savedGroups[p];b&&(i.add(p),u.set(p,b),a.push(()=>{!Array.isArray(b)&&b.type==="condition"&&d(b.condition)}))}function x(p){for(let b of["hashAttribute","fallbackAttribute"])if(p[b]!==void 0&&Mo(p[b]))throw new Error(`Funnel GB ${b} uses a reserved flow namespace`);d(p.condition);for(let b of p.parentConditions??[])k(b.id),d(b.condition)}function k(p,b=!1){let R=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!R){if(b)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),s.set(p,R),a.push(()=>{for(let Q of R.rules??[]){x(Q);for(let ne of Q.tracks??[])x(ne.experiment)}}))}function S(p){let b=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!b)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),c.set(p,b),a.push(()=>x(b)))}for(let p of e.graph.nodes){p.type==="feature"&&k(p.featureKey,!0),p.type==="split"&&S(p.experimentId),p.type==="condition"&&p.cases.forEach(R=>d(R.condition)),p.type==="offering"&&p.configuration.source==="feature"&&k(p.configuration.featureKey,!0);let b=p.type==="output"?p.value:p.type==="end"?p.output:null;b?.type==="feature"&&k(b.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(s),experiments:Object.fromEntries(c),savedGroups:Object.fromEntries(u)}}import{z as V}from"zod";import{z as dr}from"zod";var _l=dr.object({defaultLocale:mn,locales:dr.record(mn,dr.object({name:dr.string().max(80),description:dr.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"})});var sA=["customer_data","coupon_code"],cA=V.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Pl=V.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Si=(e,t)=>new Set(e.map(t)).size===e.length,uA=V.strictObject({currency:ce,amountMinor:V.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),lA=V.strictObject({featureId:V.uuid(),name:V.string().trim().min(1).max(120),allowance:V.string().max(40).nullable(),access:V.boolean()}),pA=V.strictObject({stripe:V.strictObject({prices:V.array(uA).min(1).max(50)}).optional(),apple:V.strictObject({productIds:V.array(cA).min(1).max(10)}).optional(),google:V.strictObject({products:V.array(V.strictObject({productId:Pl,basePlanId:Pl.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Si(e.stripe.prices,n=>n.currency)||e.apple&&!Si(e.apple.productIds,n=>n)||e.google&&!Si(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),dA=V.strictObject({name:V.string().trim().min(1).max(80),interval:V.enum(["free","week","month","year","one_time"]),intervalCount:V.number().int().min(1).max(100),trial:V.strictObject({days:V.number().int().min(1).max(730),cardRequired:V.boolean()}).nullable(),benefits:V.array(lA).max(50).refine(e=>Si(e,t=>t.featureId),"Duplicate benefit"),channels:pA,prepaid:V.array(us).max(100).optional()}),mA=V.strictObject({digest:En,content:V.strictObject({discount:Ft,duration:at,appliesTo:lo,displayCopy:_l.nullable(),firstPurchaseOnly:V.boolean(),qualificationRequired:V.boolean(),startsAt:V.iso.datetime().nullable(),endsAt:V.iso.datetime().nullable(),grantWindowHours:V.number().int().positive(),perCustomerLimit:V.number().int().positive()})}),fA=V.discriminatedUnion("type",[V.strictObject({type:V.literal("checkout"),product:ci}),V.strictObject({type:V.literal("close")}),V.strictObject({type:V.literal("action"),action:ko})]),Cl=V.strictObject({kind:V.literal("paywall"),formatVersion:V.literal(1),name:V.string().trim().min(1).max(80),offeringVersionId:V.uuid(),presentation:Rt,screen:it,products:Ur,catalog:V.record(V.uuid(),dA),buttons:V.record(Zn,fA),coupons:V.record(V.uuid(),mA)}).superRefine((e,t)=>{let n=b=>t.addIssue({code:"custom",message:b}),{screen:r}=e;Os(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Do(r,sA).forEach(n),Tt(r).some(b=>!b.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,s=new Set;Pt(r,b=>{let R="bind"in b?b.bind:void 0;R?.promotionCode&&n("Promotion codes must not be published"),R?.plan&&i.add(R.plan),R?.coupon&&a.add(R.coupon),b.type==="plan_picker"&&(b.planIds?.forEach(Q=>i.add(Q)),b.defaultPlan&&i.add(b.defaultPlan)),b.type==="text"&&b.feature&&s.add(b.feature.id)});let c=e.products.items.map(b=>b.productVersionId),u=Object.keys(e.catalog);(c.length!==u.length||c.some(b=>!Object.hasOwn(e.catalog,b)))&&n("Catalog must contain exactly the displayed Products");let d=new Set(c);e.products.defaultProductVersionId!==null&&!d.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let b of i)d.has(b)||n("Screen references a Product that is not displayed");for(let b of Object.values(e.catalog))!b.channels.stripe&&!b.channels.apple&&!b.channels.google&&n("A displayed Product needs at least one sales channel");let f=new Set(Object.values(e.catalog).flatMap(b=>b.benefits.map(R=>R.featureId)));for(let b of s)f.has(b)||n("Feature text must read a displayed benefit");let x=r.actions.filter(b=>b.type!=="navigate");r.actions.some(b=>b.type!=="event"&&b.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==x.length||x.some(b=>!Object.hasOwn(e.buttons,b.id)))&&n("Buttons must match the screen's actions");let S=!1;for(let b of Object.values(e.buttons)){if(b.type!=="checkout")continue;S=!0,(b.product.type==="fixed"?[b.product.productVersionId]:b.product.allowedProductVersionIds).some(Q=>!d.has(Q))&&n("Checkout may only sell displayed Products")}S||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(b=>!a.has(b)))&&n("Coupons must be exactly the bound Coupons")}),kl=V.strictObject({state:V.enum(["published","archived"]),controlRevision:V.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:V.uuid(),versions:V.record(V.uuid(),V.strictObject({version:V.number().int().positive(),artifact:V.string().min(1),sourceDigest:V.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var AA={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Yo=te.string().regex(/^[a-f0-9]{64}$/),ea=te.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),hA=ve.extend({environmentId:te.uuid()}),Rl=te.strictObject({features:te.array(te.string()).max(500),experiments:te.record(te.uuid(),te.array(te.string()).max(20)),savedGroups:te.array(te.string()).max(1e3)}),ra=te.strictObject({kind:te.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:te.number().int().positive(),url:te.string().min(1).max(2048),sha256:Yo,byteLength:te.number().int().positive().max(AA.maxArtifactBytes),generation:Yo.optional()}),gA=te.strictObject({state:te.enum(["active","paused","archived"]),controlRevision:ea,evaluationMode:te.enum(["local","remote"]),evaluationRevision:ea,currentVersionId:te.uuid(),versions:te.record(te.uuid(),te.strictObject({artifact:te.string(),dependencies:Rl,definitionDigest:En.optional(),couponDigests:te.record(te.uuid(),En).optional()}))}),t0=te.strictObject({kind:te.literal("sdk_configuration"),schemaVersion:te.literal(1),scope:hA,revision:ea,generation:Yo,policy:te.strictObject({refreshIntervalSeconds:te.number().positive().max(15),maxControlAgeSeconds:te.number().positive().max(60)}),gb:te.strictObject({features:te.string().nullable(),pageExperiments:te.string().nullable()}),artifacts:te.record(te.string(),ra),funnels:te.record(te.uuid(),gA),paywalls:te.record(te.uuid(),kl).optional()}).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.paywalls??{}))for(let i of Object.values(r.versions))n(i.artifact,"paywall");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 ta(e){if(Array.isArray(e))return`[${e.map(ta).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)}:${ta(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function bA(e){return wr(jr(typeof e=="string"?new TextEncoder().encode(e):e))}function n0(e){return bA(ta(e))}var na=class extends Error{constructor(n,r){super(n);this.dependency=r}dependency};function r0(e,t){let n=f=>f.type==="feature"?f.featureKey:f.type==="end"&&f.output?.type==="feature"?f.output.featureKey:f.type==="output"&&f.value.type==="feature"?f.value.featureKey:void 0,r=(f,x)=>e.graph.nodes.find(k=>f==="experiment"?k.type==="split"&&k.experimentId===x:f==="feature"&&n(k)===x)?.name,i=(f,x,k=r(x.type,x.resource))=>new na(f,{...x,...k?{step:k}:{}});for(let f of Object.values(e.references)){let x=f.type==="flag"?!Object.hasOwn(t.features,f.key)||t.remoteFeatures.includes(f.key)?{type:"feature",resource:f.key}:null:f.type==="experiment"?Object.hasOwn(t.experiments,f.id)?null:{type:"experiment",resource:f.id}:f.type==="saved_group"&&!Object.hasOwn(t.savedGroups,f.id)?{type:"saved_group",resource:f.id}:null;if(x)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...x})}let a=xi(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),s=new Set(t.remoteFeatures);for(let f of e.graph.nodes){let x=n(f);if(!x)continue;let k=a.features[x],S=f.type==="feature"?e.variables[f.writes.value]:e.outputSchema,p={type:"feature",resource:x};if(!k||!S)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...p},f.name);if([k.defaultValue,...(k.rules??[]).flatMap(R=>[...Object.hasOwn(R,"force")?[R.force]:[],...R.variations??[],...(R.tracks??[]).flatMap(Q=>Q.experiment.variations)])].some(R=>R===void 0||!lt(S,R)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...p},f.name)}let c=new Set,u=(f,x)=>{for(let k of Dt(f)){if(c.has(k))continue;let S=t.savedGroups[k];if(!S)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:k},x);c.add(k),!Array.isArray(S)&&S.type==="condition"&&u(S.condition,x)}},d=(f,x)=>{if(s.has(f)||!t.features[f])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:f},x)};for(let f of e.graph.nodes)if(f.type==="condition")for(let x of f.cases)u(x.condition,f.name);for(let[f,x]of Object.entries(a.features)){let k=r("feature",f);for(let S of x.rules??[]){u(S.condition,k);for(let p of[...S.parentConditions??[],...(S.tracks??[]).flatMap(b=>b.experiment.parentConditions??[])])d(p.id,k),u(p.condition,k);for(let p of S.tracks??[])u(p.experiment.condition,k)}}for(let[f,x]of Object.entries(a.experiments)){let k=r("experiment",f);u(x.condition,k);for(let S of x.parentConditions??[])d(S.id,k),u(S.condition,k)}for(let f of e.graph.nodes)if(f.type==="split"){let x=a.experiments[f.experimentId],k={type:"experiment",resource:f.experimentId};if(!x)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...k},f.name);for(let S of x.variations)if(typeof S!="string"||!Object.hasOwn(f.routes,S))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...k},f.name)}return Rl.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([f,x])=>[f,x.variations.map(String)])),savedGroups:[...c].sort()})}function i0(e){return Vt.parse(e)}var El=Be.strictObject({...wn,selector:Be.discriminatedUnion("type",[Be.strictObject({type:Be.literal("paywall"),paywallId:Be.uuid()}),Be.strictObject({type:Be.literal("version"),versionId:Be.uuid()})]),customerId:Be.uuid().optional(),commerce:Pr,locale:Be.string().min(1).max(35),requirement:An.optional()}),mr=Be.strictObject({id:Be.uuid(),paywallId:Be.uuid(),version:Be.number().int().positive(),document:Rn.omit({requirement:!0,offeringId:!0}),offering:Be.strictObject({id:Be.uuid()}),content:Be.strictObject({environmentId:Be.uuid(),offeringVersionId:Be.uuid(),artifact:ra.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:hn,check:Hn.nullable()}).superRefine((e,t)=>{let n=new Set(e.document.products.items.map(r=>r.productVersionId));(e.document.offeringVersionId!==e.offering.id||Object.values(e.capabilities.plans).some(r=>!n.has(r.versionId)))&&t.addIssue({code:"custom",message:"Paywall resolution must preserve the exact Offering Version and displayed Product subset"})}),fr=Be.strictObject(mr.shape).omit({document:!0,offering:!0}).extend({content:mr.shape.content.unwrap()});function A0(e,t){let n=Cl.parse(t);if(n.offeringVersionId!==e.content.offeringVersionId)throw new Error("Public Paywall Offering pin changed");let r=structuredClone(e.capabilities);for(let[i,a]of Object.entries(n.catalog)){let s=r.plans[i],c=a.channels.stripe?.prices.find(u=>u.currency===s?.currency);s&&c&&Object.assign(s,{amountMinor:c.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return mr.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Je}from"zod";var Dl={requestId:Je.uuid(),sourceId:Je.uuid(),expectedAvailable:fn},Tl=Je.discriminatedUnion("action",[Je.strictObject({...Dl,action:Je.enum(["add","subtract","set_remaining"]),amount:we}),Je.strictObject({...Dl,action:Je.literal("edit"),granted:we,expiresAt:Je.iso.datetime({offset:!0}).nullable(),nextResetAt:Je.iso.datetime({offset:!0}).nullable(),expectedRevision:Je.number().int().nonnegative()})]),ia=Je.strictObject({sourceId:Je.uuid(),available:fn,held:fn,spent:fn,adjustmentGrantId:Je.uuid().nullable()}),Ml=ia.extend({granted:fn,expiresAt:Je.iso.datetime({offset:!0}).nullable(),nextResetAt:Je.iso.datetime({offset:!0}).nullable(),revision:Je.number().int().nonnegative()});import{z as ct}from"zod";var Bl=ct.discriminatedUnion("action",[ct.object({action:ct.literal("upsert"),externalId:ct.string().min(1).max(128),name:ct.string().trim().min(1).max(80)}).strict(),ct.object({action:ct.literal("archive"),entityId:ct.uuid()}).strict()]),ql=ct.object({id:ct.uuid(),externalId:ct.string().min(1).max(128),name:ct.string().min(1).max(80),archived:ct.boolean()}).strict();import{z as Ge}from"zod";import{z as cn}from"zod";var Nl=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],zl=cn.string().regex(/.+\/.+/),oa=cn.number().min(-100),sn=cn.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),yA=cn.strictObject({input:sn,output:sn,cache_read:sn.optional(),cache_write:sn.optional(),reasoning:sn.optional(),input_audio:sn.optional(),output_audio:sn.optional()}),aa=(e,t)=>cn.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),O0=cn.strictObject({defaultMarkup:oa,providerMarkups:aa(cn.string().min(1),oa),modelMarkups:aa(zl,oa),customModels:aa(zl,yA.partial())});import{z as Z}from"zod";var un=Z.iso.datetime({offset:!0}),Lt=Z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),xA=Z.discriminatedUnion("kind",[Z.object({kind:Z.literal("absolute"),from:un,to:un}).strict(),Z.object({kind:Z.literal("last_days"),days:Z.union([Z.literal(1),Z.literal(7),Z.literal(30),Z.literal(90)])}).strict(),Z.object({kind:Z.literal("billing_cycles"),membershipId:Z.uuid(),count:Z.number().int().min(1).max(12),includeCurrent:Z.boolean()}).strict()]),Fl=Z.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"),SA=Z.object({key:Z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:Z.array(Z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),ln=Z.object({range:xA,timezone:Fl,filterBy:Z.array(SA).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:Z.enum(["hour","day","week","month"]),internal_feature_id:Z.uuid().nullable(),entityId:Z.uuid().nullable(),topN:Z.number().int().min(1).max(50).nullable(),groupBy:Z.union([Z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),Z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:Z.object({bucket:un,group:Z.string().max(240),isOther:Z.boolean(),internal_feature_id:Z.uuid(),resourceId:Z.uuid()}).strict().nullable(),limit:Z.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)"})}),Ul=Z.object({from:un,to:un,interval:Z.enum(["hour","day","week","month"]),timezone:Fl,rows:Z.array(Z.object({bucket:un,group:Z.string().max(240),isOther:Z.boolean(),internal_feature_id:Z.uuid(),resourceId:Z.uuid(),consumedUnits:Lt,refundedUnits:Lt,reservedUnits:Lt,charged:Lt,refunded:Lt,reserved:Lt,netUnits:Lt,netCharged:Lt}).strict()).max(100),nextCursor:Z.object({bucket:un,group:Z.string().max(240),isOther:Z.boolean(),internal_feature_id:Z.uuid(),resourceId:Z.uuid()}).strict().nullable()}).strict();var zn=Ge.string().regex(/^(0|[1-9]\d{0,29})$/),Vl=Ge.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),sa=Ge.strictObject({bucket:Ge.iso.datetime({offset:!0}),group:Ge.string().max(240),isOther:Ge.boolean(),internal_feature_id:Ge.uuid()}),Ll=Ge.strictObject({...ln.shape,groupBy:Ge.union([Ge.enum(["customer","entity","entitlement"]),Ge.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:sa.nullable()}).superRefine((e,t)=>{let n=ln.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),$l=Ge.strictObject({from:Ge.iso.datetime({offset:!0}),to:Ge.iso.datetime({offset:!0}),interval:ln.shape.interval,timezone:ln.shape.timezone,rows:Ge.array(Ge.strictObject({...sa.shape,eventCount:zn,units:Vl,tokenEventCount:zn,tokens:Ge.strictObject(Object.fromEntries(Nl.map(e=>[e,zn]))),totalTokens:zn,providerCostEventCount:zn,providerCostUsd:Vl,invalidTelemetryEventCount:zn})).max(100),nextCursor:sa.nullable()});import{z as Ee}from"zod";var Gl=Ee.object({requestId:Ee.uuid(),items:Ee.array(Ee.object({customerId:Ee.uuid(),command:Gn.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"),Kl=Ee.object({batchId:Ee.uuid(),after:Ee.number().int().min(-1).max(999),limit:Ee.number().int().min(1).max(100)}).strict(),Hl=Ee.object({batchId:Ee.uuid(),status:Ee.enum(["queued","complete"]),total:Ee.number().int().min(1).max(1e3),processed:Ee.number().int().min(0).max(1e3),items:Ee.array(Ee.object({position:Ee.number().int().min(0).max(999),customerId:Ee.uuid(),idempotencyKey:Ee.string().min(1).max(120),status:Ee.enum(["queued","accepted","rejected","failed"]),receipt:Kn.nullable(),errorCode:Ee.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:Ee.number().int().min(0).max(999).nullable()}).strict();import{z as g}from"zod";var vA=g.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Zl=g.enum(["draft","active","paused","archived"]),Ql=g.string().min(1).max(256),Jl=g.array(Ql).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),IA=g.strictObject({duration:g.enum(["day","week","month","year"]),length:g.number().int().min(1).max(3660)}),OA=g.strictObject({internal_feature_id:g.uuid(),allowance:g.number().nonnegative().max(1e15).nullable(),expiry:IA.nullable()}),wA=g.discriminatedUnion("type",[g.strictObject({type:g.literal("feature_grant"),grants:g.array(OA).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),g.strictObject({type:g.literal("free_product"),productId:Ql,duration:at}),g.strictObject({type:g.literal("invoice_credits"),amount:g.number().positive().max(1e8),duration:at,rollover:g.boolean(),productIds:Jl})]),jA=g.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),Wl=g.object({key:jA,name:g.string().trim().min(1).max(80),configuration:wA}).strict(),Xl=g.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),ca=g.object({code:Xl,maxUses:g.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:g.boolean()}).strict(),Yl=g.object({key:g.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:g.string().trim().min(1).max(80),rewardId:g.uuid(),redeemOn:g.enum(["customer_creation","checkout"]),receivedBy:g.enum(["referrer","all"]),maxRedemptions:g.number().int().min(1).max(1e6).nullable(),productIds:Jl,excludeTrial:g.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),ep={id:g.uuid(),projectId:g.uuid(),environmentId:g.uuid(),revision:g.number().int().nonnegative(),status:Zl,createdAt:g.iso.datetime({offset:!0}),updatedAt:g.iso.datetime({offset:!0})},_A=Wl.extend(ep).strict(),PA=Yl.safeExtend(ep).strict(),z0=g.strictObject({id:g.uuid(),key:g.string(),name:g.string(),type:vA,status:Zl}),N0=g.discriminatedUnion("action",[g.object({action:g.literal("save"),id:g.uuid().nullable(),revision:g.number().int().nonnegative(),input:Wl}).strict(),g.object({action:g.enum(["activate","pause","resume","archive","delete"]),id:g.uuid(),revision:g.number().int().nonnegative()}).strict()]),F0=g.discriminatedUnion("action",[g.object({action:g.literal("save"),id:g.uuid().nullable(),revision:g.number().int().nonnegative(),input:Yl}).strict(),g.object({action:g.enum(["activate","pause","resume","archive","delete"]),id:g.uuid(),revision:g.number().int().nonnegative()}).strict()]),tp=g.object({id:g.uuid(),rewardId:g.uuid(),programId:g.uuid().nullable(),customerId:g.uuid(),referrerId:g.uuid().nullable(),status:g.enum(["pending","applied","unavailable"]),result:g.record(g.string(),g.unknown()).nullable(),createdAt:g.iso.datetime({offset:!0})}).strict(),np=g.object({code:Xl,requestId:g.uuid()}).strict(),rp=g.strictObject({redemptionId:g.uuid(),currency:ce,requestId:g.uuid(),accepted:g.literal(!0)}),CA=g.strictObject({type:g.literal("checkout"),orderId:g.uuid(),productVersionId:g.uuid(),currency:ce,duration:at,renewalAmountMinor:g.number().int().positive().max(1e8),status:g.enum(["created","pending","trialing","paid","cancelled","failed"]),url:g.url().nullable()}),ip=g.discriminatedUnion("type",[CA,g.strictObject({type:g.literal("subscription"),operationId:g.uuid(),membershipId:g.uuid(),productVersionId:g.uuid(),currency:ce,duration:at,renewalAmountMinor:g.number().int().positive().max(1e8),status:g.enum(["pending","running","applied","failed"])})]),op=g.object({programId:g.uuid(),requestId:g.uuid()}).strict(),ap=g.object({id:g.uuid(),programId:g.uuid(),code:ca.shape.code,createdAt:g.iso.datetime({offset:!0})}).strict(),U0=g.object({rows:g.array(_A).max(100),nextCursor:g.uuid().nullable()}).strict(),V0=g.object({rows:g.array(PA).max(100),nextCursor:g.uuid().nullable()}).strict(),kA=ca.extend({id:g.uuid(),redemptions:g.number().int().nonnegative()}).strict(),RA=g.strictObject({id:g.uuid(),programId:g.uuid().nullable(),customerId:g.uuid().nullable(),referrerId:g.uuid().nullable(),code:g.string().nullable(),status:g.enum(["pending","triggered","applied"]),createdAt:g.iso.datetime({offset:!0})}),L0=g.object({codes:g.array(kA).max(100),redemptions:g.array(RA).max(100),customers:g.record(g.uuid(),g.string()),codesCursor:g.uuid().nullable(),redemptionsCursor:g.uuid().nullable()}).strict(),$0=g.discriminatedUnion("action",[g.object({action:g.literal("create"),rewardId:g.uuid(),revision:g.number().int().nonnegative(),input:ca}).strict(),g.object({action:g.literal("remove"),rewardId:g.uuid(),revision:g.number().int().nonnegative(),codeId:g.uuid()}).strict()]);import{z as m}from"zod";import{z as B}from"zod";var It={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},Ar=e=>new Set(e).size===e.length,ua=B.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),EA=B.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),hr=B.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"))),DA=B.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),sp=B.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var cp=B.strictObject({id:B.uuid(),repo:EA,platform:B.enum(["github","gitlab","bitbucket"]),branches:B.array(hr).min(1).max(4).refine(Ar),workflow:B.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:B.array(B.uuid()).min(1).max(4).refine(Ar),include:B.array(sp).min(1).max(16),exclude:B.array(sp).max(16),methods:B.array(B.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(Ar),maxAgeHours:B.number().int().min(1).max(720)}),up=cp.extend({revision:B.number().int().positive()}),H0=B.strictObject({repository:cp,expectedRevision:B.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),lp=B.strictObject({repositoryId:B.uuid(),branch:hr}),TA=B.array(ua).max(It.keys).refine(Ar),pp=B.strictObject({repository:up.omit({keyIds:!0}),branch:hr,keys:TA,keySetHash:B.string().regex(/^[a-f0-9]{64}$/)}),MA=B.strictObject({filePath:DA,startingLineNumber:B.number().int().min(1).max(1e7)}),la=B.strictObject({protocol:B.literal(1),repositoryId:B.uuid(),branch:hr,workflow:B.string().max(200),configurationRevision:B.number().int().positive(),keySetHash:B.string().regex(/^[a-f0-9]{64}$/),commit:B.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:B.uuid(),runNumber:B.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:B.number().int().min(1).max(1e4),scannerVersion:B.literal("1"),scannedAt:B.iso.datetime({offset:!0}),coverage:B.strictObject({complete:B.literal(!0),files:B.number().int().min(0).max(It.files),sourceBytes:B.number().int().min(0).max(It.sourceBytes),unresolvedCalls:B.number().int().min(0).max(1e6),unsupportedFiles:B.number().int().min(0).max(It.files)}),features:B.array(B.strictObject({key:ua,refs:B.array(MA).max(It.referencesPerKey)})).max(It.keys)}).superRefine((e,t)=>{Ar(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)>It.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),pa=B.strictObject({scanId:B.uuid(),commit:B.string(),receivedAt:B.string(),references:B.number().int().nonnegative(),removedReferences:B.number().int().nonnegative()}),BA=pa.extend({repositoryId:B.uuid(),branch:hr,workflow:B.string(),digest:B.string(),configurationRevision:B.number().int().positive(),runNumber:B.number().int().positive(),runAttempt:B.number().int().positive(),scannedAt:B.string(),keySetHash:B.string(),coverage:la.shape.coverage}),qA=B.strictObject({repositories:B.array(up).max(It.repositories),scans:B.array(BA).max(It.repositories*It.branches)}),zA=B.strictObject({key:ua,references:B.number().int().nonnegative(),coveredTargets:B.number().int().nonnegative(),expiredTargets:B.number().int().nonnegative(),uncertainTargets:B.number().int().nonnegative()}),Z0=B.strictObject({available:B.boolean().default(!0),settings:qA,expectedTargets:B.number().int().min(0).max(80),features:B.array(zA).max(2001),truncated:B.boolean()});import{z as qe}from"zod";var NA=qe.enum(["checkout.session.completed","checkout.session.expired","checkout.session.async_payment_succeeded","checkout.session.async_payment_failed","customer.subscription.created","customer.subscription.updated","customer.subscription.deleted","customer.subscription.paused","customer.subscription.resumed","invoice.created","invoice.paid","customer.discount.created","customer.discount.updated","refund.created","refund.updated","refund.failed","charge.refunded"]),FA=qe.strictObject({provider:qe.literal("stripe"),accountId:qe.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:qe.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:NA,occurredAt:qe.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:qe.record(qe.string(),qe.unknown()).and(qe.object({id:qe.string().min(1).max(255),object:qe.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:qe.boolean()}))}),dp=qe.union([FA,Ds]),mp=qe.strictObject({id:qe.uuid(),eventId:qe.string().min(1).max(200),source:qe.literal("merchant"),providerVerified:qe.literal(!1),outcome:qe.string().min(1).max(100)});import{z as We}from"zod";var Ap={customerId:We.uuid(),eventId:We.string().trim().min(1).max(200),grantId:We.uuid(),occurredAt:We.iso.datetime({offset:!0})},hp=We.strictObject({...Ap,productVersionId:We.uuid(),subscriptionId:We.string().trim().min(1).max(255)}),gp=We.strictObject({...Ap,merchandiseId:We.uuid()}),bp=We.union([hp,gp]),fp={id:We.uuid(),couponId:We.uuid(),status:We.literal("redeemed"),source:We.literal("merchant"),recordedAt:We.iso.datetime({offset:!0})},yp=We.union([hp.extend(fp),gp.extend(fp)]);import{z as U}from"zod";var xp=cu,UA=xp.extend({invoice_id:xp.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),da=U.strictObject({name:U.string().trim().min(1).max(255),memo:U.string().max(1e4).nullable().optional(),footer:U.string().max(1e4).nullable().optional(),net_terms_days:U.number().int().positive().nullable().optional()}),VA=da.extend({id:U.string().min(1).max(255),created_at:U.number().nullable()}),Sp=U.strictObject({items:U.array(VA).max(50),nextCursor:U.uuid().nullable()}),rI=U.discriminatedUnion("action",[U.strictObject({action:U.literal("create"),requestId:U.uuid(),values:da}),U.strictObject({action:U.literal("update"),id:U.string().min(1).max(255),values:da}),U.strictObject({action:U.literal("delete"),id:U.string().min(1).max(255)})]),vp=U.discriminatedUnion("action",[U.strictObject({action:U.literal("create"),requestId:U.uuid(),params:_n}),U.strictObject({action:U.enum(["finalize","send","pay","void"]),requestId:U.uuid(),invoiceId:U.uuid()}),U.strictObject({action:U.literal("reissue"),requestId:U.uuid(),invoiceId:U.uuid(),params:UA})]),ma=U.strictObject({id:U.uuid(),customerId:U.uuid(),providerInvoiceId:U.string().nullable(),status:U.enum(["draft","open","paid","void","uncollectible"]),currency:U.string(),totalMinor:U.string().regex(/^-?\d+$/),paidMinor:U.string().regex(/^\d+$/),refundedMinor:U.string().regex(/^\d+$/),hostedInvoiceUrl:U.url().nullable(),createdAt:U.number(),collectionMethod:U.enum(["send_invoice","charge_automatically"]).nullable()}),Ip=ma.extend({lines:U.array(U.strictObject({id:U.uuid(),description:U.string(),amountMinor:U.string().regex(/^-?\d+$/),netAmountMinor:U.string().regex(/^-?\d+$/),quantity:U.number().nullable(),periodStart:U.number().nullable(),periodEnd:U.number().nullable()})).max(1e3)}),Nn=U.strictObject({taskId:U.uuid(),status:U.enum(["ready","running","done","dead"]),invoice:ma.nullable(),errorCode:U.string().nullable()}),Op=U.strictObject({items:U.array(ma).max(50),nextCursor:U.uuid().nullable(),operations:U.array(Nn).max(50),operationsLimited:U.boolean()});var LA=m.enum(["customers:read","customers:write","entitlements:read","content:read","sessions:create","funnels:run","offers:resolve","offers:grant","billing:read","billing:write","credits:read","credits:consume","credits:manage","features:read","events:write","messaging:write","code-references:read","code-references:write","app-manifests:write"]),wp={scope:ve,permissions:m.array(LA),expiresAt:m.iso.datetime().nullable()},ZI=m.discriminatedUnion("kind",[m.object({...wp,kind:m.literal("server"),keyId:m.string().min(1)}),m.object({...wp,kind:m.literal("customer"),customerId:m.string().min(1),identityKind:m.enum(["identified","guest"]),expiresAt:m.iso.datetime()})]),_=m.object({requestId:m.uuid(),scope:ve}).strict(),$A=ml.safeExtend({fingerprint:Ai.optional()}).strict(),GA=_.extend({customer:Bn,created:m.boolean()});function jp(){return _.extend({offer:Yn.nullable(),reason:mc.nullable()})}var j={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:Qc,response:_.extend({message:m.object({messageId:m.uuid(),channel:or,acceptedAt:m.iso.datetime({offset:!0}),status:m.enum(["accepted","sending","completed","canceled"]),replayed:m.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:m.strictObject({messageId:m.uuid()}),response:_.extend({message:m.object({id:m.uuid(),channel:or,status:m.enum(["accepted","sending","completed","canceled"]),deliveries:m.array(m.object({id:m.uuid(),status:Wc,attempts:m.number().int().nonnegative(),receipts:m.array(m.object({kind:Xc,occurredAt:m.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Ys,response:_.extend({installation:$r})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:ec,response:_.extend({installation:$r})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Lr,response:_.extend({installation:$r})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:m.strictObject({channel:or}),response:_.extend({preference:no})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:Jc,response:_.extend({preference:no})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:m.strictObject({cursor:m.uuid().optional()}),response:_.extend({templates:Sp})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),params:_n}),response:_.extend({preview:xo})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),requestId:m.uuid(),params:_n}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:_.extend({operation:Nn})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:m.strictObject({customerId:m.uuid(),command:vp}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:_.extend({operation:Nn})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),taskId:m.uuid()}),response:_.extend({operation:Nn})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),cursor:m.uuid().optional()}),response:_.extend({invoices:Op})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:m.strictObject({customerId:m.uuid(),invoiceId:m.uuid()}),response:_.extend({invoice:Ip})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:lp,response:_.extend({config:pp})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:la,response:_.extend({receipt:pa})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:m.strictObject({}),response:_.extend({payload:Eo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Ju,response:_.merge(Wu)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Xu,response:_.merge(Yu)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid(),sourceId:m.uuid()}),response:_.extend({balance:Ml})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:Tl}),response:_.extend({balance:ia})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:m.strictObject({internal_feature_id:m.uuid(),customerId:m.uuid().optional(),entityId:m.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:_.extend({internal_feature_id:m.uuid(),config:so,model_markups:Zr})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid(),query:is}),response:_.extend({usage:qi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:os}),response:_.extend({usage:qi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:m.strictObject({customerId:m.uuid(),command:Nc}),response:_.extend({grant:fo})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Fc,response:_.extend({grants:Uc})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:m.union(Uu.options.map(e=>e.extend({customerId:m.uuid().optional(),customerToken:m.string().regex(Bt).optional()}))),response:_.extend({operation:Vu})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:ku.extend({customerId:m.uuid().optional()}),response:_.extend({setup:wo})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:Ru.extend({customerId:m.uuid().optional()}),response:_.extend({setup:wo})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:_u.safeExtend({customerId:m.uuid()}),response:_.extend({batch:sr})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ni.extend({customerId:m.uuid()}),response:_.extend({batch:sr})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ni.extend({customerId:m.uuid()}),response:_.extend({batch:sr})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ni.extend({customerId:m.uuid()}),response:_.extend({batch:sr})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:m.discriminatedUnion("action",[ri.options[0].extend({customerId:m.uuid()}),ri.options[1].extend({customerId:m.uuid()}),ri.options[2].extend({customerId:m.uuid()})]),response:_.extend({trial:Oo})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:Pu.extend({customerId:m.uuid()}),response:_.extend({trial:Oo})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ai,response:_.extend({subscriptions:zu})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ai,response:_.extend({purchases:Nu})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:Mu,response:_.extend({conflicts:Fu})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:Bu,response:_.extend({resolution:qu})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Du,response:_.extend({verification:Tu})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:yu.safeExtend({...wn,customerId:m.uuid().optional()}),response:_.extend({quote:Pn})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:dp,response:_.extend({record:mp})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:nn.extend({customerId:m.uuid().optional(),intent:m.enum(["confirm","cancel"]).optional()}),response:_.extend({operation:Cn})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:nn.extend({customerId:m.uuid().optional()}),response:_.extend({operation:Cn})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:vu.safeExtend({customerId:m.uuid().optional()}),response:_.extend({quote:Ou})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:nn.extend({customerId:m.uuid().optional(),intent:m.enum(["confirm","cancel"]).optional()}),response:_.extend({operation:So})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:nn.extend({customerId:m.uuid().optional()}),response:_.extend({operation:So})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:wu.safeExtend({customerId:m.uuid()}),response:_.extend({quote:vo})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:nn.extend({customerId:m.uuid()}),response:_.extend({operation:ti})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:nn.extend({customerId:m.uuid()}),response:_.extend({operation:ti})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:_c,response:_.extend({controls:mo})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:xc,response:_.extend({prepared:vc})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Ic,response:_.extend({authorization:Jr})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Ec,response:_.extend({coupons:Dc})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Oc,response:_.extend({authorization:Jr})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:kc,response:_.extend({invoices:Rc})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Cc.extend({customerId:m.uuid()}),response:_.extend({operation:Nn})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Pc,response:_.extend({invoice:nr})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:m.object({customerId:m.uuid(),command:jc}).strict(),response:_.extend({controls:mo})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:m.object({customerId:m.uuid(),command:Bl}).strict(),response:_.extend({entity:ql})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:m.strictObject({customerId:m.uuid().nullable(),query:Ll}),response:_.extend({analytics:$l})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:m.object({customerId:m.uuid().nullable(),query:ln}).strict(),response:_.extend({analytics:Ul})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Gl,response:_.extend({batchId:m.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Kl,response:_.extend({batch:Hl})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:ps.extend({customerId:m.string().min(1).optional()}),response:_.extend({check:Hn})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:m.strictObject({kind:zt,selector:m.discriminatedUnion("type",[m.strictObject({type:m.literal("resource"),id:m.uuid()}),m.strictObject({type:m.literal("version"),id:m.uuid()})]),customerId:m.string().min(1).optional()}),response:_.extend({content:eo})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:El,response:_.extend({paywall:fr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:m.strictObject({...wn,selector:Ku,customerId:m.string().min(1).optional(),commerce:Pr,requirement:An.optional()}),response:_.extend({offering:Hu,candidates:m.array(ds).max(20),availability:m.array(m.strictObject({productVersionId:m.uuid(),available:m.boolean(),reason:m.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:Hn.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),entityId:m.uuid().optional()}).strict(),response:_.extend({holdings:as})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),query:ss}).strict(),response:_.extend({ledger:cs})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Vc.extend({customerId:m.uuid().optional()}),response:_.extend({detail:Lc})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Ao.safeExtend({customerId:m.uuid().optional()}),response:_.extend({statement:$c})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:m.object({customerId:m.uuid().optional(),command:Gn.options[0]}).strict(),response:_.extend({quote:rs})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:m.strictObject({customerId:m.uuid(),command:m.union([m.strictObject({eventName:m.string().min(1),quantity:we.optional(),properties:_t.optional(),entityId:m.uuid().optional(),idempotencyKey:m.string().min(1).max(120)}),m.strictObject({internal_feature_id:m.uuid(),quantity:we.optional(),properties:_t.optional(),entityId:m.uuid().optional(),idempotencyKey:m.string().min(1).max(120)})])}),response:_.extend({receipts:m.array(Kn).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:m.object({customerId:m.uuid(),command:Gn.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:_.extend({receipt:Kn})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:np,response:_.extend({redemption:tp})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:op,response:_.extend({referralCode:ap})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:rp,response:_.extend({checkout:ip})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:Kc,response:_.extend({seats:bo})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:Hc,response:_.extend({seats:bo})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:$A,response:GA},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Vo,response:_.extend({customer:Bn})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:hl,response:_.extend(gl.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Al,response:_.extend(fl.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:m.object({customerId:m.uuid()}).strict(),response:_.extend(qt.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:m.strictObject({}),response:_.extend(qt.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:m.strictObject({customerId:m.uuid(),sessionId:m.uuid().optional()}),response:_.extend({revoked:m.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ai.optional()}),response:_.extend({customerId:m.uuid(),guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:m.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:_.extend(qt.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:m.strictObject({guestToken:m.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:m.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:m.uuid()}),response:_.extend({customer:Bn,switched:m.boolean(),replayed:m.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:m.strictObject({code:m.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:m.uuid()}),response:jp()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:m.object({}).strict(),response:_.extend({offers:m.array(Yn)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:m.object({customerId:m.string().min(1).max(255).optional(),couponId:m.uuid(),...wn,requestId:m.uuid(),couponContentDigest:m.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:jp()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:bp,response:_.extend({receipt:yp})}},QI={recordBillingEvent:j.recordBillingEvent,sendMessage:j.sendMessage,readMessage:j.readMessage,bindPushInstallation:j.bindPushInstallation,readPushInstallation:j.readPushInstallation,updatePushAddress:j.updatePushAddress,readMessagingPreference:j.readMessagingPreference,setMessagingPreference:j.setMessagingPreference,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,prepareBillingAdjustment:j.prepareBillingAdjustment,manageBillingLimits:j.manageBillingLimits,createCustomer:j.createCustomer,getCustomer:j.getCustomer,listCustomers:j.listCustomers,updateCustomer:j.updateCustomer,createSession:j.createSession,refreshSession:j.refreshSession,revokeSessions:j.revokeSessions,createGuestCustomer:j.createGuestCustomer,resumeGuestSession:j.resumeGuestSession,claimGuestCustomer:j.claimGuestCustomer,checkEntitlement:j.checkEntitlement,resolveOffering:j.resolveOffering,resolveContent:j.resolveContent,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};import{z as fa}from"zod";var gr=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Aa(e,t,n){let r={},i,a,s,c="next",u;switch(e.type){case"entry":u=e.next;break;case"condition":{let d=e.cases.findIndex(f=>Bi(t.attributes??{},f.condition,t.savedGroups??{}));c=d<0?"default":`case:${d}`,u=d<0?e.default:e.cases[d].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new gr("Required GB Feature is unavailable");i=$n(e.featureKey,t),s=i.value,Object.assign(r,Wt(e,{value:s})),u=e.next;break;case"split":{let d=n[e.experimentId];if(!d)throw new gr("Required GB Experiment is unavailable");if(a=Ya(d,t),s=a.value,c=a.inExperiment&&!a.passthrough&&typeof s=="string"?s:"notParticipating",u=c==="notParticipating"?e.notParticipating:e.routes[c],!u)throw new gr("Experiment Variation has no published route");break}case"offering":{let d=e.configuration.source==="fixed"?e.configuration.versionId:$n(e.configuration.featureKey,t).value;s={type:"offering_version",id:fa.uuid().parse(d)},Object.assign(r,Wt(e,{value:s})),u=e.next;break}case"coupon":case"coupons":s=e.type==="coupons"?e.couponIds.map(d=>({type:"reward",id:d})):{type:"reward",id:e.couponId},Object.assign(r,Wt(e,{value:s})),u=e.next;break}return{port:c,target:u,projections:r,...s===void 0?{}:{value:s},...i?{feature:i}:{},...a?{experiment:a}:{}}}function rO(e,t,n){fa.uuid().parse(e),fa.number().int().nonnegative().parse(t);let r=wr(jr(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 D}from"zod";var $t=D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),KA=D.enum(["running","waiting","completed","closed","ineligible","failed"]),HA=D.discriminatedUnion("type",[Fo,D.strictObject({type:D.literal("wait"),receiptId:D.uuid(),kind:D.enum(["timer","event","operation"]),deadline:D.iso.datetime({offset:!0}).nullable(),eventName:$t.optional()}),D.strictObject({type:D.literal("open_url"),receiptId:D.uuid(),url:$o,openIn:Go}),D.strictObject({type:D.literal("event"),receiptId:D.uuid(),event:$t})]),ZA=D.strictObject({type:D.literal("funnel"),id:D.uuid(),versionId:D.uuid()}),QA={id:$t,presentation:Rt,outputs:D.array($t).max(250),inputs:Fi,values:D.record(D.string(),me).optional(),offeringKey:Te.optional(),capabilities:hn,customerData:bs,dataCursors:D.record($t,kr.nullable())},JA=D.strictObject({...QA,content:D.strictObject({type:D.literal("document"),document:it})}),ha=D.strictObject({id:D.uuid(),source:ZA,revision:D.number().int().nonnegative(),visit:D.number().int().nonnegative(),nodeId:$t,nodeType:D.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:KA,stopped:D.boolean(),canBack:D.boolean(),authenticated:D.boolean(),locale:D.string().min(1).max(35),answers:Zt,parameters:xt,variables:D.record(D.string(),me),output:me.nullable(),screen:JA.nullable(),paywall:D.strictObject({receiptId:D.uuid(),resolution:D.union([mr,fr]),quote:Pn.nullable(),operation:Cn.nullable(),purchaseRequestId:D.uuid().nullable(),selectionGeneration:D.number().int().nonnegative().optional(),canReselect:D.boolean().optional()}).nullable(),instruction:HA.nullable(),pendingRequest:D.strictObject({requestId:D.uuid(),authenticationRequired:D.boolean()}).nullable(),runExpiresAt:D.iso.datetime({offset:!0}),credentialExpiresAt:D.iso.datetime({offset:!0}).nullable()}),ga=D.strictObject({scope:ve,run:ha,settlement:D.strictObject({requestId:D.uuid(),state:D.enum(["pending","unknown","settled"]),operationId:D.uuid().nullable(),receiptId:D.uuid().nullable().optional()}).optional(),purchase:D.strictObject({receiptId:D.uuid(),quote:Pn.nullable(),operation:Cn.nullable(),canReselect:D.boolean().optional()}).optional(),review:D.strictObject({activeOperationId:D.uuid().nullable(),pages:D.array(D.strictObject({receiptId:D.uuid(),nodeId:$t,visit:D.number().int().nonnegative()})).max(100),page:D.strictObject({receiptId:D.uuid(),nodeId:$t,visit:D.number().int().nonnegative(),document:it,answers:Zt,inputs:Fi,values:D.record(D.string(),me).optional()}).nullable(),coupons:D.array(D.strictObject({grantId:D.uuid(),status:D.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:D.string().nullable()})).max(100),purchases:D.array(D.strictObject({receiptId:D.uuid(),operationId:D.uuid(),status:D.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:D.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:D.uuid().optional()}),_p=ga.extend({run:ha.extend({paywall:ha.shape.paywall.unwrap().extend({resolution:fr}).nullable()})});var yO="X-Indiana-Server-Key";import{z as tt}from"zod";import{z as vi}from"zod";var IO=vi.strictObject({operation:vi.literal("renew_run"),runId:vi.uuid(),customerId:vi.uuid()}),Pp=ga.refine(e=>!!e.runToken,"Renewal returns a credential"),Cp=_p.refine(e=>!!e.runToken,"Renewal returns a credential");var RO=tt.discriminatedUnion("operation",[tt.strictObject({operation:tt.literal("campaign_decide"),...Lo}).refine(rn,on),tt.strictObject({operation:tt.literal("campaign_start"),funnelId:tt.uuid(),requestId:tt.uuid(),customer:Tn,customerData:Mn.optional(),locale:tt.string().min(1).max(35),parameters:xt,cooldownSeconds:tt.number().int().min(1).max(2592e3)}).refine(rn,on)]),WA=tt.union([tt.strictObject({scope:ve,suppressed:tt.literal(!0),reason:tt.enum(["frequency","in_progress"]),retryAt:tt.iso.datetime({offset:!0})}),Pp]),EO=tt.union([WA.options[0],Cp]);import{z as se}from"zod";var Fn=se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Rp=se.strictObject({entry:Fn,nodes:se.array(se.strictObject({id:Fn,type:se.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:se.record(se.string(),Fn),writes:se.record(Te,Te),resources:se.strictObject({screenId:Fn.optional(),paywallVersionId:se.uuid().optional(),couponId:se.uuid().optional(),couponIds:se.array(se.uuid()).max(20).optional(),experimentId:se.uuid().optional(),featureKey:se.string().optional(),offeringVersionId:se.uuid().optional()})})).min(1).max(500)}),kp={scope:ve,funnelId:se.uuid(),versionId:se.uuid(),evaluationRevision:se.number().int().nonnegative(),expiresAt:se.iso.datetime({offset:!0}).nullable(),topology:Rp},Un=se.discriminatedUnion("evaluationMode",[se.strictObject({...kp,evaluationMode:se.literal("local"),growth:Mt,conditions:se.record(Fn,se.array(se.strictObject({condition:Ht,port:se.string()})))}),se.strictObject({...kp,evaluationMode:se.literal("remote")})]),XA=Un.options[0].extend({evaluation:se.strictObject({maxTransitions:se.number().int().min(1).max(1e4),variables:se.record(Te,Sn),outputSchema:xn,terminals:se.record(Fn,se.strictObject({outcome:se.enum(["completed","closed","ineligible","failed"]),output:ur.nullable()}))})});function YA(e){return Rp.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(s=>s.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,s)=>{n[`case:${s}`]=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=se.uuid().parse(t.action.coupon.value.id));break;case"external_page":n.opened=t.opened,n.failed=t.failed;break;case"wait":t.wait.type==="duration"?n.elapsed=t.wait.elapsed:(n.received=t.wait.received,n.timeout=t.wait.timeout);break;case"end":case"output":break}t.type==="feature"&&(r.featureKey=t.featureKey),t.type==="offering"&&t.configuration.source==="feature"&&(r.featureKey=t.configuration.featureKey);let i=t.type==="output"?t.value:t.type==="end"?t.output:void 0;return i?.type==="feature"&&(r.featureKey=i.featureKey),t.type==="coupon"&&(r.couponId=t.couponId),t.type==="coupons"&&(r.couponIds=t.couponIds),t.type==="offering"&&t.configuration.source==="fixed"&&(r.offeringVersionId=t.configuration.versionId),{id:t.id,type:t.type,outputs:n,resources:r,writes:"writes"in t?t.writes??{}:{}}})})}function eh(e){let t=Vt.parse(e.document),n=e.evaluationMode==="local"?Mt.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:YA(t)};return Un.parse(e.evaluationMode==="remote"?r:{...r,growth:xi(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,s)=>({condition:a.condition,port:`case:${s}`}))]))})}function VO(e){let t=eh(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Vt.parse(e.document);return XA.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 mt}from"zod";import{z as Ke}from"zod";var Ep=Ke.discriminatedUnion("provider",[Ke.strictObject({provider:Ke.literal("apple"),orderId:Ke.uuid(),receiptId:Ke.uuid(),signedTransaction:Ke.string().min(1).max(131072)}),Ke.strictObject({provider:Ke.literal("google"),orderId:Ke.uuid(),receiptId:Ke.uuid(),purchaseToken:Ke.string().min(1).max(16384)})]),Dp=Ke.strictObject({orderId:Ke.uuid(),receiptId:Ke.uuid(),transactionIds:Ke.array(Ke.string().min(1).max(255)).min(1).max(50),membership:Ke.boolean()});var JO=mt.strictObject({operation:mt.literal("native_receipt"),requestId:mt.uuid(),customerToken:mt.string().regex(Bt),orderId:mt.uuid(),receiptId:mt.uuid(),nativeEvidence:Ep.nullable()}).refine(e=>e.nativeEvidence===null||e.nativeEvidence.orderId===e.orderId&&e.nativeEvidence.receiptId===e.receiptId,"Evidence must use this current order receipt"),WO=mt.strictObject({scope:ve,requestId:mt.uuid(),orderId:mt.uuid(),receiptId:mt.uuid(),orderStatus:mt.enum(["created","pending","trialing","paid","cancelled","failed"]),refunded:mt.boolean(),nativeCompletion:Dp.optional()});import{z as Oe}from"zod";var Tp=Oe.string().regex(/^[a-f0-9]{64}$/),th=ys.omit({variations:!0,active:!0}).extend({changeId:Tp,variations:Oe.array(Oe.strictObject({urlRedirect:Oe.string().max(2048)})).min(2).max(20)}),tw=Oe.strictObject({environmentId:Oe.uuid(),trackExposures:Oe.boolean(),generation:Tp,experiments:Oe.array(th).max(100),savedGroups:Ss}),nh=Oe.strictObject({eventUuid:Oe.uuid(),timestamp:Oe.iso.datetime({offset:!0}).optional(),deviceId:Oe.string().min(1).max(128),sessionId:Oe.string().min(1).max(128).optional(),url:Oe.url().max(2048),pageTitle:Oe.string().max(512).optional(),experimentKey:Oe.string().min(1).max(255),variationKey:Oe.string().min(1).max(64)}),nw=Oe.strictObject({events:Oe.array(nh).min(1).max(20)}),rw=Oe.strictObject({inserted:Oe.number().int().nonnegative(),duplicates:Oe.number().int().nonnegative(),skipped:Oe.number().int().nonnegative(),rejected:Oe.array(Oe.strictObject({index:Oe.number().int().nonnegative(),reason:Oe.string()}))});import{z as Ce}from"zod";var ya=32,rh=522240;function xa(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 ih=Ce.strictObject({nodeId:Ce.string().min(1).max(64),visit:Ce.number().int().nonnegative(),revision:Ce.number().int().nonnegative()}),ba=Ce.record(Ce.string(),me),oh=Ce.strictObject({id:Ce.uuid(),nodeId:Ce.string().min(1).max(64),visit:Ce.number().int().nonnegative(),input:Ce.strictObject({schemaVersion:lr.shape.schemaVersion,kind:lr.shape.kind,selector:lr.shape.selector,contract:lr.shape.contract}),context:ba,removed:Ce.array(Ce.string()).max(100),attributes:ba,removedAttributes:Ce.array(Ce.string()).max(100),result:Ol,offeringVersionId:Ce.uuid().nullable(),events:Ce.strictObject({entered:Ce.string().regex(/^[1-9][0-9]{0,18}$/),decision:Ce.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),uw=Ce.strictObject({schemaVersion:Ce.literal(1),mode:Ce.enum(["local","remote"]),versionId:Ce.uuid(),generation:Ce.number().int().positive(),base:ih,context:ba,steps:Ce.array(oh).min(1).max(ya)}).refine(e=>ot(e)<=rh,"Segment exceeds its byte budget");var Sa=class extends Error{constructor(n,r){super(r);this.code=n;this.name="FunnelLocalCalculationError"}code},Ii=(e,t)=>new Sa(e,t),ah=e=>({experiments:e.experiments,features:e.features});function sh(e,t=Ii){let n=new Map(e.topology.nodes.map(s=>[s.id,s])),r=Xa(e.growth.savedGroups),i=ah(e.growth);function a(s,c){if(!Object.hasOwn(e.growth.features,s))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return $n(s,c).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(s,c){let u=n.get(s);if(!u)throw t("NOT_FOUND","Funnel node is unavailable");let d,f;if(u.type==="condition"){let k=e.conditions[u.id];if(!k)throw t("INVALID_RESPONSE","Local condition rules are unavailable");d=Aa({id:u.id,name:u.id,type:"condition",cases:k.map(S=>({condition:S.condition,target:u.outputs[S.port]})),default:u.outputs.default},c,i.experiments).port}else if(u.type==="feature"){if(!u.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");f=a(u.resources.featureKey,c),d="next"}else if(u.type==="split"){if(!(u.resources.experimentId?e.growth.experiments[u.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let S=Aa({id:u.id,name:u.id,type:"split",experimentId:u.resources.experimentId,routes:u.outputs,notParticipating:u.outputs.notParticipating},c,i.experiments);f=S.value,d=S.port}else if(["offering","end","output"].includes(u.type)&&u.resources.featureKey)f=a(u.resources.featureKey,c),d=u.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let x=u.outputs[d]??(d==="value"?u.id:void 0);if(!x)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:s,port:d,target:x,...f===void 0?{}:{value:f}}}}}function xw(e,t,n,r=Ii){return va(e,r)(t,n)}function va(e,t){let n=Un.parse(e);if(n.evaluationMode!=="local")throw t("EVALUATION_MODE","Remote nodes are evaluated by Grow");let r=n.expiresAt?Date.parse(n.expiresAt):null,i=()=>{if(r!==null&&r<=Date.now())throw t("CONFIGURATION_EXPIRED","Refresh local rules at the scheduled transition")};i();let a=sh(n,t);return(s,c)=>(i(),ch(a,s,c))}function ch(e,t,n){let r=rt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:s}=n,c={attributes:r,...i?{saveStickyBucketAssignmentDoc:u=>i(structuredClone(u))}:{},...a?{onFeatureUsage:(u,d)=>a(u,structuredClone(d))}:{},...s?{onExperimentViewed:(u,d)=>s(structuredClone(u),structuredClone(d))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,c)}function Sw(e,t,n,r=Ii){return Mp(va(e,r),t,n)}function Mp(e,t,n){let r=[],i=[],a=[],s=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(c){let u=r.findIndex(x=>x.next.attributeName===c.attributeName&&x.next.attributeValue===c.attributeValue),d=c.attributeName+"||"+c.attributeValue,f={expected:n.sticky[d]??null,next:c};u<0?r.push(f):r[u]=f},onExperimentViewed(c,u){u.inExperiment&&u.hashUsed&&!u.passthrough&&i.push(me.parse({key:c.key,variationId:u.variationId,keyUsed:u.key,hashAttribute:u.hashAttribute,hashValue:u.hashValue}))},onFeatureUsage(c,u){a.push(me.parse({feature:c,value:u.value,source:u.source,...u.ruleId?{ruleId:u.ruleId}:{}}))}});return{port:s.port,...s.value===void 0?{}:{value:s.value},sticky:r,exposures:i,features:a}}function vw(e,t,n,r=Ii){let i=n,a=new Map(t.graph.nodes.map(b=>[b.id,b])),s=structuredClone(n.variables),c=structuredClone(i.sticky),u=[],d=n.nodeId,f=n.visit,x=!1,k,S=b=>(k??=va(e,r),Mp(k,b,{attributes:Bo({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:s,savedGroups:{}}),sticky:c}));for(let b=0;b<ya;b++){let R=a.get(d);if(!R||!xa(R))break;if(f>=t.execution.maxTransitions&&(f>t.execution.maxTransitions||R.type!=="end"&&R.type!=="output")){if(!u.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let Q,ne;if(["condition","feature","split"].includes(R.type)||R.type==="offering"&&R.configuration.source==="feature")Q=S(R.id),R.type==="offering"&&(Q.value={type:"offering_version",id:String(Q.value)}),R.type==="condition"?ne=Q.port==="default"?R.default:R.cases[Number(Q.port.slice(5))]?.target:R.type==="split"?ne=Q.port==="notParticipating"?R.notParticipating:R.routes[Q.port]:(R.type==="feature"||R.type==="offering")&&(ne=R.next);else if(Q={port:"next",sticky:[],exposures:[],features:[]},(R.type==="entry"||R.type==="coupon"||R.type==="coupons")&&(ne=R.next),R.type==="offering"&&R.configuration.source==="fixed"&&(Q.value={type:"offering_version",id:R.configuration.versionId},ne=R.next),R.type==="end"||R.type==="output"){let q=R.type==="end"?R.output:R.value;if(Q=q?.type==="feature"?S(R.id):{...Q,port:"value",value:q?.type==="literal"?q.value:q?.type==="variable"?Wi({source:"variable",key:q.key,...q.path?{path:q.path}:{}},{declarations:t.variables,answers:n.answers,results:s,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},q&&(Q.value===void 0||!lt(t.outputSchema,Q.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let Se=[...u,{nodeId:d,result:Q}];if(ot({steps:Se})>6e4){if(!u.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(u.push({nodeId:d,result:Q}),R.type==="feature"||R.type==="offering"||R.type==="coupon"||R.type==="coupons"){let q=R.type==="coupons"?R.couponIds.map(oe=>({type:"reward",id:oe})):R.type==="coupon"?{type:"reward",id:R.couponId}:Q.value;if(q===void 0)throw r("INVALID_RESPONSE","Node output is missing");let ie=Wt(R,{value:q});Ji(t.variables,R,ie),Object.assign(s,ie)}for(let q of Q.sticky)c[`${q.next.attributeName}||${q.next.attributeValue}`]=structuredClone(q.next);if(R.type==="end"||R.type==="output"){x=!0;break}if(!ne)throw r("INVALID_RESPONSE","Local pure exit is unavailable");d=ne,f++}let p=a.get(d);return{steps:u,...!x&&p&&!xa(p)?{boundary:{nodeId:d,visit:f}}:{}}}import{z as uh}from"zod";var _w=uh.strictObject({document:Vt,configuration:Un.options[0]});import{z as W}from"zod";var Oi=W.string().regex(/^[a-f0-9]{64}$/),lh=W.strictObject({release:Oi,render:vs,button:W.strictObject({selector:W.string().min(1).max(512),elementKey:W.string().min(1).max(256),tag:W.enum(["button","a","input"])}).nullable()}),Tw=W.strictObject({scope:ve.extend({environmentId:W.uuid()}),release:Oi,validatedAt:W.iso.datetime({offset:!0}),validUntil:W.iso.datetime({offset:!0}),entries:W.array(W.strictObject({id:W.uuid(),funnelId:W.uuid(),versionId:W.uuid(),event:W.enum(["screen_enter","button_click"]),target:lh})).max(4e3)}),Mw=W.strictObject({operation:W.literal("entry_start"),funnelId:W.uuid(),versionId:W.uuid(),entryId:W.uuid(),release:Oi,requestId:W.uuid(),locale:W.string().min(1).max(35).default("en")}),Bw=W.strictObject({scope:ve,suppressed:W.literal(!0),reason:W.enum(["frequency","in_progress"]),retryAt:W.iso.datetime({offset:!0}).nullable()}),qw=W.strictObject({experimentId:W.uuid(),splitNodeId:W.string().min(1).max(128)}),ph=W.strictObject({experimentId:W.uuid(),experimentKey:W.string().min(1).max(128),variationKey:W.string().min(1).max(128),inExperiment:W.boolean(),generation:W.string().min(1).max(256)}),zw=W.strictObject({operation:W.literal("page_experiments"),release:Oi,usedReceiptIds:W.array(W.uuid()).max(20).default([]),customerToken:W.string().regex(Bt).optional()}),Nw=W.strictObject({scope:ve,runId:W.uuid(),assignments:W.array(ph.extend({receiptId:W.uuid()})).max(100),payload:ws});function ge(e){return typeof e=="string"?e:String(e)}var dh=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function mh(e){return e.replace(dh,"$1\uFFFD")}function ja(e,t){if(typeof e!="object"||e==null){let n="";throw n+="The provided value is not an object",new TypeError(n)}return e}function $p(e){if(e!=null&&(typeof e=="object"||typeof e=="function")){let t=e[Symbol.iterator];if(t==null)return;if(typeof t!="function")throw new TypeError("The provided value is not iterable");let n=t.call(e);if(!n||typeof n!="object")throw new TypeError("Result of the Symbol.iterator method is not an object");return n}}function Bp(e){let t;if(Array.isArray(e)){let n=e.map(ge);if(n.length===2)return n}else if((t=$p(e))!=null){let n=ja(t.next()),r=ja(t.next());if(!n.done&&!r.done)return[ge(n.value),ge(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var qp="0123456789ABCDEF",fh=/(?:%[0-9A-Fa-f]{2})+/g;function Ot(e){return`%${qp[e>>4&15]}${qp[15&e]}`}function Gp(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Ot(e):String.fromCharCode(e):e<=2047?Ot(192|e>>6)+Ot(128|63&e):e<=65535?Ot(224|e>>12)+Ot(128|e>>6&63)+Ot(128|63&e):Ot(240|e>>18)+Ot(128|e>>12&63)+Ot(128|e>>6&63)+Ot(128|63&e)}function _a(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Pa(e,t=!1){let n=0;for(;n<e.length;n++){let r=e.charCodeAt(n);if(r===37||t&&r===43)break}return n===e.length?e:(t?e.replace(/\+/g," "):e).replace(fh,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function xr(e){return e<=31||e>126}function Ah(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return xr(e)}}function Ma(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return xr(e)}}function hh(e){return Ma(e)||e===39}function Ca(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Ma(e)}}function Ci(e){switch(e){case 47:case 58:case 59:case 61:case 64:case 91:case 92:case 93:case 124:return!0;default:return Ca(e)}}function zp(e){switch(e){case 33:case 39:case 40:case 41:case 126:return!0;default:return(function(n){switch(n){case 36:case 37:case 38:case 43:case 44:return!0;default:return Ci(n)}})(e)}}function Kp(e,t){return Gp(e=e||0,t)}function wt(e,t,n=!1){let r=0;for(;r<e.length;r++){let a=e.charCodeAt(r);if(a>=128||n&&a===32||t(a))break}if(r===e.length)return e;let i=e.slice(0,r);for(;r<e.length;r++){let a=e.charCodeAt(r),s=a;if(a>=55296&&a<=56319&&r+1<e.length){let c=e.charCodeAt(r+1);c>=56320&&c<=57343&&(s=(a-55296<<10)+c-56320+65536,r++)}i+=Gp(s,t,n)}return i}function Ba(e){let t=[],n=0,r=0;for(;r<=e.length;){if(r=e.indexOf("&",n),r<0&&(r=e.length),r!==n){let i=e.slice(n,r),a=i.indexOf("=");a<0&&(a=i.length),t.push([Pa(i.slice(0,a),!0),Pa(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function ka(e){let t="";for(let n=0;n<e.length;n++){let r=wt(e[n][0],zp,!0),i=wt(e[n][1],zp,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var gh=[2191,2191,3164,3164,3292,3292,6863,6877,6880,6891,8385,8385,11158,11158,42958,42959,42962,42962,42964,42964,42993,42993,64451,64466,64912,64913,64968,64974,67904,67929,69317,69319,69328,69336,69370,69371,72544,72551,73136,73179,73184,73193,93856,93880,93883,93907,94194,94198,100344,100351,101641,101662,101760,101874,118010,118012,118458,118480,118496,118512,124608,124638,124640,124661,124670,124671,128728,128728,128887,128890,129232,129240,129620,129623,129674,129674,129678,129678,129736,129736,129741,129741,129770,129770,129775,129775,130042,130042,177978,177983,183970,183981,205744,210041],bh=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],yh=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],xh=[2381,2381,2509,2509,2637,2637,2765,2765,2893,2893,3021,3021,3149,3149,3277,3277,3387,3388,3405,3405,3530,3530,3642,3642,3770,3770,3972,3972,4153,4154,5908,5909,5940,5940,6098,6098,6752,6752,6980,6980,7082,7083,7154,7155,11647,11647,43014,43014,43052,43052,43204,43204,43347,43347,43456,43456,43766,43766,44013,44013,68159,68159,69702,69702,69744,69744,69759,69759,69817,69817,69939,69940,70080,70080,70197,70197,70378,70378,70477,70477,70606,70608,70722,70722,70850,70850,71103,71103,71231,71231,71350,71350,71467,71467,71737,71737,71997,71998,72160,72160,72244,72244,72263,72263,72345,72345,72767,72767,73028,73029,73111,73111,73537,73538,90415,90415];function Sh(e){for(let t=0;t<e.length;t++){let n=e.codePointAt(t);if(n>65535&&t++,n<=32||n===37||n===127||n>=55296&&n<=57343||n>=128&&n<=159||n>=64976&&n<=65007||!(65534&~n)||n===65533)return!0}return!1}var[vh,Ih,Oh,Np]=[[[],"0,6,7,8,m,w,10,1b,1d,1f,72,73,7k,8k,dt,2rk","AAAAAAAAAAAAAAAAAAAAAP////8AAAAAAAAAAAAAAAA/AAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAADAAABwfwAAAAAAAMADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhAAAAQAAAAAAAAQCAAABAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgACAAAAAAAAAAAAAAAAD//wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAP///////////////wAAAAAAAAAAAAAAAAAAAAA="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAEF9+P/+BwAAAMAA//8AAPz/////BlADAAAAAJwAAPz///8AAADA//H/5+X8AAAAAAAAAAAA/P///wcAAAAAAAAAAAAAPv0vAD0BAABA/gAA/5/5/f8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD8g+N8B+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAYAAAAAAAAAAAAAD/////CwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANgAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/HgwAAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"6,7,8,o,4o,7e,7f,7h,7i,7j,dl","AAAAAP3////+BwAAAMDu//////////////8vAADAAJwAAP3///8AAADg////////AAAAAAAAAAAA/P///wcAAAAAAAAAAAAA////Ab0H//9H/gAA/9////8BAAAAAAAAgAAAAP//////////////AYD/////BQAAAAAAAAAAAAAAAAAAAAAAAP///////wcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAL/G//8T+AAAAAAAAAAAAAAAAAAAAAAAAP//AwAAfgAAAAAAAAAAAAD+////DwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANwAAAAAAAAAAAAAAAAA//8fAB4AAAD//wMAAAAAAH3/Hg4AAAAAAAD//////////w8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="],[[],"0,3,4,5,6,7,8,9,a,b,c,d,e,f,g,j,n,o,p,q,r,s,t,w,18,19,1c,4m,4o,4p,4q,4r,6z,72,73,75,76,77,7e,7h,7i,7j,7k,7l,7m,7n,7o,7p,7q,7r,7s,7t,7u,7v,7w,7x,7y,7z,8k,9t,a2,a3,a7,cc,cv,cx,cy,d6,dc,dd,de,dg,dh,di,dk,dl,2rk,2rl","AAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAD//////////////////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/v////+/tgAAAAAAAAAAAP8XAAAAAAD4//8AAAEAAAAAAAAAAAAAAMCfnz0AAACAAgAAAP///wcAAAAAAAAAAAAAwP8BAAAAAAAA+A8gAADA++8+AAAAAAAOAAAAAAAAgP8AAAAAAPz///v///8HAAAAAAAAFP4h/gAMAAAAAgAAAAAAABAeIAAADAAAQAYAAAAAAAAQhjkCAAAAIwAGAAAAAAAAEL4hAAAMAAD8AgAAAAAAAJAeIGAADAAAAAQAAAAAAAAAASAAAAAAAAARAAAAAAAA0ME9YAAMAAAAAgAAAAAAAJBAMAAADAAAAAMAAAAAAAAYHiAAAAwAAAACAAAAAAAAAAAEXAAAAAAAAAAAAAAA8geAfwAAAAAAAAAAAAAAAPIfAH8AAAAAAAAAAAADAACgAgAAAAAAAP5/3+D//v///x9AAAAAAAAAAAAAAAAA4P1mAAAAwwEAHgBkIAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwAAAAMAAAADAAAAAwAAAAAAAAAsD9A/g8gAAAAAAC4AAAAAAAAAAAAAAAAAABgAAAAAAIAAAAAAAAAAAAAAAAAAIcBBA4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAJAAAAAAAAQH/lH/ifAAAAAAAA//////8//w8AAA8AAAAAANAXBAAAAAD4DwADAAAAPDsAAAAAAABAowMAAAAAAADwzwAAAAAAAAAAAAAAAAAAAAAAAAD3//0hEAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//////////wDIAAAAfAAAAAAAAB/8AAAAAAAAAAAAAAAA/////wEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAwAAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAAAAA/////wAAAAAAPAAAAAAAAAAAAAAAAAAGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAID3PwAAAMAAAAAAAAAAAAAAAwBECAAAYBAAAAAAAAAAAAAAAAAAAAAAAAAwAAAA//8DgAAAAADAPwAAgP8DAAAAAAAHAAAAAADIMwAAAAAgAAAAAAAAAAB+ZgAIEAAAAAAAEAAAAAAAAJ3BAgAAAAAwQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAICEAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//8AAP//AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAMAHAAAAAAAAAAAAAAAAAAAAAG7wAAAAAACHAAAAAAAAAAAAAAAAAAAAAAAAAABgAAAAAAAAAPAAAAAAAAAAAD4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAYAAAAAAAAAAAA/AAAAAAAAAAAwP8BAAAAAAA8AAAAAAAAAAAAAAAAAAAAAgAAAAAAAP9/AAAAAAAZgAMAAAAAAHgGBAAAAAAAAAAHAAAAgO8fAAAAAAAAAAgAAwAAAAAAwH8AngAAAAAAAAAAAAAAgNNAAgAAAAAAAAAAAAAAAAAAAAAAAID4BwAAAwAAAAAAABgBAAAAwB8fAAAAAAAAAAD4AUAFAAYAAAAAAAAAAAAA/1wAAEAAAAAAAAAAAAAA+IUNAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8sAEAADAAAAAAAAAAAAAA+KcBAAAAAAAAAAAAAAAAKL8AAAAAAAAAAAAAAACgvA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgP8GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFgIAAAAAAAAAAAAAAAAAAAAAADwDAEAAAD+BwAAAAD4eYAAfg4AAAAAAPx/AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAF0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAf78AAAAAAAAAAAAA/P///G0AAAAAAAAAAAAAAAAAAAB+tL8AAAAAAAAAAACjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABgAAwAAAAAAwAcFAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD//4H/PwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMD/4wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHwAAAAAAAAB/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAgAcAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGAPAAAAAAAAAAAAAAD//////z///38AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAD+P/nDwAAADwAAAAAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD///////9/+P//////HyAAEAAA+P7/AAAAAAAAAAAAAH////nbBwAAAAAAAAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASMAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfwAAAAAAAAAAAAAAAADwDwAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAA////////////////AAAAAAAAAAAAAAAAAAAAAP///////////////////////////////////////wAA"]].map(function([t,n,r]){return[t,n.split(",").map(i=>parseInt(i,36)),Uint8Array.from(atob(r),i=>i.charCodeAt(0))]});function wh(e,t){return t===931||t===1010||t===120531||t===120589||t===120647||t===120705||t===120763?"\u03C3":t>=5112&&t<=5117?String.fromCodePoint(t-8):t>=43888&&t<=43967?String.fromCodePoint(t-38864):t>=93856&&t<=93880?String.fromCodePoint(t+27):t===837||t===890||t>=8064&&t<=8111||t>=8114&&t<=8188?e.normalize("NFD").replace(/\u0345/g,"\u03B9").normalize("NFC").toLowerCase():""}function Hp(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function br(e,t){let[n,r,i]=e,a=t>>8;for(let u=0;u<n.length;u+=2)if(a>=n[u]&&a<=n[u+1])return!0;let s=r.indexOf(a);if(s<0)return!1;let c=255&t;return!!(i[32*s+(c>>3)]&1<<(7&c))}function jh(e){let t=Array.from(e,n=>n.codePointAt(0));for(let n=0;n<t.length;n++){let r=t[n];if(r!==8204&&r!==8205||n>0&&Hp(xh,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&br(Np,t[i]);)i--;let a=n+1;for(;a<t.length&&br(Np,t[a]);)a++;if(!(i>=0&&a<t.length&&br(Ih,t[i])&&br(Oh,t[a])))return!1}return!0}var _h=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,Ph=/\p{Script=Latin}/u;function Ch(e){return!_h.test(e)||!Ph.test(e)}var Gt=36,ji=1,Ra=26,kh=38,Rh=700,Eh=72,Dh=128,Th=2147483647;function Fp(e){return String.fromCharCode(e+22+75*+(e<26))}function Mh(e,t,n){let r=0;for(e=n?Math.floor(e/Rh):e>>1,e+=Math.floor(e/t);e>(Gt-ji)*Ra>>1;r+=Gt)e=Math.floor(e/(Gt-ji));return Math.floor(r+(Gt-ji+1)*e/(e+kh))}function Bh(e){let t=Array.from(e,u=>u.codePointAt(0)),n="",r=0;for(let u=0;u<t.length;u++){let d=t[u];d<128&&(n+=String.fromCharCode(d),r++)}let i=r;i&&(n+="-");let a=Dh,s=0,c=Eh;for(;r<t.length;){let u=Th;for(let d=0;d<t.length;d++){let f=t[d];f>=a&&f<u&&(u=f)}s+=(u-a)*(r+1),a=u;for(let d=0;d<t.length;d++){let f=t[d];if(f<a&&s++,f===a){let x=s;for(let k=Gt;;k+=Gt){let S=k<=c?ji:k>=c+Ra?Ra:k-c;if(x<S)break;n+=Fp(S+(x-S)%(Gt-S)),x=Math.floor((x-S)/(Gt-S))}n+=Fp(x),c=Mh(s,r+1,r===i),s=0,r++}}s++,a++}return n}function Ia(e){let t=10;if(e.length>=2&&e[0]==="0"&&(e[1]==="x"||e[1]==="X"))e=e.slice(2),t=16;else if(e.length>=2&&e[0]==="0")e=e.slice(1),t=8;else if(e==="")return-1;let n=0;for(let r=0;r<e.length;r++){let i=_a(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Up(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function Zp(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Qp(e){return e.length===2&&Zp(e.codePointAt(0),e.codePointAt(1))}function Vp(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ke(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Jp(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Ea(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,s=0,c=0,u=Array.from(r,d=>d.codePointAt(0));if(u[c]===58){if(u[c+1]!==58)return null;c+=2,s++,a=s}for(;c<u.length;){if(s===8)return null;if(u[c]===58){if(a!==null)return null;c++,s++,a=s;continue}let d=0,f=0,x=0;for(;x<4&&(d=_a(u[c]))>=0;)f=(f<<4)+d,c++,x++;if(u[c]===46){if(x===0||s>6)return null;c-=x;let k=0;for(;u[c]!==void 0;){let S=0;if(k>0)if(u[c]===46&&k<4)c++;else return null;if(u[c]==null||u[c]<48||u[c]>57)return null;for(;u[c]>=48&&u[c]<=57;){if(S=10*S+_a(u[c]),S>255)return null;c++}i[s]=256*i[s]+S,k++,k%2==0&&s++}if(k!==4)return null;break}else if(u[c]===58){if(u[++c]===void 0)return null}else if(u[c]!==void 0)return null;i[s]=f,s++}if(a!==null){let d=s-a;for(s=7;s!==0&&d>0;){let f=i[a+d-1];i[a+d-1]=i[s],i[s]=f,s--,d--}}else if(a===null&&s!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Vp(r)?null:wt(r,xr)})(e);{let n=(function(i){let a=!1,s=!1;for(let u=0;u<i.length;u++){let d=i.charCodeAt(u);if(d<=32||d===37||d===127)return null;if(d>=128){a=!0;break}d>=65&&d<=90&&(s=!0)}if(!a)return i!==""?s?i.toLowerCase():i:null;if((function(d){for(let f of d){let x=f.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(f)&&!Hp(gh,x)||br(vh,x))return!0}return!1})(i))return null;let c=(i=(function(d){let f="";for(let x of d){let k=x.codePointAt(0);if(k!==8204&&k!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(x))continue;let S=wh(x,k);if(S){f+=S;continue}let p=bh.indexOf(k);f+=p<0?x:yh[p]}return f})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let u=0;u<c.length;u++){let d=c[u];if(d==="")continue;let f=/[^\0-\x7f]/.test(d);if(Sh(d)||f&&(/^\p{Mark}/u.test(d)||!jh(d)||!Ch(d)||d.startsWith("xn--")))return null;f&&(c[u]=`xn--${Bh(d)}`)}return(i=c.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Pa(e));return n===null||Vp(n)?null:(function(i){let a=i.length,s=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=s)return!1;if(Ia(i.slice(s,a))>=0)return!0;for(;s<a;s++){let c=i.charCodeAt(s);if(c<48||c>57)return!1}return!0})(n)?(function(i){let a=i.split("."),s=a.length;if(a[s-1]||s--,s>4)return null;let c=0;for(let d=0;d<s-1;d++){let f=Ia(a[d]);if(f<0||f>255)return null;c+=f*(1<<8*(3-d))}let u=Ia(a[s-1]);return u<0||u>=256**(5-s)?null:(c+=u,c)})(n):n}}function Da(e){return typeof e=="number"?(function(n){let i="";return i+=`${(n>>>24&255).toString(10)}.`,i+=`${(n>>>16&255).toString(10)}.`,i+=`${(n>>>8&255).toString(10)}.`,i+=(n&255).toString(10),i})(e):Array.isArray(e)?`[${(function(n){let r=(function(c){let u=-1,d=-1,f=1,x=0;for(let k=0;k<c.length;++k)c[k]!==0?(x>f&&(u=d,f=x),d=-1,x=0):(d===-1&&(d=k),++x);return x>f?d:u})(n),i="",a=!1;for(let s=0;s<=7;++s)if(!(a&&n[s]===0)){if(a&&(a=!1),r===s){i+=s===0?"::":":",a=!0;continue}i+=n[s].toString(16),s!==7&&(i+=":")}return i})(e)}]`:e}function Wp(e){e.path.length>0&&(e.path.length!==1||e.scheme!=="file"||!(function(n){return/^[A-Za-z]:$/u.test(n)})(e.path[0]))&&e.path.pop()}function Xp(e){return e.username!==""||e.password!==""}function Oa(e){return e.host===null||e.host===""||e.scheme==="file"}var h=0,O="",X="",de=null,w,_i=!1,Pi=!1,pn=!1,Re;function ut(e,t,n,r){t||(e=(function(s){let c=0,u=s.length;for(;c<u&&!(s.charCodeAt(c)>32);++c);for(;u>c&&!(s.charCodeAt(u-1)>32);--u);return s.substring(c,u)})(e)),e=(function(s){let c=0;for(;c<s.length;c++){let d=s.charCodeAt(c);if(d===9||d===10||d===13)break}if(c===s.length)return s;let u=s.slice(0,c);for(;c<s.length;c++){let d=s.charCodeAt(c);d!==9&&d!==10&&d!==13&&(u+=s[c])}return u})(e),h=0,O=e,X="",de=n||null,w=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},_i=!1,Pi=!1,pn=!1,Re=r||0;let i=qh;switch(r){case 3:case 4:i=ki;break;case 5:i=za;break;case 6:i=dn;break;case 7:i=Kt;break;case 8:i=jt}return i(E(e,h))!==1?w:null}function z(e,t){return h+=h===e?bt(t):1,h<=O.length}function E(e,t){return t<e.length?e.codePointAt(t):void 0}function bt(e){return e!=null&&e>65535?2:1}function Yp(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var qh=e=>{let t=h;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=h+1;for(e=O.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=O.charCodeAt(n);return X=O.slice(h,n).toLowerCase(),h=n,zh(n<O.length?e:void 0)}else return Re?1:(--h,z(t,e)?ed(E(O,h)):0)},zh=e=>{let t=h;if(e===58){if(Re){if(ke(w.scheme)!==ke(X))return 0;if((Xp(w)||w.port!==null)&&X==="file")return 0;if(w.scheme==="file"&&w.host==="")return 0}return w.scheme=X,Re?(w.port===Jp(w.scheme)&&(w.port=null),0):(X="",w.scheme==="file"?z(t,e)?Na(E(O,h)):0:ke(w.scheme)&&de!==null&&de.scheme===w.scheme?z(t,e)?Nh(E(O,h)):0:ke(w.scheme)?z(t,e)?Uh(E(O,h)):0:E(O,h+1)===47?(h++,z(t,e)?Fh(E(O,h)):0):(w.path=[""],w.opaquePath=!0,z(t,e)?nd(E(O,h)):0))}else return Re?1:(X="",h=-1,z(t,e)?ed(E(O,h)):0)},ed=e=>{let t=h;return de===null||de.opaquePath&&e!==35?1:de.opaquePath&&e===35?(w.scheme=de.scheme,w.path=de.path.slice(),w.opaquePath=de.opaquePath,w.query=de.query,w.fragment="",z(t,e)?jt(E(O,h)):0):de.scheme==="file"?(h--,z(t,e)?Na(E(O,h)):0):(h--,z(t,e)?qa(E(O,h)):0)},Nh=e=>{let t=h;return e===47&&E(O,h+1)===47?(++h,z(t,e)?Ei(E(O,h)):0):(h--,z(t,e)?qa(E(O,h)):0)},Fh=e=>{let t=h;return e===47?z(t,e)?Vn(E(O,h)):0:(h--,z(t,e)?yt(E(O,h)):0)},qa=e=>{let t=h;return w.scheme=de.scheme,e===47||ke(w.scheme)&&e===92?z(t,e)?Lp(E(O,h)):0:(w.username=de.username,w.password=de.password,w.host=de.host,w.port=de.port,w.path=de.path.slice(),w.query=de.query,e===63?(w.query="",z(t,e)?Kt(E(O,h)):0):e===35?(w.fragment="",z(t,e)?jt(E(O,h)):0):e!=null?(w.query=null,w.path.pop(),h--,z(t,e)?yt(E(O,h)):0):z(t,e)?qa(E(O,h)):0)},Lp=e=>{let t=h;return ke(w.scheme)&&(e===47||e===92)?z(t,e)?Ei(E(O,h)):0:e===47?z(t,e)?Vn(E(O,h)):0:(w.username=de.username,w.password=de.password,w.host=de.host,w.port=de.port,h--,z(t,e)?yt(E(O,h)):0)},Uh=e=>{let t=h;return e===47&&E(O,h+1)===47?h++:h--,z(t,e)?Ei(E(O,h)):0},Ei=e=>{let t=h;return e!==47&&e!==92?(h--,z(t,e)?Vn(E(O,h)):0):z(t,e)?Ei(E(O,h)):0},Vn=e=>{let t=h;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ke(w.scheme))){let n=h+bt(e);for(;n<O.length;){let r=E(O,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&ke(w.scheme))break;n+=bt(r)}return X+=O.slice(h,n),h=n-1,z(t,e)?Vn(E(O,h)):0}if(e===64){_i&&(X=`%40${X}`),_i=!0;for(let n=0;n<X.length;n++){let r=X.codePointAt(n);if(r===58&&!Pi){Pi=!0;continue}let i=Kp(r,Ci);Pi?w.password+=i:w.username+=i,r!=null&&r>65535&&n++}return X="",z(t,e)?Vn(E(O,h)):0}else return e==null||e===35||e===47||e===63||e===92&&ke(w.scheme)?_i&&X===""?1:(h-=X.length+1,X="",z(t,e)?ki(E(O,h)):0):(X+=Yp(e),z(t,e)?Vn(E(O,h)):0)},ki=e=>{let t=h;if(Re&&w.scheme==="file")return h--,z(t,e)?Fa(E(O,h)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ke(w.scheme))){let n=h+bt(e);for(e===91?pn=!0:e===93&&(pn=!1);n<O.length;){let r=E(O,n);if(r==null||!pn&&r===58||r===35||r===47||r===63||r===92&&ke(w.scheme))break;r===91?pn=!0:r===93&&(pn=!1),n+=bt(r)}return X+=O.slice(h,n),h=n-1,z(t,e)?ki(E(O,h)):0}else if(e===58&&!pn){if(X===""||Re===4)return 1;let n=Ea(X,!ke(w.scheme));return n===null?1:(w.host=Da(n),X="",z(t,e)?za(E(O,h)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ke(w.scheme)){if(h--,ke(w.scheme)&&X==="")return 1;if(Re&&X===""&&(Xp(w)||w.port!==null))return 1;let n=Ea(X,!ke(w.scheme));return n===null?1:(w.host=Da(n),X="",Re?0:z(t,e)?dn(E(O,h)):0)}else return X+=Yp(e),z(t,e)?ki(E(O,h)):0},za=e=>{let t=h;if(e!=null&&e>=48&&e<=57){let n=h+1;for(;n<O.length;){let r=O.charCodeAt(n);if(r<48||r>57)break;n++}return X+=O.slice(h,n),h=n-1,z(t,e)?za(E(O,h)):0}else if(Re||e==null||e===35||e===47||e===63||e===92&&ke(w.scheme)){if(X!==""){let n=parseInt(X,10);if(n>65535)return 1;if(w.port=n===Jp(w.scheme)?null:n,X="",Re)return 0}return Re?1:(h--,z(t,e)?dn(E(O,h)):0)}else return 1};function td(e,t){let n=e.length-t;if(n<2)return!1;if(Zp(E(e,t),E(e,t+1))){if(n===2)return!0;{let r=E(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var Na=e=>{let t=h;return w.scheme="file",w.host="",e===47||e===92?z(t,e)?Vh(E(O,h)):0:de?.scheme==="file"?(w.host=de.host,w.path=de.path.slice(),w.opaquePath=de.opaquePath,w.query=de.query,e===63?(w.query="",z(t,e)?Kt(E(O,h)):0):e===35?(w.fragment="",z(t,e)?jt(E(O,h)):0):e!=null?(w.query=null,td(O,h)?w.path=[]:Wp(w),h--,z(t,e)?yt(E(O,h)):0):z(t,e)?Na(E(O,h)):0):(h--,z(t,e)?yt(E(O,h)):0)},Vh=e=>{let t=h;return e===47||e===92?z(t,e)?Fa(E(O,h)):0:(de!==null&&de.scheme==="file"&&(!td(O,h)&&(function(r){if(r.length===2){let i=r.codePointAt(0),a=r.codePointAt(1);return(i>=65&&i<=90||i>=97&&i<=122)&&a===58}else return!1})(de.path[0])&&w.path.push(de.path[0]),w.host=de.host),h--,z(t,e)?yt(E(O,h)):0)},Fa=e=>{let t=h;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=h+bt(e);for(;n<O.length;){let r=E(O,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=bt(r)}return X+=O.slice(h,n),h=n-1,z(t,e)?Fa(E(O,h)):0}else if(e==null||e===47||e===92||e===63||e===35){if(h--,!Re&&Qp(X))return z(t,e)?yt(E(O,h)):0;if(X==="")return w.host="",Re?0:z(t,e)?dn(E(O,h)):0;{let n=Ea(X,!ke(w.scheme));return n===null?1:(n==="localhost"&&(n=""),w.host=Da(n),X="",Re?0:z(t,e)?dn(E(O,h)):0)}}return 1},dn=e=>{let t=h;return ke(w.scheme)?(e!==92&&e!==47&&h--,z(t,e)?yt(E(O,h)):0):!Re&&e===63?(w.query="",z(t,e)?Kt(E(O,h)):0):!Re&&e===35?(w.fragment="",z(t,e)?jt(E(O,h)):0):e!=null?(e!==47&&h--,z(t,e)?yt(E(O,h)):0):(Re&&w.host===null&&w.path.push(""),z(t,e)?dn(E(O,h)):0)},yt=e=>{let t=h;if(e!=null&&e!==47&&(!ke(w.scheme)||e!==92)&&(Re||e!==63&&e!==35)){let n=h+bt(e);for(;n<O.length;){let r=E(O,n);if(r==null||r===47||ke(w.scheme)&&r===92||!Re&&(r===63||r===35))break;n+=bt(r)}X+=wt(O.slice(h,n),Ca),h=n,e=E(O,n)}if(e==null||e===47||ke(w.scheme)&&e===92||!Re&&(e===63||e===35)){let n=ke(w.scheme)&&e===92;return(function(i){switch(i){case"..":case"%2e.":case"%2E.":case".%2e":case".%2E":case"%2e%2e":case"%2E%2e":case"%2e%2E":case"%2E%2E":return!0;default:return!1}})(X)?(Wp(w),e!==47&&!n&&w.path.push("")):Up(X)&&e!==47&&!n?w.path.push(""):Up(X)||(w.scheme==="file"&&w.path.length===0&&Qp(X)&&(X=`${X[0]}:`),w.path.push(X)),X="",e===63?(w.query="",z(t,e)?Kt(E(O,h)):0):e===35?(w.fragment="",z(t,e)?jt(E(O,h)):0):z(t,e)?yt(E(O,h)):0}else return X+=Kp(e,Ca),z(t,e)?yt(E(O,h)):0},nd=e=>{let t=h;if(e===63)return w.query="",z(t,e)?Kt(E(O,h)):0;if(e===35)return w.fragment="",z(t,e)?jt(E(O,h)):0;if(e!=null){let n=h+bt(e);for(;n<O.length;){let i=E(O,n);if(i===63||i===35)break;n+=bt(i)}let r=O.slice(h,n);if(n<O.length&&r.charCodeAt(r.length-1)===32?w.path[0]+=wt(r.slice(0,-1),xr)+"%20":w.path[0]+=wt(r,xr),h=n,(e=E(O,n))===63)return w.query="",z(t,e)?Kt(E(O,h)):0;if(e===35)return w.fragment="",z(t,e)?jt(E(O,h)):0}return z(t,e)?nd(E(O,h)):0},Kt=e=>{let t=h,n=h;if(e!=null){if(Re)n=O.length;else{let i=O.indexOf("#",h);n=i===-1?O.length:i}let r=ke(w.scheme)?hh:Ma;w.query+=wt(O.slice(h,n),r)}return h=n,E(O,n)===35&&!Re?(w.fragment="",z(t,e)?jt(E(O,h)):0):z(t,e)?Kt(E(O,h)):0},jt=e=>{let t=h;return e!=null&&(w.fragment+=wt(O.slice(h),Ah),h=O.length),z(t,e)?jt(E(O,h)):0};function Ta(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function rd(e){switch(e.scheme){case"blob":{let t=ut(Ta(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":rd(t)}case"ftp":case"http":case"https":case"ws":case"wss":return(function(n){let r=`${n.scheme}://`;return r+=n.host,n.port!==null&&(r+=`:${n.port}`),r})(e);default:return"null"}}var he=Symbol("URLImpl"),Sr=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=ge(t),n!=null&&(n=ge(n));let r=null;if(n!=null&&(r=ut(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=ut(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[he]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=ge(t),n!==void 0&&(n=ge(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=ge(t),n!==void 0&&(n=ge(n));let r=null;return n!=null&&(r=ut(n,null,null,0),r==null)?!1:ut(t,null,r,0)!=null}get href(){return(function(n){let r=`${n.scheme}:`;return n.host!==null&&(r+="//",(n.username!==""||n.password!=="")&&(r+=n.username,n.password!==""&&(r+=`:${n.password}`),r+="@"),r+=n.host,n.port!==null&&(r+=`:${n.port}`)),n.host===null&&!n.opaquePath&&n.path.length>1&&n.path[0]===""&&(r+="/."),r+=Ta(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[he].url)}set href(t){let n=ut(t=ge(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[he].url=n,this[he].query&&wa(this[he].query,n.query)}get origin(){return rd(this[he].url)}get protocol(){return`${this[he].url.scheme}:`}set protocol(t){ut(`${t=ge(t)}:`,this[he].url,null,2)}get username(){return this[he].url.username}set username(t){t=ge(t),Oa(this[he].url)||(function(r,i){r.username=wt(i,Ci)})(this[he].url,t)}get password(){return this[he].url.password}set password(t){t=ge(t),Oa(this[he].url)||(function(r,i){r.password=wt(i,Ci)})(this[he].url,t)}get host(){let{url:t}=this[he];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=ge(t),this[he].url.opaquePath||ut(t,this[he].url,null,3)}get hostname(){let{url:t}=this[he];return t.host!=null?t.host:""}set hostname(t){t=ge(t),this[he].url.opaquePath||ut(t,this[he].url,null,4)}get port(){let{url:t}=this[he];return t.port!=null?`${t.port}`:""}set port(t){t=ge(t);let{url:n}=this[he];Oa(n)||(t?ut(t,n,null,5):n.port=null)}get pathname(){return Ta(this[he].url)}set pathname(t){t=ge(t);let{url:n}=this[he];n.opaquePath||(n.path=[],ut(t,n,null,6))}get search(){let{url:t}=this[he];return t.query?`?${t.query}`:""}set search(t){t=ge(t);let{url:n,query:r}=this[he];if(!t)n.query=null,r&&wa(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",ut(i,n,null,7),r&&wa(r,n.query)}}get searchParams(){let t=this[he],n=t.query;return n==null&&(n=t.query=(function(i,a){let s=new Ri;return s[_e].url=i,s[_e].serialized=a==null,a&&(s[_e].list=Ba(a)),s})(this,t.url.query)),n}get hash(){let{url:t}=this[he];return t.fragment?`#${t.fragment}`:""}set hash(t){t=ge(t);let{url:n}=this[he];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",ut(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(Sr.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var _e=Symbol("URLSearchParamsImpl"),Lh=Symbol.dispose||Symbol.for("dispose");function wa(e,t){t?e[_e].list=Ba(t):e[_e].list.length=0,e[_e].serialized=t==null}function wi(e){if(e.url){let t=ka(e.list);(function(r,i){r[he].url.query=i})(e.url,t||null),e.serialized=!0}}var $h=typeof Iterator<"u"?Iterator:Object,yr=class extends $h{constructor(t,n){super(),this[_e]={ptr:t,map:n,index:0}}next(){let t=this[_e];return t.index<t.ptr.list.length?{value:t.map(t.ptr.list[t.index++]),done:!1}:{value:void 0,done:!0}}[Symbol.iterator](){return this}[Lh](){}},Ri=class{constructor(t){let n=this[_e]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Bp(t[i]));else if((r=$p(t))!=null){let i;for(;!(i=ja(r.next())).done;)n.list.push(Bp(i.value))}else if((typeof t=="object"||typeof t=="function")&&t!=null){let i=Object.keys(t);for(let a=0;a<i.length;a++){let s=i[a],c=mh(s),u=ge(t[s]),d=n.list.find(f=>f[0]===c);d?d[1]=u:n.list.push([c,u])}}else if(t!==void 0){let i=ge(t);i=i[0]==="?"?i.substring(1):i,n.list=Ba(i)}}get size(){return this[_e].list.length}append(t,n){t=ge(t),n=ge(n),this[_e].list.push([t,n]);let r=this[_e];r.url&&r.serialized?(function(a,s){let c=a[he].url;c.query=c.query?`${c.query}&${s}`:s})(r.url,ka([[t,n]])):wi(r)}delete(t,n){t=ge(t),n=n!=null?ge(n):void 0;let{list:r}=this[_e],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;wi(this[_e])}get(t){t=ge(t);let{list:n}=this[_e];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=ge(t);let n=[],{list:r}=this[_e];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=ge(t),n=n!=null?ge(n):void 0;let{list:r}=this[_e];for(let i=0;i<r.length;i++)if(r[i][0]===t&&(n==null||r[i][1]===n))return!0;return!1}set(t,n){t=ge(t),n=ge(n);let{list:r}=this[_e],i=!1,a=!1,s=0;for(;s<r.length;)r[s][0]===t?i?(r.splice(s,1),a=!0):(i=!0,r[s][1]!==n&&(r[s][1]=n,a=!0),s++):s++;i||(r.push([t,n]),a=!0),a&&wi(this[_e])}sort(){this[_e].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),wi(this[_e])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[_e];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new yr(this[_e],t=>t)}keys(){return new yr(this[_e],t=>t[0])}values(){return new yr(this[_e],t=>t[1])}toString(){return ka(this[_e].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Ri.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});function id(e){let t,n,r=0,i,a=new Map,s=()=>{for(let x of[...a.keys()])try{x()}catch{}};function c(x,k){let S=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}S===r&&(t=x,n=k,s())}let u=()=>c();function d(x,k=!1){let S=qt.safeParse(x);if(!S.success||k&&Date.parse(S.data.expiresAt)<=Date.now()||Date.parse(S.data.refreshExpiresAt)<=Date.now()||Date.parse(S.data.refreshExpiresAt)<Date.parse(S.data.expiresAt))throw new ue("INVALID_RESPONSE","Invalid customer session credentials");return S.data}async function f(){if(i)return i;let x=t,k=r;if(!x||Date.parse(x.refreshExpiresAt)<=Date.now())throw x&&u(),new ue("UNAUTHENTICATED","Customer authentication is required",401);let S=(async()=>{try{let p=await e(x.refreshToken);if(k!==r)throw new ue("IDENTITY_CHANGED","Customer identity changed during refresh");let b=d(p,!0);if(b.customerId!==x.customerId||b.sessionId!==x.sessionId)throw new ue("SCOPE_MISMATCH","Refresh changed the customer session");return t=b,n=b.accessToken,{...b}}catch(p){throw k!==r?new ue("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof ue&&p.status===401&&u(),p)}})();i=S;try{return await S}finally{i===S&&(i=void 0)}}return{identify(x){let k=typeof x=="string"?void 0:d(x),S=typeof x=="string"?x:k.accessToken;if(!S.trim()||/\s/.test(S)||S.length>4096)throw new ue("INVALID_TOKEN","A server-issued token is required");c(k,S)},reset:u,subscribeIdentity(x,k){return a.set(x,k),()=>{a.delete(x)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return f().then(()=>{if(!n)throw new ue("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new ue("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:f}}var od=Symbol("IndianaNoContent");function p_(e,t,n=Sr){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?ve.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new ue("SCOPE_MISMATCH","Configuration belongs to another App/environment");let s=new n(e.baseUrl??_s);if(s.username||s.password||s.search||s.hash)throw new ue("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(s.protocol!=="https:"&&!(s.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(s.hostname)))throw new ue("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let c=e.fetch??globalThis.fetch.bind(globalThis),u=e.timeoutMs??1e4;if(!Number.isFinite(u)||u<1||u>12e4)throw new ue("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let d=null,f=0,x=null,k=new Set,S=e.session??id(async ne=>{let Se=await Q("customer-sessions/refresh",{},"POST",{},ne);if(!Se||typeof Se!="object")throw new ue("INVALID_RESPONSE","Invalid refresh response");let{requestId:q,scope:ie,...oe}=Se;return oe});function p(){f+=1,d=null,x=null;for(let ne of k)ne.abort();k.clear()}let b=S.subscribeIdentity(p);function R(){S.reset()}async function Q(ne,Se={},q="POST",ie={},oe){let L=ie.installationDetach===!0;if(L&&(ne!=="push/installations/detach"||q!=="POST"))throw new ue("INVALID_REQUEST","Installation authority only detaches this installation");if(!oe&&!d&&!L)throw new ue("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let Xe=f,Ye=new AbortController;L||k.add(Ye);let vr=()=>!L&&Xe!==f?new ue("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new ue("TIMEOUT","Longplay request timed out"),Di,ad=new Promise((Le,nt)=>{Di=()=>nt(vr()),Ye.signal.addEventListener("abort",Di,{once:!0})}),sd=setTimeout(()=>Ye.abort(),u),cd=async()=>{let Le=await c(`${s.href.replace(/\/$/,"")}/api/v1/${ne}`,{method:q,headers:{"Content-Type":"application/json",...L?{}:{Authorization:`Bearer ${oe??d}`},[ro]:io.current,[tc]:js.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:q==="POST"?JSON.stringify(Se):void 0,signal:Ye.signal,credentials:"omit",cache:"no-store",redirect:"error",...ie.keepalive?{keepalive:!0}:{}});if(Ye.signal.aborted)throw vr();let nt;try{nt=Le.status===204?od:await Le.json()}catch{throw Ye.signal.aborted?vr():new ue(Le.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Le.status,Le.headers.get("X-Request-Id")??void 0)}if(Ye.signal.aborted)throw vr();if(!L&&Xe!==f)throw new ue("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Le.ok){let ze=Ka.safeParse(nt),Et=ze.success&&(!Ln.safeParse(ze.data.error.code).success||Ga(ze.data.error.code,Le.status)),Ua=Et?ze.data.error.code:"HTTP_ERROR",Va=Ha(Ua,Le.status,{retryAfter:Le.headers.get("Retry-After"),recovery:Et?ze.data.error.recovery:void 0,reason:Et?ze.data.error.reason:void 0});throw new ue(Ua,Et?ze.data.error.message:"Longplay request failed",Le.status,Le.headers.get("X-Request-Id")??(ze.success?ze.data.requestId:void 0),{...Va,...ze.success&&ze.data.error.retryable===!1?{retryable:!1}:{},...Va.retryAfterSeconds===void 0&&ze.success&&ze.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ze.data.error.retryAfterSeconds}:{}})}if(Le.headers.get(ro)!==io.current)throw new ue("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&nt!==od){let ze=nt&&typeof nt=="object"&&"scope"in nt?nt:nt&&typeof nt=="object"&&"configuration"in nt?nt.configuration:null;if(!ze||typeof ze!="object"||!("scope"in ze))throw new ue("INVALID_RESPONSE","Response is missing its App/environment scope");let Et=ve.safeParse(ze.scope);if(!Et.success||Et.data.projectId!==a.projectId||Et.data.environment!==a.environment)throw new ue("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Ir=Le.headers.get("X-Indiana-Telemetry-Subject");if(Ir){if(!/^[a-f0-9]{64}$/.test(Ir))throw new ue("INVALID_RESPONSE","Invalid telemetry identity");x!==Ir&&(x=Ir,t?.(x))}return nt};try{return await Promise.race([cd(),ad])}catch(Le){throw!L&&Xe!==f?new ue("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Le instanceof ue?Le:new ue(Ye.signal.aborted?"TIMEOUT":"NETWORK_ERROR",Ye.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(sd),Ye.signal.removeEventListener("abort",Di),k.delete(Ye)}}return{session:S,requestWithCredential(ne,Se,q,ie={}){return Q(ne,Se,"POST",ie,q)},subjectKey:()=>x,identify(ne){if(a&&typeof ne=="object"&&"scope"in ne){let Se=ve.safeParse(ne.scope);if(!Se.success||Se.data.projectId!==a.projectId||Se.data.environment!==a.environment)throw new ue("SCOPE_MISMATCH","Customer session belongs to another App/environment")}S.identify(ne),d=S.peek()??null},reset:R,dispose(){b(),p()},request(ne,Se={},q="POST",ie={}){if(ie.installationDetach)return Q(ne,Se,q,ie);let oe=f;try{let L=S.access(),Xe=Ye=>{if(oe!==f)throw new ue("IDENTITY_CHANGED","Customer identity changed before dispatch");return Q(ne,Se,q,ie,Ye)};return typeof L=="string"?Xe(L):L.then(Xe)}catch(L){return Promise.reject(L)}}}}export{Gg as a,Kg as b,Hg as c,Zg as d,$r as e,Jg as f,Zh as g,Qh as h,Rs as i,Bt as j,yn as k,Ms as l,ng as m,rg as n,fd as o,Ns as p,ag as q,hd as r,gd as s,bd as t,Mr as u,qr as v,Gi as w,Sd as x,sg as y,vd as z,cg as A,ug as B,Vs as C,dg as D,mg as E,Od as F,wd as G,gg as H,lt as I,Ji as J,Wi as K,eo as L,Vg as M,vx as N,Eo as O,Bf as P,Wu as Q,Bo as R,Zx as S,Qx as T,Jx as U,fS as V,AS as W,hS as X,Ov as Y,Cl as Z,AA as _,hA as $,t0 as aa,ta as ba,bA as ca,n0 as da,r0 as ea,i0 as fa,fr as ga,A0 as ha,Nl as ia,zl as ja,oa as ka,yA as la,O0 as ma,j as na,rO as oa,ZA as pa,ga as qa,_p as ra,yO as sa,IO as ta,Pp as ua,RO as va,WA as wa,EO as xa,Un as ya,XA as za,eh as Aa,VO as Ba,JO as Ca,WO as Da,tw as Ea,sh as Fa,xw as Ga,Sw as Ha,vw as Ia,_w as Ja,lh as Ka,Tw as La,Mw as Ma,Bw as Na,zw as Oa,Nw as Pa,Sr as Qa,p_ as Ra};
|