@tinkerlandai/indiana-react-native 0.10.1 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Io=Object.defineProperty;var $h=Object.getOwnPropertyDescriptor;var Gh=Object.getOwnPropertyNames;var Kh=Object.prototype.hasOwnProperty;var Hh=(e,t,n)=>t in e?Io(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Qh=(e,t)=>{for(var n in t)Io(e,n,{get:t[n],enumerable:!0})},Jh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Gh(t))!Kh.call(e,i)&&i!==n&&Io(e,i,{get:()=>t[i],enumerable:!(r=$h(t,i))||r.enumerable});return e};var Zh=e=>Jh(Io({},"__esModule",{value:!0}),e);var Le=(e,t,n)=>Hh(e,typeof t!="symbol"?t+"":t,n);var _I={};Qh(_I,{IndianaError:()=>y,createConfigurationSync:()=>Uh,createFeatureClient:()=>ns,createIndianaReactNative:()=>II,createLocalFunnelClient:()=>Lh});module.exports=Zh(_I);var vo=require("zod"),Wh=vo.z.enum(["sandbox","live"]),ze=vo.z.object({projectId:vo.z.string().min(1),environment:Wh}).strict();var qe=require("zod"),Pi=qe.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Hu=qe.z.enum(["unknown","denied","provisional","granted"]),Qu=qe.z.enum(["ios","android"]),wo=qe.z.strictObject({installationId:qe.z.uuid(),publicKey:qe.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:qe.z.iso.datetime({offset:!0}),signature:qe.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),us=qe.z.string().regex(/^[a-f0-9]{64}$/),Ju=wo.extend({sequence:Pi,platform:Qu,credentialDigest:us}),Zu=wo.extend({credentialDigest:us}),Wu=wo.extend({sequence:Pi,platform:Qu}),Oo=wo.extend({sequence:Pi,credentialDigest:us,connectionId:qe.z.uuid().nullable(),kind:qe.z.enum(["fcm_token","apns_token"]).nullable(),token:qe.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Hu}),Yu=Oo,Xu=Oo.extend({challenge:qe.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),ls=qe.z.strictObject({requested:qe.z.literal(!0),expiresAt:qe.z.iso.datetime({offset:!0})}),br=qe.z.strictObject({installationId:qe.z.uuid(),bound:qe.z.boolean(),identitySeq:Pi,bindingGeneration:Pi,addressSeq:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:qe.z.uuid().nullable(),addressStatus:qe.z.enum(["active","invalid"]).nullable(),permission:Hu}),ds=qe.z.strictObject({channel:qe.z.enum(["email","sms","voice","push"]),state:qe.z.enum(["unknown","allowed","denied"]),revision:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:qe.z.iso.datetime({offset:!0}).nullable()}),EI=qe.z.strictObject({state:qe.z.enum(["allowed","denied"]),revision:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function el(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 bt=require("zod"),Nn=bt.z.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),kI=bt.z.enum([...Nn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),jI=bt.z.enum([...Nn.options,"stale_revision"]),ps=bt.z.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),ms=bt.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),nl={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var tl={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function Yh(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(tl,e)){let r=tl[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Nn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:nl[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function rl(e,t){let n=Nn.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):nl[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function Xh(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var il=bt.z.object({retryable:bt.z.boolean(),recovery:ps,reason:ms.optional(),retryAfterSeconds:bt.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),fs=bt.z.object({requestId:bt.z.uuid().optional(),error:bt.z.object({code:bt.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:bt.z.string(),...il.partial().shape})}),TI=bt.z.object({error:fs.shape.error.extend({requestId:bt.z.uuid().optional()})}),NI=bt.z.object({error:bt.z.string(),code:bt.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:bt.z.uuid(),...il.shape});function _o(e,t,n={}){let r=Yh(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?Xh(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var gs="X-Indiana-Protocol",ol="X-Indiana-SDK-Version";var hs={current:"0.10"};var al=require("zod"),eA=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],he=al.z.enum(eA);var _=require("zod");var qt=_.z.string().min(1).max(200),Gt=_.z.iso.datetime({offset:!0}),mt=_.z.number().int().nonnegative().max(1e8),Co=_.z.string().regex(/^[A-Z]{3}$/),tA=["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"],sl=_.z.enum(tA),cl=_.z.strictObject({priceId:_.z.uuid(),productVersionId:_.z.uuid(),productId:qt,quantity:_.z.number().int().min(1).max(1e6),unitAmountMinor:mt,totalMinor:mt,interval:_.z.enum(["week","month","year","one_off"]),intervalCount:_.z.number().int().min(1).max(52),kind:_.z.enum(["fixed","prepaid","seat"]),tiers:_.z.strictObject({mode:_.z.enum(["graduated","volume"]),tiers:_.z.array(_.z.strictObject({upTo:_.z.number().int().positive().nullable(),unitAmountMinor:mt,flatAmountMinor:mt.optional()})).min(2).max(12)}).nullable()}),nA=_.z.strictObject({grantId:_.z.uuid(),couponId:_.z.uuid(),amountMinor:mt,terms:_.z.discriminatedUnion("type",[_.z.strictObject({type:_.z.literal("percent"),percentOff:_.z.number().gt(0).max(100)}),_.z.strictObject({type:_.z.literal("amount"),amountOffMinor:mt,currency:Co})]),duration:_.z.discriminatedUnion("type",[_.z.strictObject({type:_.z.literal("once")}),_.z.strictObject({type:_.z.literal("forever")}),_.z.strictObject({type:_.z.literal("repeating"),months:_.z.number().int().min(1).max(36)})])}),Ss={provider:_.z.literal("merchant"),executor:_.z.literal("merchant"),operationId:_.z.uuid(),customerId:_.z.uuid(),configurationRevision:_.z.number().int().nonnegative(),connectionRevision:_.z.number().int().nonnegative(),currency:Co,expiresAt:Gt},Po=_.z.strictObject({...Ss,type:_.z.literal("purchase"),mode:_.z.enum(["payment","subscription"]),lineItems:_.z.array(cl).min(1).max(100),catalogAmountMinor:mt,discount:nA.nullable(),trialPeriodDays:_.z.number().int().min(1).max(730).nullable(),automaticTax:_.z.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"),Eo=_.z.strictObject({...Ss,type:_.z.literal("subscription_change"),subscriptionId:_.z.uuid(),merchantSubscriptionId:qt,membershipId:_.z.uuid(),subscriptionAction:_.z.enum(["update","cancel","schedule","release"]),supersedesOperationId:_.z.uuid().nullable(),change:_.z.discriminatedUnion("type",[_.z.strictObject({type:_.z.literal("cancel")}),_.z.strictObject({type:_.z.literal("uncancel")}),_.z.strictObject({type:_.z.literal("plan"),productVersionId:_.z.uuid()}),_.z.strictObject({type:_.z.literal("seats"),licenseKey:qt,quantity:_.z.number().int().nonnegative().max(1e6)}),_.z.strictObject({type:_.z.literal("quantity"),internal_feature_id:_.z.uuid(),quantity:_.z.number().int().nonnegative().max(1e6)}),_.z.strictObject({type:_.z.literal("billing_cycle"),billingCycleAnchor:_.z.union([_.z.literal("now"),_.z.number().int().positive()])})]),timing:_.z.enum(["immediate","renewal"]),effectiveAt:Gt,creditMinor:mt,debitMinor:mt,totalMinor:mt,discountMinor:mt,taxMinor:mt,proration:_.z.enum(["none","create_prorations","always_invoice"]),lineItems:_.z.array(cl.extend({quantity:_.z.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:_.z.array(_.z.uuid()).max(100)}),Ro=_.z.strictObject({...Ss,type:_.z.literal("refund"),invoiceId:_.z.uuid(),merchantInvoiceId:qt,amountMinor:mt.refine(e=>e>0),mode:_.z.enum(["full","partial"]),entitlementAction:_.z.enum(["retain","revoke"]),cancelSubscriptions:_.z.array(qt).max(100)}),ul=_.z.discriminatedUnion("type",[Po,Eo,Ro]);var Ei=_.z.strictObject({phase:_.z.enum(["execution","payment","fulfillment","recording"]),code:Nn,reason:ms.optional(),recovery:ps,retryable:_.z.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),As={operationId:_.z.uuid(),customerId:_.z.uuid(),merchantExecutionId:qt,fulfillmentStatus:_.z.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:_.z.enum(["not_ready","pending","accepted","failed"]),updatedAt:Gt,problem:Ei.nullable(),pollAfterMs:_.z.number().int().min(1e3).max(6e4).nullable()},Sr=_.z.discriminatedUnion("type",[_.z.strictObject({...As,type:_.z.literal("purchase"),merchantOrderId:qt.nullable(),paymentStatus:_.z.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:_.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:Gt.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),_.z.strictObject({...As,type:_.z.literal("subscription_change"),status:_.z.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:qt,scheduledFor:Gt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),_.z.strictObject({...As,type:_.z.literal("refund"),status:_.z.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:qt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ll=_.z.discriminatedUnion("lookup",[_.z.strictObject({lookup:_.z.literal("found"),operationId:_.z.uuid(),customerId:_.z.uuid(),execution:Sr,readAt:Gt}),_.z.strictObject({lookup:_.z.literal("not_received"),operationId:_.z.uuid(),customerId:_.z.uuid(),execution:_.z.null(),readAt:Gt})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),ys=_.z.strictObject({merchantSubscriptionId:qt,revision:_.z.number().int().positive(),status:_.z.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Gt,periodEndsAt:Gt,cancelAtPeriodEnd:_.z.boolean(),hasDiscounts:_.z.boolean(),items:_.z.array(_.z.strictObject({merchantItemId:qt,priceId:_.z.uuid(),quantity:_.z.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"),bs=_.z.strictObject({merchantInvoiceId:qt,currency:Co,subtotalMinor:mt,discountMinor:mt,taxMinor:mt,totalMinor:mt,paidMinor:mt,periodStartsAt:Gt.nullable(),periodEndsAt:Gt.nullable(),lines:_.z.array(_.z.strictObject({merchantLineId:qt,priceId:_.z.uuid(),quantity:_.z.number().int().nonnegative().max(1e6),subtotalMinor:_.z.number().int().min(-1e8).max(1e8),discountMinor:mt,taxMinor:mt,totalMinor:_.z.number().int().min(-1e8).max(2e8),periodStartsAt:Gt.nullable(),periodEndsAt:Gt.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"),Kr={provider:_.z.literal("merchant"),eventId:_.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:_.z.uuid(),occurredAt:Gt},dl=_.z.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),pl=_.z.discriminatedUnion("type",[_.z.strictObject({...Kr,type:_.z.literal("purchase.completed"),operationId:_.z.uuid(),merchantOrderId:qt,paymentStatus:_.z.enum(["paid","trialing","no_payment_required"]),invoice:bs.nullable(),subscription:ys.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),_.z.strictObject({...Kr,type:_.z.literal("purchase.closed"),operationId:_.z.uuid(),status:_.z.enum(["failed","expired","canceled"])}),_.z.strictObject({...Kr,type:_.z.literal("subscription.observed"),operationId:_.z.uuid().nullable(),subscription:ys}),_.z.strictObject({...Kr,type:_.z.literal("subscription.change.completed"),operationId:_.z.uuid(),status:_.z.enum(["scheduled","applied"]),scheduledFor:Gt.nullable(),subscription:ys,invoice:bs.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),_.z.strictObject({...Kr,type:_.z.literal("invoice.paid"),merchantSubscriptionId:qt,invoice:bs}),_.z.strictObject({...Kr,type:_.z.literal("refund.updated"),operationId:_.z.uuid(),merchantRefundId:qt,status:_.z.enum(["pending","succeeded","failed"]),amountMinor:mt.refine(e=>e>0),currency:Co})]);var R=require("zod");var Gn=require("zod"),Vt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Kn=Gn.z.object({customerId:Gn.z.uuid(),sessionId:Gn.z.uuid(),accessToken:Gn.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Gn.z.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Gn.z.iso.datetime(),refreshExpiresAt:Gn.z.iso.datetime()});var Is=3;var rA=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],iA=R.z.enum(rA);var oA=R.z.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),fl=R.z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),aA=R.z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),sA=R.z.strictObject({keyId:fl,signingSecret:aA}),cA=R.z.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),gl=R.z.array(iA).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),hl=R.z.strictObject({bridgeVersion:R.z.literal(Is),projectId:R.z.uuid(),environmentId:R.z.uuid(),environment:R.z.enum(["sandbox","live"]),capabilities:gl,catalog:R.z.enum(["endpoint","static","none"]),billingEvents:R.z.array(dl).max(6),profiles:R.z.array(sl).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"})}),Al=R.z.strictObject({origin:cA,requiredCapabilities:gl}),uA=R.z.strictObject({revision:R.z.number().int().nonnegative(),checkedAt:R.z.iso.datetime(),outcome:R.z.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:R.z.strictObject({ping:R.z.enum(["passed","failed","not_checked"]),authentication:R.z.enum(["passed","failed","not_checked"]),catalog:R.z.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:hl.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),zI=R.z.strictObject({projectId:R.z.uuid(),environmentId:R.z.uuid(),environment:R.z.enum(["sandbox","live"]),execution:R.z.enum(["indiana","record_only"]),accountId:R.z.string().nullable(),revision:R.z.number().int().nonnegative(),authentication:R.z.strictObject({keyId:fl}).nullable(),secretStoreConfigured:R.z.boolean().optional(),connection:Al.nullable(),check:uA.nullable()});var ml=R.z.strictObject({projectId:R.z.uuid(),environmentId:R.z.uuid()}),$I=R.z.discriminatedUnion("action",[ml.extend({action:R.z.literal("save"),revision:R.z.number().int().nonnegative(),connection:Al,authentication:sA.optional()}),ml.extend({action:R.z.literal("check"),revision:R.z.number().int().nonnegative()})]),vs=R.z.strictObject({projectId:R.z.uuid(),environmentId:R.z.uuid(),environment:R.z.enum(["sandbox","live"])});var lA=R.z.strictObject({nativeUserId:R.z.string().min(1).max(128),session:Kn.strict()}),dA=R.z.strictObject({nativeUserId:R.z.string().min(1).max(128),presentation:R.z.strictObject({customerId:R.z.uuid(),decisionId:R.z.uuid(),offeringVersionId:R.z.uuid(),paywallVersionId:R.z.uuid(),variant:R.z.string().min(1).max(128)}).nullable()}),pA=R.z.strictObject({decisionId:R.z.uuid(),eventId:R.z.uuid()}),ko=R.z.strictObject({operationId:R.z.uuid(),customerId:R.z.uuid()}),jo=R.z.strictObject({scope:vs,operationId:R.z.uuid(),customerId:R.z.uuid(),confirmedAt:R.z.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:R.z.boolean(),instruction:ul}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),xs=Sr,Dn=R.z.string().min(1).max(120),mA=R.z.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),fA=R.z.strictObject({revision:Dn,updatedAt:R.z.iso.datetime(),provider:R.z.literal("merchant"),items:R.z.array(R.z.strictObject({merchantProductId:Dn,productVersionId:R.z.uuid(),name:R.z.string().min(1).max(255),kind:R.z.enum(["subscription","credit_pack"]),merchantPriceId:Dn,currency:R.z.string().regex(/^[a-z]{3}$/),amountMinor:R.z.number().int().nonnegative().max(1e8),interval:R.z.enum(["one_time","month","year"]),intervalCount:R.z.literal(1),includedCredits:R.z.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:R.z.enum(["none","month"]),creditPolicyId:Dn,available:R.z.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)}),gA=R.z.strictObject({customerId:R.z.uuid(),revision:R.z.string().min(1).max(128),observedAt:R.z.iso.datetime(),subscriptions:R.z.array(R.z.strictObject({merchantSubscriptionId:Dn,merchantProductId:Dn,productVersionId:R.z.uuid().nullable(),status:R.z.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:R.z.iso.datetime().nullable(),currentPeriodEndsAt:R.z.iso.datetime().nullable(),cancelAtPeriodEnd:R.z.boolean(),scheduledChange:R.z.strictObject({effectiveAt:R.z.iso.datetime(),merchantProductId:Dn}).nullable()})).max(100),purchaseHistory:R.z.strictObject({complete:R.z.boolean(),hasPaidPurchase:R.z.boolean(),lastPaidAt:R.z.iso.datetime().nullable()}),balances:R.z.array(R.z.strictObject({bucketId:Dn,key:Dn,available:mA,expiresAt:R.z.iso.datetime().nullable(),nextResetAt:R.z.iso.datetime().nullable()})).max(100)}),GI=R.z.strictObject({bridgeVersion:R.z.literal(Is),requestId:R.z.uuid(),command:R.z.string().min(1).max(64),scope:vs,error:R.z.strictObject({code:R.z.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:R.z.string().min(1).max(500),retryable:R.z.boolean(),recovery:R.z.string().min(1).max(80)})}),Ri=R.z.strictObject({}),hA={"bridge.ping":R.z.strictObject({challenge:R.z.uuid()}),"bridge.describe":Ri,"session.create":Ri,"catalog.read":Ri,"customer.commerce.read":Ri,"presentation.resolve":Ri,"presentation.report":pA,"purchase.execute":ko,"operation.read":ko,"subscription.change":ko,"refund.execute":ko},KI={"bridge.ping":R.z.strictObject({challenge:R.z.uuid()}),"bridge.describe":hl,"session.create":lA,"catalog.read":fA,"customer.commerce.read":gA,"presentation.resolve":dA,"presentation.report":R.z.strictObject({queued:R.z.literal(!0)}),"purchase.execute":xs,"operation.read":ll,"subscription.change":xs,"refund.execute":xs},HI=R.z.strictObject({bridgeVersion:R.z.literal(Is),requestId:R.z.uuid(),scope:vs,command:oA,data:R.z.unknown()}).superRefine((e,t)=>{hA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var xr=require("zod");var To=xr.z.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"),ZI=xr.z.object({amountCents:xr.z.number().int().min(0).max(1e8),currency:he,interval:xr.z.enum(["free","month","year"]),currencyOptions:xr.z.partialRecord(he,xr.z.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");var D=require("zod"),AA=D.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Sl=D.z.enum(["single_use","continuous_use"]),ws=D.z.record(D.z.string(),D.z.union([D.z.string(),D.z.number(),D.z.boolean()]).transform(String).pipe(D.z.string())),yl=D.z.string().min(1).max(64).refine(e=>!e.includes("::")),xl={credit_amount:D.z.number(),tier_behavior:D.z.never().optional(),tiers:D.z.never().optional()},Il={credit_amount:D.z.never().optional(),tier_behavior:D.z.literal("graduated"),tiers:D.z.array(D.z.strictObject({to:D.z.union([D.z.number(),D.z.literal("inf")]),credit_amount:D.z.number()}))},yA=D.z.union([D.z.strictObject({match:ws,priority:D.z.number().int().optional(),...xl}),D.z.strictObject({match:ws,priority:D.z.number().int().optional(),...Il})]),bA=D.z.strictObject({match:ws,factor:D.z.number().positive().optional(),add:D.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),bl={metered_feature_id:D.z.string(),feature_amount:D.z.number().optional(),dimensions:D.z.record(yl,yA).optional(),multipliers:D.z.record(yl,bA).optional()},Os=D.z.union([D.z.strictObject({...bl,...xl}),D.z.strictObject({...bl,...Il})]),Do=D.z.number().min(-100),vl=D.z.record(D.z.string(),D.z.strictObject({markup:Do})).nullish(),Fo=D.z.record(D.z.string().regex(/.+\/.+/),D.z.strictObject({markup:Do.optional(),input_cost:D.z.number().min(0).optional(),output_cost:D.z.number().min(0).optional()})).nullish(),SA=D.z.strictObject({default_markup:Do.optional(),provider_markups:vl,model_markups:Fo}),YI=D.z.strictObject({schema:D.z.array(Os).optional(),markups:SA.optional()}),xA=D.z.strictObject({filters:D.z.array(D.z.strictObject({property:D.z.string(),operator:D.z.string(),value:D.z.array(D.z.string())})),aggregate:D.z.strictObject({type:D.z.string(),property:D.z.string().nullable()}),usage_type:Sl}),wl=D.z.strictObject({schema:D.z.array(Os).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:D.z.boolean().optional(),usage_type:Sl.default("single_use").overwrite(()=>"single_use"),default_markup:Do.optional(),provider_markups:vl}),_s=wl.safeExtend({schema:D.z.array(Os).length(0)}),No={id:AA,name:D.z.string().min(1),display:D.z.strictObject({singular:D.z.string().optional(),plural:D.z.string().optional()}).nullish(),event_names:D.z.array(D.z.string()).default([]),model_markups:Fo,stripe_meter:D.z.strictObject({id:D.z.string(),event_name:D.z.string()}).nullish(),stripe_product_id:D.z.string().nullish()},Cs=e=>D.z.discriminatedUnion("type",[D.z.strictObject({...No,...e,type:D.z.literal("boolean"),config:D.z.null()}),D.z.strictObject({...No,...e,type:D.z.literal("metered"),config:xA}),D.z.strictObject({...No,...e,type:D.z.literal("credit_system"),config:wl}),D.z.strictObject({...No,...e,type:D.z.literal("ai_credit_system"),config:_s})]),XI=Cs({}),IA=D.z.strictObject({id:D.z.boolean(),type:D.z.boolean(),usage_type:D.z.boolean()}),vA={internal_id:D.z.uuid(),org_id:D.z.uuid(),created_at:D.z.number(),env:D.z.enum(["sandbox","live"]),archived:D.z.boolean(),project_id:D.z.uuid(),environment_id:D.z.uuid(),revision:D.z.number().int().nonnegative(),update_rules:IA},Ol=Cs(vA),ev=D.z.strictObject({rows:D.z.array(Ol).max(200),nextCursor:D.z.uuid().nullable()}),tv=D.z.strictObject({features:D.z.array(Ol).max(500),limited:D.z.boolean()}),nv=D.z.union([Cs({action:D.z.literal("save"),internal_id:D.z.uuid().nullable(),revision:D.z.number().int().nonnegative()}),D.z.strictObject({action:D.z.enum(["archive","restore","delete"]),internal_id:D.z.uuid(),revision:D.z.number().int().nonnegative()})]);var wr=require("zod");var it=require("zod"),Kt=it.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),ge=it.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Mo=it.z.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Ps=ge.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),_l=it.z.string().min(1).max(64),Ir=it.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Cl=it.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),St=it.z.record(_l,it.z.union([it.z.string().max(120),it.z.number().finite(),it.z.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),Pl=it.z.record(_l,it.z.union([it.z.string().max(120),it.z.number().finite(),it.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Hr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},El=it.z.array(it.z.object({upTo:Ps.nullable(),cost:ge}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Hr(t.upTo)>Hr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),wA=it.z.object({key:Cl,match:Pl,priority:it.z.number().int().default(0),cost:ge.optional(),tiers:El.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),OA=it.z.object({key:Cl,match:Pl,factor:Ps.optional(),add:Mo.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),_A=it.z.object({units:Ps.default("1"),cost:ge,tiers:El.optional(),dimensions:it.z.array(wA).max(12).optional(),multipliers:it.z.array(OA).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(o=>o.key)).size!==n.length||new Set(r.map(o=>o.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[o,s]of n.entries())for(let c of n.slice(o+1))Object.keys(s.match).length===Object.keys(c.match).length&&s.priority===c.priority&&!Object.keys(s.match).some(u=>c.match[u]!==void 0&&c.match[u]!==s.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(o=>o.cost),...n.flatMap(o=>[...o.cost===void 0?[]:[o.cost],...(o.tiers??[]).map(s=>s.cost)])],a=Hr(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((p,g)=>s&1<<g);if(c.some((p,g)=>c.slice(g+1).some(f=>Object.keys(p.match).some(S=>f.match[S]!==void 0&&f.match[S]!==p.match[S]))))continue;let u=Hr(o),d=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Hr(g.factor??"1"),d*=BigInt("1000000"),m+=Hr(g.add??"0"));let w=(u+m*d)*BigInt("1000000"),I=d*a;(w<BigInt("0")||w%I!==BigInt("0")||w/I>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),iv=_A.safeExtend({featureKey:Ir});var vr=require("zod"),Rl=vr.z.number().int().min(0).max(1e8),ki=vr.z.strictObject({kind:vr.z.enum(["graduated","volume"]),tiers:vr.z.array(vr.z.strictObject({upTo:vr.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Rl,flatAmountMinor:Rl.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function Es(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?ki.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function qo(e){return Es({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var CA=ge.refine(e=>/[1-9]/.test(e)),Vo=wr.z.strictObject({units:CA,prices:wr.z.array(wr.z.strictObject({currency:he,amountMinor:wr.z.number().int().min(0).max(1e8),pricing:ki.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:wr.z.number().int().min(0).max(1e4),maximumQuantity:wr.z.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&Es({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function kl(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");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"))}function jl(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=kl(e)+kl(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}var h=require("zod");var W=require("zod");var vt=require("zod");var j=require("zod");function Tl(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function Bo(e,t,n){return n===2?Tl(Tl(e+t)+"")%1e4/1e4:null}function PA(e){return e<=0?[]:new Array(e).fill(1/e)}function Uo(e,t){return e>=t[0]&&e<t[1]}function Nl(e,t){for(let[n,r]of t.entries())if(Uo(e,r))return n;return-1}function Dl(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=PA(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,c)=>c+s,0);(i<.99||i>1.01)&&(n=r);let a=0,o=t;return n.map(s=>{let c=a;return a+=s,[c,c+o*s]})}function Fl(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let a=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>o===void 0?NaN:parseInt(o))[0];return a!==void 0&&a>=0&&a<n?a:null}function Ml(e){try{return e()}catch{return!1}}function ji(e){return typeof e=="string"?e:JSON.stringify(e)}function en(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function EA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function ql(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=jA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function RA(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function kA(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,a)=>{r.push([e.searchParams.get(a)||"",i,!1])}),!r.some(i=>!RA(i[0],i[1],i[2]))}catch{return!1}}function jA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=EA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return kA(r,n);return!1}catch{return!1}}function Rs(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function Lo(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function Vl(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Lo(e.savedGroups??{})}var TA=e=>e/2**32|0,NA=e=>e>>>0;function Bl(e,t,n,r){let i=TA(n),a=NA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Ul(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ks=e=>e?`"${e}" `:"";function DA(e,t=""){if(typeof e!="number")throw new TypeError(ks(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ks(t)+"expected integer >= 0, got "+e);return e}function zo(e,t,n=""){if(Ul(e)&&(t===void 0||e.length===t))return e;t!==void 0&&DA(t,"length");let r=Ul(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=ks(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var FA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Ll=(e,t)=>{FA(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function js(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function zl(e,t){zo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Ts(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $o(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function hn(e,t){return e<<32-t|e>>>t}var MA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",qA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Qr(e){if(zo(e),MA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=qA[e[n]];return t}function VA(e,t,n="opts"){return Ll(e,"defaults"),t!==void 0&&Ll(t,n),Object.assign(Object.create(null),e,t)}function $l(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=VA({},t,"info");let n=(i,a)=>e(a).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var Gl=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Kl(e,t,n){return e&t^~e&n}function Hl(e,t,n){return e&t^e&n^t&n}var Go=class{constructor(t,n,r,i){Le(this,"blockLen");Le(this,"outputLen");Le(this,"canXOF",!1);Le(this,"padOffset");Le(this,"isLE");Le(this,"buffer");Le(this,"view");Le(this,"finished",!1);Le(this,"length",0);Le(this,"pos",0);Le(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=$o(this.buffer)}update(t){js(this),zo(t);let{view:n,buffer:r,blockLen:i}=this,a=t.length,o=!1;for(let s=0;s<a;){let c=Math.min(i-this.pos,a-s);if(c===i){let u=$o(t);for(;i<=a-s;s+=i)this.process(u,s);o=!0;continue}r.set(s===0&&c===a?t:t.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(n,0),this.pos=0,o=!0)}return this.length+=t.length,o&&this.roundClean(),this}digestInto(t){js(this),zl(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:a}=this,{pos:o}=this;n[o++]=128,n.fill(0,o),this.padOffset>i-o&&(this.process(r,0),n.fill(0)),Bl(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:$o(t),c=this.outputLen,u=c/4,d=this.get();if(c%4||u>d.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,d[m],a)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=i,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Ql=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var BA=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Hn=new Uint32Array(64),Ns=class extends Go{constructor(n,r){super(64,n,8,!1);Le(this,"A",0);Le(this,"B",0);Le(this,"C",0);Le(this,"D",0);Le(this,"E",0);Le(this,"F",0);Le(this,"G",0);Le(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;return[n,r,i,a,o,s,c,u]}set(n,r,i,a,o,s,c,u){this.A=n|0,this.B=r|0,this.C=i|0,this.D=a|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=u|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let w=0;w<16;w++,r+=4)Hn[w]=n.getUint32(r,!1);for(let w=16;w<64;w++){let I=Hn[w-15],p=Hn[w-2],g=hn(I,7)^hn(I,18)^I>>>3,f=hn(p,17)^hn(p,19)^p>>>10;Hn[w]=f+Hn[w-7]+g+Hn[w-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:d,H:m}=this;for(let w=0;w<64;w++){let I=hn(c,6)^hn(c,11)^hn(c,25),p=m+I+Kl(c,u,d)+BA[w]+Hn[w]|0,f=(hn(i,2)^hn(i,13)^hn(i,22))+Hl(i,a,o)|0;m=d,d=u,u=c,c=s+p|0,s=o,o=a,a=i,i=p+f|0}i=i+this.A|0,a=a+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,u=u+this.F|0,d=d+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,d,m)}roundClean(){Ts(Hn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ts(this.buffer)}},Ds=class extends Ns{constructor(){super(32,Ql)}};var Jr=$l(()=>new Ds,Gl(1));var Jl=new Map,Fs=32,Zl=new WeakMap,Wl=new WeakMap;function UA(e){return Qr(Jr(new TextEncoder().encode(String(e))))}var Ho=e=>Array.isArray(e)?e.map(Ho):typeof e=="string"||typeof e=="number"?UA(e):null,Ko=e=>typeof e=="string"?e.toLowerCase():e;function nd(e){let t=Zl.get(e);return t||(t=new Set(e),Zl.set(e,t)),t}function LA(e){let t=Wl.get(e);return t||(t=new Set(e.map(Ko)),Wl.set(e,t)),t}function Zr(e){Lo(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=Fs&&nd(n)}return e}function Qt(e,t,n,r){n=n||{},r||Lo(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!td(e,a,n,r))return!1;break;case"$nor":if(td(e,a,n,r))return!1;break;case"$and":if(!HA(e,a,n,r))return!1;break;case"$not":if(Qt(e,a,n,r))return!1;break;case"$savedGroup":if(!zA(e,a,n,r))return!1;break;default:if(!Ti(a,rd(e,i),n,!1,r))return!1}return!0}function zA(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:a}=t;if(typeof i!="string"||r.has(i)||a!==void 0&&typeof a!="string")return!1;let o=n[i];if(!o||Array.isArray(o)||typeof o!="object")return!1;let s=new Set(r).add(i);if(o.type==="list"||o.type==="hashed"){let c=a??o.attributeKey;if(typeof c!="string"||!Array.isArray(o.values))return!1;let u=rd(e,c);return Or(o.type==="hashed"?Ho(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:Qt(e,o.condition,n,s):!1}function rd(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function Yl(e,t=!1){let n=`${e}${t?"/i":""}`,r=Jl.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Jl.set(n,r)),r}function Ti(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!id(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!KA(o,t,a[o],n,i))return!1;return!0}function id(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function $A(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function GA(e,t,n,r){if(!Array.isArray(e))return!1;let i=id(t)?a=>Ti(t,a,n,!1,r):a=>Qt(a,t,n,r);for(let a=0;a<e.length;a++)if((e[a]??null)!==null&&i(e[a]))return!0;return!1}function Or(e,t,n=!1){if(n){let i;if(t.length>=Fs){let a=LA(t);i=o=>{let s=Ko(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Ko(a)===Ko(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=Fs?(i=>a=>i.has(a))(nd(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Xl(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function ed(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let a=0;a<t.length;a++){let o=!1;for(let s=0;s<e.length;s++)if(Ti(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function KA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return en(t)===en(n);case"$vne":return en(t)!==en(n);case"$vgt":return en(t)>en(n);case"$vgte":return en(t)>=en(n);case"$vlt":return en(t)<en(n);case"$vlte":return en(t)<=en(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return a<o;case"$lte":return a<=o;case"$gt":return a>o;case"$gte":return a>=o;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?Or(t,n):!1;case"$ini":return Array.isArray(n)?Or(t,n,!0):!1;case"$inGroup":{let s=r[n],c=Xl(s);return c===null?!1:Or(s?.type==="hashed"?Ho(t):t,c)}case"$notInGroup":{let s=r[n],c=Xl(s);return c===null?!1:!Or(s?.type==="hashed"?Ho(t):t,c)}case"$nin":return Array.isArray(n)?!Or(t,n):!1;case"$nini":return Array.isArray(n)?!Or(t,n,!0):!1;case"$not":return!Ti(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ti(n,t.length,r,!1,i):!1;case"$elemMatch":return GA(t,n,r,i);case"$all":return Array.isArray(n)?ed(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?ed(t,n,r,!0,i):!1;case"$regex":try{return Yl(n).test(t)}catch{return!1}case"$regexi":try{return Yl(n,!0).test(t)}catch{return!1}case"$type":return $A(t)===n;default:return!1}}function td(e,t,n,r){if(!t.length)return!0;for(let i of t)if(Qt(e,i,n,r))return!0;return!1}function HA(e,t,n,r){for(let i of t)if(!Qt(e,i,n,r))return!1;return!0}function Ms(e){return Vl(e),{context:e,stack:{evaluatedFeatures:new Set}}}function qs(e){return{...e.attributes,...e.attributeOverrides}}function Qn(e,t,n){let r=t||"id",i="",a=qs(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Je(e,t,n){e.context.log?.(t,n)}function Qo(e,t){return t=t||0,`${e}__${t}`}function Vs(e,t){return`${e}||${t}`}function QA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Qn(e,t),o=Vs(i,ji(a)),{hashAttribute:s,hashValue:c}=Qn(e,n),u=c?Vs(s,ji(c)):null,d={};return u&&r[u]&&Object.assign(d,r[u].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}function od({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:a,expMeta:o}){n=n||0,a=a||0,r=r||"id",o=o||[];let s=Qo(t,n),c=QA(e,r,i);if(a>0)for(let m=0;m<a;m++){let w=Qo(t,m);if(c[w]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let d=o.findIndex(m=>m.key===u);return d<0?{variation:-1}:{variation:d}}function ad(e,t,n,r){let i=Vs(t,n),a=e.stickyBucketAssignmentDocs,o=a&&a[i]?a[i].assignments||{}:{},s={...o,...r},c=JSON.stringify(o)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:c}}function sd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Jo(e,t){let n=Ms(t),r=ud(e,null,n);return t.onExperimentEval?.(e,r),r}function Fn(e,t){return Us(e,Ms(t))}function JA(e){return e.forcedVariations||{}}function cd(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=pd(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Bs(()=>r.onExperimentViewed?.(t,n))}function ZA(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}Bs(()=>r.onFeatureUsage?.(t,n))}function Bs(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function Us(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Je(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Jn(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Rs(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Je(t,"Global override",{id:e,value:i.get(e)}),Jn(t,e,i.get(e),"override");if(!r)return Je(t,"Unknown feature",{id:e}),Jn(t,e,null,"unknownFeature");if(r.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let u of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let d=Us(u.id,t);if(d.source==="cyclicPrerequisite")return Jn(t,e,null,"cyclicPrerequisite");let m={value:d.value};if(!Qt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Je(t,"Feature blocked by prerequisite",{id:e,rule:o}),Jn(t,e,null,"prerequisite");Je(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&dd(o.filters,t)){Je(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!ld(o.condition,t)){Je(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!WA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Je(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Je(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{cd(t,u.experiment,u.result)}),Jn(t,e,o.force,"force",o.id)}if(!o.variations){Je(t,"Skip invalid rule",{id:e,rule:o});continue}let s={variations:o.variations,key:o.key||e};"coverage"in o&&(s.coverage=o.coverage),o.weights&&(s.weights=o.weights),o.hashAttribute&&(s.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(s.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(s.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(s.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(s.minBucketVersion=o.minBucketVersion),o.meta&&(s.meta=o.meta),o.ranges&&(s.ranges=o.ranges),o.name&&(s.name=o.name),o.phase&&(s.phase=o.phase),o.seed&&(s.seed=o.seed),o.hashVersion&&(s.hashVersion=o.hashVersion),o.filters&&(s.filters=o.filters),o.condition&&(s.condition=o.condition);let c=ud(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Jn(t,e,c.value,"experiment",o.id,s,c)}}return Je(t,"Use default value",{id:e,value:r.defaultValue}),Jn(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function ud(e,t,n){let{context:r}=n;Rs(e);let i=e.key,a=e.variations.length;if(a<2)return Je(n,"Invalid experiment",{id:i}),Et(n,e,-1,!1,t);if(r.enabled===!1)return Je(n,"Context disabled",{id:i}),Et(n,e,-1,!1,t);if(e.urlPatterns&&!ql(r.url||"",e.urlPatterns))return Je(n,"Skip because of url targeting",{id:i}),Et(n,e,-1,!1,t);let o=Fl(i,r.url||"",a);if(o!==null)return Je(n,"Force via querystring",{id:i,variation:o}),Et(n,e,o,!1,t);let c=JA(r)[i];if(c!==void 0)return Je(n,"Force via dev tools",{id:i,variation:c}),Et(n,e,c,!1,t);if(e.active===!1)return Je(n,"Skip because inactive",{id:i}),Et(n,e,-1,!1,t);let{hashAttribute:u,hashValue:d}=Qn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return Je(n,"Skip because missing hashAttribute",{id:i}),Et(n,e,-1,!1,t);let m=-1,w=!1,I=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:S}=od(sd({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));w=f>=0,m=f,I=!!S}if(!w){if(e.filters&&dd(e.filters,n))return Je(n,"Skip because of filters",{id:i}),Et(n,e,-1,!1,t);if(e.include&&!Ml(e.include))return Je(n,"Skip because of include function",{id:i}),Et(n,e,-1,!1,t);if(e.condition&&!ld(e.condition,n))return Je(n,"Skip because of condition exp",{id:i}),Et(n,e,-1,!1,t);if(e.parentConditions){let f=new Set(n.stack.evaluatedFeatures);for(let S of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let A=Us(S.id,n);if(A.source==="cyclicPrerequisite")return Et(n,e,-1,!1,t);let P={value:A.value};if(!Qt(P,S.condition||{},r.savedGroups||{}))return Je(n,"Skip because prerequisite evaluation fails",{id:i}),Et(n,e,-1,!1,t)}}}let p=Bo(e.seed||i,d,e.hashVersion??2);if(p===null)return Je(n,"Skip because of invalid hash version",{id:i}),Et(n,e,-1,!1,t);if(!w){let f=e.ranges||Dl(a,e.coverage===void 0?1:e.coverage,e.weights);m=Nl(p,f)}if(I)return Je(n,"Skip because sticky bucket version is blocked",{id:i}),Et(n,e,-1,!1,t,void 0,!0);if(m<0)return Je(n,"Skip because of coverage",{id:i}),Et(n,e,-1,!1,t);if("force"in e)return Je(n,"Force variation",{id:i,variation:e.force}),Et(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Je(n,"Skip because QA mode",{id:i}),Et(n,e,-1,!1,t);let g=Et(n,e,m,!0,t,p,w);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:S,doc:A}=ad(r,u,ji(d),{[Qo(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[S]=A;let P=r.saveStickyBucketAssignmentDoc;Bs(()=>P(A))}}return cd(n,e,g),Je(n,"In experiment",{id:i,variation:g.variationId}),g}function Jn(e,t,n,r,i,a,o){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return a&&(s.experiment=a),o&&(s.experimentResult=o),r!=="override"&&ZA(e,t,s),s}function ld(e,t){return Qt(qs(t.context),e,t.context.savedGroups||{})}function dd(e,t){return e.some(n=>{let{hashValue:r}=Qn(t.context,n.attribute);if(!r)return!0;let i=Bo(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>Uo(i,a))})}function WA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Qn(e.context,n,r);if(!s)return!1;let c=Bo(t,s,o??2);return c===null?!1:i?Uo(c,i):a!==void 0?c<=a:!0}function Et(e,t,n,r,i,a,o){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:u}=Qn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},m=t.variations[0];for(let[I,p]of t.variations.entries())if(I===n){m=p;break}let w={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return d.name&&(w.name=d.name),a!==void 0&&(w.bucket=a),d.passthrough&&(w.passthrough=d.passthrough),w}function pd(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
1
+ "use strict";var Io=Object.defineProperty;var Gh=Object.getOwnPropertyDescriptor;var Kh=Object.getOwnPropertyNames;var Hh=Object.prototype.hasOwnProperty;var Qh=(e,t,n)=>t in e?Io(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Jh=(e,t)=>{for(var n in t)Io(e,n,{get:t[n],enumerable:!0})},Zh=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Kh(t))!Hh.call(e,i)&&i!==n&&Io(e,i,{get:()=>t[i],enumerable:!(r=Gh(t,i))||r.enumerable});return e};var Wh=e=>Zh(Io({},"__esModule",{value:!0}),e);var Le=(e,t,n)=>Qh(e,typeof t!="symbol"?t+"":t,n);var PI={};Jh(PI,{IndianaError:()=>y,createConfigurationSync:()=>Lh,createFeatureClient:()=>ns,createIndianaReactNative:()=>wI,createLocalFunnelClient:()=>zh});module.exports=Wh(PI);var vo=require("zod"),Yh=vo.z.enum(["sandbox","live"]),ze=vo.z.object({projectId:vo.z.string().min(1),environment:Yh}).strict();var qe=require("zod"),Pi=qe.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Ku=qe.z.enum(["unknown","denied","provisional","granted"]),Hu=qe.z.enum(["ios","android"]),wo=qe.z.strictObject({installationId:qe.z.uuid(),publicKey:qe.z.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:qe.z.iso.datetime({offset:!0}),signature:qe.z.string().regex(/^[A-Za-z0-9_-]{86}$/)}),us=qe.z.string().regex(/^[a-f0-9]{64}$/),Qu=wo.extend({sequence:Pi,platform:Hu,credentialDigest:us}),Ju=wo.extend({credentialDigest:us}),Zu=wo.extend({sequence:Pi,platform:Hu}),Oo=wo.extend({sequence:Pi,credentialDigest:us,connectionId:qe.z.uuid().nullable(),kind:qe.z.enum(["fcm_token","apns_token"]).nullable(),token:qe.z.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Ku}),Wu=Oo,Yu=Oo.extend({challenge:qe.z.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),ls=qe.z.strictObject({requested:qe.z.literal(!0),expiresAt:qe.z.iso.datetime({offset:!0})}),br=qe.z.strictObject({installationId:qe.z.uuid(),bound:qe.z.boolean(),identitySeq:Pi,bindingGeneration:Pi,addressSeq:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:qe.z.uuid().nullable(),addressStatus:qe.z.enum(["active","invalid"]).nullable(),permission:Ku}),ds=qe.z.strictObject({channel:qe.z.enum(["email","sms","voice","push"]),state:qe.z.enum(["unknown","allowed","denied"]),revision:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:qe.z.iso.datetime({offset:!0}).nullable()}),kI=qe.z.strictObject({state:qe.z.enum(["allowed","denied"]),revision:qe.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Xu(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 bt=require("zod"),Nn=bt.z.enum(["INVALID_PROTOCOL_VERSION","UNSUPPORTED_PROTOCOL_VERSION","PROTOCOL_RETIRED","UNAUTHENTICATED","FORBIDDEN","SCOPE_MISMATCH","INVALID_REQUEST","NOT_FOUND","CONFLICT","PAYLOAD_TOO_LARGE","RATE_LIMITED","SERVICE_UNAVAILABLE","NOT_CONFIGURED","CAPABILITY_UNAVAILABLE","INTERNAL_ERROR"]),TI=bt.z.enum([...Nn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),NI=bt.z.enum([...Nn.options,"stale_revision"]),ps=bt.z.enum(["fix_request","authenticate","check_permissions","check_scope","resolve_conflict","reload_state","retry_same_request","configure_integration","check_availability","upgrade_sdk","recover_operation","contact_support"]),ms=bt.z.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),tl={INVALID_PROTOCOL_VERSION:{status:400,recovery:"fix_request"},UNSUPPORTED_PROTOCOL_VERSION:{status:400,recovery:"upgrade_sdk"},PROTOCOL_RETIRED:{status:410,recovery:"upgrade_sdk"},UNAUTHENTICATED:{status:401,recovery:"authenticate"},FORBIDDEN:{status:403,recovery:"check_permissions"},SCOPE_MISMATCH:{status:403,recovery:"check_scope"},INVALID_REQUEST:{status:400,recovery:"fix_request"},NOT_FOUND:{status:404,recovery:"fix_request"},CONFLICT:{status:409,recovery:"resolve_conflict"},PAYLOAD_TOO_LARGE:{status:413,recovery:"fix_request"},RATE_LIMITED:{status:429,recovery:"retry_same_request"},SERVICE_UNAVAILABLE:{status:503,recovery:"retry_same_request"},NOT_CONFIGURED:{status:501,recovery:"configure_integration"},CAPABILITY_UNAVAILABLE:{status:501,recovery:"check_availability"},INTERNAL_ERROR:{status:500,recovery:"recover_operation"}};var el={TIMEOUT:"recover_operation",NETWORK_ERROR:"recover_operation",HTTP_ERROR:"recover_operation",INVALID_RESPONSE:"recover_operation",NOT_IDENTIFIED:"authenticate",INVALID_TOKEN:"authenticate",INVALID_URL:"fix_request",INVALID_TIMEOUT:"fix_request",SERVER_ONLY:"fix_request",PROTOCOL_MISMATCH:"upgrade_sdk",IDENTITY_CHANGED:"reload_state",INVALID_STATE:"reload_state",EVENT_QUEUE_FULL:"retry_same_request",COMMAND_PENDING:"recover_operation",DECISION_PENDING:"recover_operation",DECISION_ACCEPTANCE_UNKNOWN:"recover_operation",RUN_RECONCILIATION_REQUIRED:"recover_operation",DECISION_FAILED:"contact_support",COMMAND_STORAGE_CONFLICT:"resolve_conflict",COMMAND_STORAGE_INVALID:"fix_request",CONFIGURATION_UNAVAILABLE:"check_availability",CONFIGURATION_EXPIRED:"reload_state",CONFIGURATION_CHANGED:"reload_state",CONFIGURATION_DISPOSED:"reload_state",UNSUPPORTED_SCHEMA:"upgrade_sdk",FUNNEL_STOPPED:"check_availability",PAYWALL_UNAVAILABLE:"check_availability",EVALUATION_MODE:"reload_state",SERVER_REQUIRED:"fix_request",STICKY_SAVE_FAILED:"retry_same_request",TRANSITION_LIMIT:"resolve_conflict",PRECONDITION_FAILED:"reload_state",PRODUCT_UNAVAILABLE:"fix_request",PURCHASE_HANDLER_REQUIRED:"fix_request",EVENT_HANDLER_REQUIRED:"fix_request",CLOSED:"fix_request",BRIDGE_UNAVAILABLE:"check_availability",INVALID_CONFIGURATION:"fix_request",NATIVE_OPERATION_FAILED:"contact_support",AI_PRICE_UNAVAILABLE:"fix_request",AI_USAGE_UNAVAILABLE:"recover_operation",AI_PROVIDER_ERROR:"check_availability",AI_BALANCE_REJECTED:"resolve_conflict"};function Xh(e,t){if(e==="CONFLICT"&&t===425)return{retryable:!0,recovery:"retry_same_request"};if(e==="CONFLICT"&&t===412)return{retryable:!1,recovery:"reload_state"};if(e==="INVALID_SERVER_RESPONSE")return{retryable:!1,recovery:"recover_operation"};if(e==="AMBIGUOUS_AUTHENTICATION")return{retryable:!1,recovery:"fix_request"};if(Object.hasOwn(el,e)){let r=el[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Nn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:tl[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function nl(e,t){let n=Nn.safeParse(e);if(n.success)return e==="CONFLICT"?[409,412,425].includes(t):e==="SERVICE_UNAVAILABLE"?[408,502,503,504].includes(t):e==="INVALID_REQUEST"?[400,405,415,422].includes(t):e==="NOT_CONFIGURED"?[501,503].includes(t):tl[n.data].status===t;let r={INVALID_SERVER_RESPONSE:[502],RESPONSE_TOO_LARGE:[502],AMBIGUOUS_AUTHENTICATION:[400],BROWSER_REQUIRED:[403],INVALID_REDIRECT_URI:[403],AUTHORIZATION_UNAVAILABLE:[400],UNREGISTERED_CLIENT:[403],MANAGEMENT_OPERATION_FAILED:[400,422,500]};return Object.hasOwn(r,e)&&(r[e]?.includes(t)??!1)}function eA(e,t=Date.now()){if(e===null)return;let n=e.trim();if(/^\d+$/.test(n)){let i=Number(n);return Number.isSafeInteger(i)?i:void 0}if(!/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(n))return;let r=Date.parse(n);return Number.isFinite(r)?Math.max(0,Math.ceil((r-t)/1e3)):void 0}var rl=bt.z.object({retryable:bt.z.boolean(),recovery:ps,reason:ms.optional(),retryAfterSeconds:bt.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),fs=bt.z.object({requestId:bt.z.uuid().optional(),error:bt.z.object({code:bt.z.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:bt.z.string(),...rl.partial().shape})}),DI=bt.z.object({error:fs.shape.error.extend({requestId:bt.z.uuid().optional()})}),FI=bt.z.object({error:bt.z.string(),code:bt.z.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:bt.z.uuid(),...rl.shape});function _o(e,t,n={}){let r=Xh(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?eA(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var gs="X-Indiana-Protocol",il="X-Indiana-SDK-Version";var hs={current:"0.10"};var ol=require("zod"),tA=["USD","EUR","CNY","GBP","JPY","CAD","AUD","NZD","CHF","HKD","SGD","KRW","INR","BRL","MXN","TWD","THB","IDR","MYR","PHP","VND","ZAR","AED","SAR","SEK","NOK","DKK","PLN","CZK","HUF","ILS","TRY","RON"],he=ol.z.enum(tA);var _=require("zod");var qt=_.z.string().min(1).max(200),Gt=_.z.iso.datetime({offset:!0}),mt=_.z.number().int().nonnegative().max(1e8),Co=_.z.string().regex(/^[A-Z]{3}$/),nA=["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"],al=_.z.enum(nA),sl=_.z.strictObject({priceId:_.z.uuid(),productVersionId:_.z.uuid(),productId:qt,quantity:_.z.number().int().min(1).max(1e6),unitAmountMinor:mt,totalMinor:mt,interval:_.z.enum(["week","month","year","one_off"]),intervalCount:_.z.number().int().min(1).max(52),kind:_.z.enum(["fixed","prepaid","seat"]),tiers:_.z.strictObject({mode:_.z.enum(["graduated","volume"]),tiers:_.z.array(_.z.strictObject({upTo:_.z.number().int().positive().nullable(),unitAmountMinor:mt,flatAmountMinor:mt.optional()})).min(2).max(12)}).nullable()}),rA=_.z.strictObject({grantId:_.z.uuid(),couponId:_.z.uuid(),amountMinor:mt,terms:_.z.discriminatedUnion("type",[_.z.strictObject({type:_.z.literal("percent"),percentOff:_.z.number().gt(0).max(100)}),_.z.strictObject({type:_.z.literal("amount"),amountOffMinor:mt,currency:Co})]),duration:_.z.discriminatedUnion("type",[_.z.strictObject({type:_.z.literal("once")}),_.z.strictObject({type:_.z.literal("forever")}),_.z.strictObject({type:_.z.literal("repeating"),months:_.z.number().int().min(1).max(36)})])}),Ss={provider:_.z.literal("merchant"),executor:_.z.literal("merchant"),operationId:_.z.uuid(),customerId:_.z.uuid(),configurationRevision:_.z.number().int().nonnegative(),connectionRevision:_.z.number().int().nonnegative(),currency:Co,expiresAt:Gt},Po=_.z.strictObject({...Ss,type:_.z.literal("purchase"),mode:_.z.enum(["payment","subscription"]),lineItems:_.z.array(sl).min(1).max(100),catalogAmountMinor:mt,discount:rA.nullable(),trialPeriodDays:_.z.number().int().min(1).max(730).nullable(),automaticTax:_.z.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"),Eo=_.z.strictObject({...Ss,type:_.z.literal("subscription_change"),subscriptionId:_.z.uuid(),merchantSubscriptionId:qt,membershipId:_.z.uuid(),subscriptionAction:_.z.enum(["update","cancel","schedule","release"]),supersedesOperationId:_.z.uuid().nullable(),change:_.z.discriminatedUnion("type",[_.z.strictObject({type:_.z.literal("cancel")}),_.z.strictObject({type:_.z.literal("uncancel")}),_.z.strictObject({type:_.z.literal("plan"),productVersionId:_.z.uuid()}),_.z.strictObject({type:_.z.literal("seats"),licenseKey:qt,quantity:_.z.number().int().nonnegative().max(1e6)}),_.z.strictObject({type:_.z.literal("quantity"),internal_feature_id:_.z.uuid(),quantity:_.z.number().int().nonnegative().max(1e6)}),_.z.strictObject({type:_.z.literal("billing_cycle"),billingCycleAnchor:_.z.union([_.z.literal("now"),_.z.number().int().positive()])})]),timing:_.z.enum(["immediate","renewal"]),effectiveAt:Gt,creditMinor:mt,debitMinor:mt,totalMinor:mt,discountMinor:mt,taxMinor:mt,proration:_.z.enum(["none","create_prorations","always_invoice"]),lineItems:_.z.array(sl.extend({quantity:_.z.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:_.z.array(_.z.uuid()).max(100)}),Ro=_.z.strictObject({...Ss,type:_.z.literal("refund"),invoiceId:_.z.uuid(),merchantInvoiceId:qt,amountMinor:mt.refine(e=>e>0),mode:_.z.enum(["full","partial"]),entitlementAction:_.z.enum(["retain","revoke"]),cancelSubscriptions:_.z.array(qt).max(100)}),cl=_.z.discriminatedUnion("type",[Po,Eo,Ro]);var Ei=_.z.strictObject({phase:_.z.enum(["execution","payment","fulfillment","recording"]),code:Nn,reason:ms.optional(),recovery:ps,retryable:_.z.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),As={operationId:_.z.uuid(),customerId:_.z.uuid(),merchantExecutionId:qt,fulfillmentStatus:_.z.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:_.z.enum(["not_ready","pending","accepted","failed"]),updatedAt:Gt,problem:Ei.nullable(),pollAfterMs:_.z.number().int().min(1e3).max(6e4).nullable()},Sr=_.z.discriminatedUnion("type",[_.z.strictObject({...As,type:_.z.literal("purchase"),merchantOrderId:qt.nullable(),paymentStatus:_.z.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:_.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:Gt.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),_.z.strictObject({...As,type:_.z.literal("subscription_change"),status:_.z.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:qt,scheduledFor:Gt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),_.z.strictObject({...As,type:_.z.literal("refund"),status:_.z.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:qt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),ul=_.z.discriminatedUnion("lookup",[_.z.strictObject({lookup:_.z.literal("found"),operationId:_.z.uuid(),customerId:_.z.uuid(),execution:Sr,readAt:Gt}),_.z.strictObject({lookup:_.z.literal("not_received"),operationId:_.z.uuid(),customerId:_.z.uuid(),execution:_.z.null(),readAt:Gt})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),ys=_.z.strictObject({merchantSubscriptionId:qt,revision:_.z.number().int().positive(),status:_.z.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Gt,periodEndsAt:Gt,cancelAtPeriodEnd:_.z.boolean(),hasDiscounts:_.z.boolean(),items:_.z.array(_.z.strictObject({merchantItemId:qt,priceId:_.z.uuid(),quantity:_.z.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"),bs=_.z.strictObject({merchantInvoiceId:qt,currency:Co,subtotalMinor:mt,discountMinor:mt,taxMinor:mt,totalMinor:mt,paidMinor:mt,periodStartsAt:Gt.nullable(),periodEndsAt:Gt.nullable(),lines:_.z.array(_.z.strictObject({merchantLineId:qt,priceId:_.z.uuid(),quantity:_.z.number().int().nonnegative().max(1e6),subtotalMinor:_.z.number().int().min(-1e8).max(1e8),discountMinor:mt,taxMinor:mt,totalMinor:_.z.number().int().min(-1e8).max(2e8),periodStartsAt:Gt.nullable(),periodEndsAt:Gt.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"),Kr={provider:_.z.literal("merchant"),eventId:_.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:_.z.uuid(),occurredAt:Gt},ll=_.z.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),dl=_.z.discriminatedUnion("type",[_.z.strictObject({...Kr,type:_.z.literal("purchase.completed"),operationId:_.z.uuid(),merchantOrderId:qt,paymentStatus:_.z.enum(["paid","trialing","no_payment_required"]),invoice:bs.nullable(),subscription:ys.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),_.z.strictObject({...Kr,type:_.z.literal("purchase.closed"),operationId:_.z.uuid(),status:_.z.enum(["failed","expired","canceled"])}),_.z.strictObject({...Kr,type:_.z.literal("subscription.observed"),operationId:_.z.uuid().nullable(),subscription:ys}),_.z.strictObject({...Kr,type:_.z.literal("subscription.change.completed"),operationId:_.z.uuid(),status:_.z.enum(["scheduled","applied"]),scheduledFor:Gt.nullable(),subscription:ys,invoice:bs.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),_.z.strictObject({...Kr,type:_.z.literal("invoice.paid"),merchantSubscriptionId:qt,invoice:bs}),_.z.strictObject({...Kr,type:_.z.literal("refund.updated"),operationId:_.z.uuid(),merchantRefundId:qt,status:_.z.enum(["pending","succeeded","failed"]),amountMinor:mt.refine(e=>e>0),currency:Co})]);var R=require("zod");var Gn=require("zod"),Vt=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Kn=Gn.z.object({customerId:Gn.z.uuid(),sessionId:Gn.z.uuid(),accessToken:Gn.z.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Gn.z.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Gn.z.iso.datetime(),refreshExpiresAt:Gn.z.iso.datetime()});var Is=3;var iA=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],oA=R.z.enum(iA);var aA=R.z.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),ml=R.z.string().regex(/^[A-Za-z0-9_-]{1,64}$/),sA=R.z.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),cA=R.z.strictObject({keyId:ml,signingSecret:sA}),uA=R.z.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),fl=R.z.array(oA).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),gl=R.z.strictObject({bridgeVersion:R.z.literal(Is),projectId:R.z.uuid(),environmentId:R.z.uuid(),environment:R.z.enum(["sandbox","live"]),capabilities:fl,catalog:R.z.enum(["endpoint","static","none"]),billingEvents:R.z.array(ll).max(6),profiles:R.z.array(al).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"})}),hl=R.z.strictObject({origin:uA,requiredCapabilities:fl}),lA=R.z.strictObject({revision:R.z.number().int().nonnegative(),checkedAt:R.z.iso.datetime(),outcome:R.z.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:R.z.strictObject({ping:R.z.enum(["passed","failed","not_checked"]),authentication:R.z.enum(["passed","failed","not_checked"]),catalog:R.z.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:gl.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),GI=R.z.strictObject({projectId:R.z.uuid(),environmentId:R.z.uuid(),environment:R.z.enum(["sandbox","live"]),execution:R.z.enum(["indiana","record_only"]),accountId:R.z.string().nullable(),revision:R.z.number().int().nonnegative(),authentication:R.z.strictObject({keyId:ml}).nullable(),secretStoreConfigured:R.z.boolean().optional(),connection:hl.nullable(),check:lA.nullable()});var pl=R.z.strictObject({projectId:R.z.uuid(),environmentId:R.z.uuid()}),KI=R.z.discriminatedUnion("action",[pl.extend({action:R.z.literal("save"),revision:R.z.number().int().nonnegative(),connection:hl,authentication:cA.optional()}),pl.extend({action:R.z.literal("check"),revision:R.z.number().int().nonnegative()})]),vs=R.z.strictObject({projectId:R.z.uuid(),environmentId:R.z.uuid(),environment:R.z.enum(["sandbox","live"])});var dA=R.z.strictObject({nativeUserId:R.z.string().min(1).max(128),session:Kn.strict()}),pA=R.z.strictObject({nativeUserId:R.z.string().min(1).max(128),presentation:R.z.strictObject({customerId:R.z.uuid(),decisionId:R.z.uuid(),offeringVersionId:R.z.uuid(),paywallVersionId:R.z.uuid(),variant:R.z.string().min(1).max(128)}).nullable()}),mA=R.z.strictObject({decisionId:R.z.uuid(),eventId:R.z.uuid()}),ko=R.z.strictObject({operationId:R.z.uuid(),customerId:R.z.uuid()}),jo=R.z.strictObject({scope:vs,operationId:R.z.uuid(),customerId:R.z.uuid(),confirmedAt:R.z.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:R.z.boolean(),instruction:cl}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),xs=Sr,Dn=R.z.string().min(1).max(120),fA=R.z.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),gA=R.z.strictObject({revision:Dn,updatedAt:R.z.iso.datetime(),provider:R.z.literal("merchant"),items:R.z.array(R.z.strictObject({merchantProductId:Dn,productVersionId:R.z.uuid(),name:R.z.string().min(1).max(255),kind:R.z.enum(["subscription","credit_pack"]),merchantPriceId:Dn,currency:R.z.string().regex(/^[a-z]{3}$/),amountMinor:R.z.number().int().nonnegative().max(1e8),interval:R.z.enum(["one_time","month","year"]),intervalCount:R.z.literal(1),includedCredits:R.z.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:R.z.enum(["none","month"]),creditPolicyId:Dn,available:R.z.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)}),hA=R.z.strictObject({customerId:R.z.uuid(),revision:R.z.string().min(1).max(128),observedAt:R.z.iso.datetime(),subscriptions:R.z.array(R.z.strictObject({merchantSubscriptionId:Dn,merchantProductId:Dn,productVersionId:R.z.uuid().nullable(),status:R.z.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:R.z.iso.datetime().nullable(),currentPeriodEndsAt:R.z.iso.datetime().nullable(),cancelAtPeriodEnd:R.z.boolean(),scheduledChange:R.z.strictObject({effectiveAt:R.z.iso.datetime(),merchantProductId:Dn}).nullable()})).max(100),purchaseHistory:R.z.strictObject({complete:R.z.boolean(),hasPaidPurchase:R.z.boolean(),lastPaidAt:R.z.iso.datetime().nullable()}),balances:R.z.array(R.z.strictObject({bucketId:Dn,key:Dn,available:fA,expiresAt:R.z.iso.datetime().nullable(),nextResetAt:R.z.iso.datetime().nullable()})).max(100)}),HI=R.z.strictObject({bridgeVersion:R.z.literal(Is),requestId:R.z.uuid(),command:R.z.string().min(1).max(64),scope:vs,error:R.z.strictObject({code:R.z.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:R.z.string().min(1).max(500),retryable:R.z.boolean(),recovery:R.z.string().min(1).max(80)})}),Ri=R.z.strictObject({}),AA={"bridge.ping":R.z.strictObject({challenge:R.z.uuid()}),"bridge.describe":Ri,"session.create":Ri,"catalog.read":Ri,"customer.commerce.read":Ri,"presentation.resolve":Ri,"presentation.report":mA,"purchase.execute":ko,"operation.read":ko,"subscription.change":ko,"refund.execute":ko},QI={"bridge.ping":R.z.strictObject({challenge:R.z.uuid()}),"bridge.describe":gl,"session.create":dA,"catalog.read":gA,"customer.commerce.read":hA,"presentation.resolve":pA,"presentation.report":R.z.strictObject({queued:R.z.literal(!0)}),"purchase.execute":xs,"operation.read":ul,"subscription.change":xs,"refund.execute":xs},JI=R.z.strictObject({bridgeVersion:R.z.literal(Is),requestId:R.z.uuid(),scope:vs,command:aA,data:R.z.unknown()}).superRefine((e,t)=>{AA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});var xr=require("zod");var To=xr.z.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"),YI=xr.z.object({amountCents:xr.z.number().int().min(0).max(1e8),currency:he,interval:xr.z.enum(["free","month","year"]),currencyOptions:xr.z.partialRecord(he,xr.z.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");var D=require("zod"),yA=D.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),bl=D.z.enum(["single_use","continuous_use"]),ws=D.z.record(D.z.string(),D.z.union([D.z.string(),D.z.number(),D.z.boolean()]).transform(String).pipe(D.z.string())),Al=D.z.string().min(1).max(64).refine(e=>!e.includes("::")),Sl={credit_amount:D.z.number(),tier_behavior:D.z.never().optional(),tiers:D.z.never().optional()},xl={credit_amount:D.z.never().optional(),tier_behavior:D.z.literal("graduated"),tiers:D.z.array(D.z.strictObject({to:D.z.union([D.z.number(),D.z.literal("inf")]),credit_amount:D.z.number()}))},bA=D.z.union([D.z.strictObject({match:ws,priority:D.z.number().int().optional(),...Sl}),D.z.strictObject({match:ws,priority:D.z.number().int().optional(),...xl})]),SA=D.z.strictObject({match:ws,factor:D.z.number().positive().optional(),add:D.z.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),yl={metered_feature_id:D.z.string(),feature_amount:D.z.number().optional(),dimensions:D.z.record(Al,bA).optional(),multipliers:D.z.record(Al,SA).optional()},Os=D.z.union([D.z.strictObject({...yl,...Sl}),D.z.strictObject({...yl,...xl})]),Do=D.z.number().min(-100),Il=D.z.record(D.z.string(),D.z.strictObject({markup:Do})).nullish(),Fo=D.z.record(D.z.string().regex(/.+\/.+/),D.z.strictObject({markup:Do.optional(),input_cost:D.z.number().min(0).optional(),output_cost:D.z.number().min(0).optional()})).nullish(),xA=D.z.strictObject({default_markup:Do.optional(),provider_markups:Il,model_markups:Fo}),ev=D.z.strictObject({schema:D.z.array(Os).optional(),markups:xA.optional()}),IA=D.z.strictObject({filters:D.z.array(D.z.strictObject({property:D.z.string(),operator:D.z.string(),value:D.z.array(D.z.string())})),aggregate:D.z.strictObject({type:D.z.string(),property:D.z.string().nullable()}),usage_type:bl}),vl=D.z.strictObject({schema:D.z.array(Os).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:D.z.boolean().optional(),usage_type:bl.default("single_use").overwrite(()=>"single_use"),default_markup:Do.optional(),provider_markups:Il}),_s=vl.safeExtend({schema:D.z.array(Os).length(0)}),No={id:yA,name:D.z.string().min(1),display:D.z.strictObject({singular:D.z.string().optional(),plural:D.z.string().optional()}).nullish(),event_names:D.z.array(D.z.string()).default([]),model_markups:Fo,stripe_meter:D.z.strictObject({id:D.z.string(),event_name:D.z.string()}).nullish(),stripe_product_id:D.z.string().nullish()},Cs=e=>D.z.discriminatedUnion("type",[D.z.strictObject({...No,...e,type:D.z.literal("boolean"),config:D.z.null()}),D.z.strictObject({...No,...e,type:D.z.literal("metered"),config:IA}),D.z.strictObject({...No,...e,type:D.z.literal("credit_system"),config:vl}),D.z.strictObject({...No,...e,type:D.z.literal("ai_credit_system"),config:_s})]),tv=Cs({}),vA=D.z.strictObject({id:D.z.boolean(),type:D.z.boolean(),usage_type:D.z.boolean()}),wA={internal_id:D.z.uuid(),org_id:D.z.uuid(),created_at:D.z.number(),env:D.z.enum(["sandbox","live"]),archived:D.z.boolean(),project_id:D.z.uuid(),environment_id:D.z.uuid(),revision:D.z.number().int().nonnegative(),update_rules:vA},wl=Cs(wA),nv=D.z.strictObject({rows:D.z.array(wl).max(200),nextCursor:D.z.uuid().nullable()}),rv=D.z.strictObject({features:D.z.array(wl).max(500),limited:D.z.boolean()}),iv=D.z.union([Cs({action:D.z.literal("save"),internal_id:D.z.uuid().nullable(),revision:D.z.number().int().nonnegative()}),D.z.strictObject({action:D.z.enum(["archive","restore","delete"]),internal_id:D.z.uuid(),revision:D.z.number().int().nonnegative()})]);var wr=require("zod");var it=require("zod"),Kt=it.z.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),ge=it.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Mo=it.z.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Ps=ge.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ol=it.z.string().min(1).max(64),Ir=it.z.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),_l=it.z.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),St=it.z.record(Ol,it.z.union([it.z.string().max(120),it.z.number().finite(),it.z.boolean()])).refine(e=>Object.keys(e).length<=16,"\u6700\u591A 16 \u4E2A\u8BA1\u4EF7\u5C5E\u6027").transform(e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t,String(n)]))),Cl=it.z.record(Ol,it.z.union([it.z.string().max(120),it.z.number().finite(),it.z.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Hr=e=>{let t=e.startsWith("-");t&&(e=e.slice(1));let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");let i=BigInt(n)*BigInt("1000000")+BigInt(r.padEnd(6,"0"));return t?-i:i},Pl=it.z.array(it.z.object({upTo:Ps.nullable(),cost:ge}).strict()).min(1).max(12).refine(e=>e.at(-1)?.upTo===null&&e.slice(0,-1).every((t,n)=>{let r=e[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&Hr(t.upTo)>Hr(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),OA=it.z.object({key:_l,match:Cl,priority:it.z.number().int().default(0),cost:ge.optional(),tiers:Pl.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),_A=it.z.object({key:_l,match:Cl,factor:Ps.optional(),add:Mo.optional()}).strict().refine(e=>e.factor!==void 0||e.add!==void 0,"A multiplier needs a factor or an add").transform(e=>({...e,factor:e.factor??"1",add:e.add??"0"})),CA=it.z.object({units:Ps.default("1"),cost:ge,tiers:Pl.optional(),dimensions:it.z.array(OA).max(12).optional(),multipliers:it.z.array(_A).max(4).optional()}).strict().superRefine((e,t)=>{let n=e.dimensions??[],r=e.multipliers??[];(new Set(n.map(o=>o.key)).size!==n.length||new Set(r.map(o=>o.key)).size!==r.length)&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u548C\u500D\u7387\u7684 ID \u4E0D\u80FD\u91CD\u590D"});for(let[o,s]of n.entries())for(let c of n.slice(o+1))Object.keys(s.match).length===Object.keys(c.match).length&&s.priority===c.priority&&!Object.keys(s.match).some(u=>c.match[u]!==void 0&&c.match[u]!==s.match[u])&&t.addIssue({code:"custom",message:"\u7EF4\u5EA6\u53EF\u80FD\u540C\u65F6\u5339\u914D\uFF0C\u8BF7\u8C03\u6574\u4F18\u5148\u7EA7"});let i=[e.cost,...(e.tiers??[]).map(o=>o.cost),...n.flatMap(o=>[...o.cost===void 0?[]:[o.cost],...(o.tiers??[]).map(s=>s.cost)])],a=Hr(e.units);for(let o of i)for(let s=0;s<1<<r.length;s++){let c=r.filter((p,g)=>s&1<<g);if(c.some((p,g)=>c.slice(g+1).some(f=>Object.keys(p.match).some(S=>f.match[S]!==void 0&&f.match[S]!==p.match[S]))))continue;let u=Hr(o),d=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Hr(g.factor??"1"),d*=BigInt("1000000"),m+=Hr(g.add??"0"));let w=(u+m*d)*BigInt("1000000"),I=d*a;(w<BigInt("0")||w%I!==BigInt("0")||w/I>BigInt("999999999999999999"))&&t.addIssue({code:"custom",message:"\u6BCF\u4E2A\u4E1A\u52A1\u5355\u4F4D\u7684\u6700\u7EC8\u5355\u4EF7\u5FC5\u987B\u975E\u8D1F\u3001\u5728\u8303\u56F4\u5185\u4E14\u80FD\u7CBE\u786E\u8868\u793A\u4E3A\u6700\u591A 6 \u4F4D\u5C0F\u6570"})}}),av=CA.safeExtend({featureKey:Ir});var vr=require("zod"),El=vr.z.number().int().min(0).max(1e8),ki=vr.z.strictObject({kind:vr.z.enum(["graduated","volume"]),tiers:vr.z.array(vr.z.strictObject({upTo:vr.z.number().int().min(1).max(1e4).nullable(),unitAmountMinor:El,flatAmountMinor:El.optional()})).min(1).max(12)}).refine(e=>e.tiers.at(-1)?.upTo===null&&e.tiers.slice(0,-1).every((t,n)=>{let r=e.tiers[n-1]?.upTo;return t.upTo!==null&&(n===0||r!=null&&t.upTo>r)}),"Tier ceilings must increase and end unbounded").refine(e=>!e.tiers.some(t=>(t.flatAmountMinor??0)>0)||e.kind==="volume"&&e.tiers.length>1,"Tier flat fees require volume pricing with multiple tiers");function Es(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?ki.parse(e.pricing):void 0;if(t===0)return 0;let r=0n,i=0;if(!n)r=BigInt(e.amountMinor)*BigInt(t);else for(let a of n.tiers){let o=a.upTo??1e4;if(n.kind==="volume"){if(t<=o){r=BigInt(t)*BigInt(a.unitAmountMinor)+BigInt(a.flatAmountMinor??0);break}}else t>i&&(r+=BigInt(Math.min(t,o)-i)*BigInt(a.unitAmountMinor));i=o}if(r>200000000n)throw new Error("Purchased price exceeds the payment amount limit");return Number(r)}function qo(e){return Es({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var PA=ge.refine(e=>/[1-9]/.test(e)),Vo=wr.z.strictObject({units:PA,prices:wr.z.array(wr.z.strictObject({currency:he,amountMinor:wr.z.number().int().min(0).max(1e8),pricing:ki.optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.currency)).size===e.length,"Currencies must be unique").refine(e=>e.every(t=>!t.pricing||t.amountMinor===0),"Tiered prices specify their rates in tiers"),minimumQuantity:wr.z.number().int().min(0).max(1e4),maximumQuantity:wr.z.number().int().min(0).max(1e4)}).refine(e=>e.maximumQuantity>=e.minimumQuantity,"Purchased quantity must fit its published bounds").refine(e=>{try{for(let t of e.prices)for(let n of[e.maximumQuantity,...t.pricing?.tiers.flatMap(r=>r.upTo===null?[]:[r.upTo,r.upTo+1])??[]])n<=e.maximumQuantity&&Es({amountMinor:t.amountMinor,...t.pricing===void 0?{}:{pricing:t.pricing}},n);return!0}catch{return!1}},"Every purchasable quantity must fit the payment amount limit");function Rl(e){if(!/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/.test(e))throw new Error("Invalid quantity");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"))}function kl(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Rl(e)+Rl(t)*BigInt(n);if(r>999999999999999999n)throw new Error("Purchased allowance exceeds the ledger quantity limit");let i=(r%1000000n).toString().padStart(6,"0").replace(/0+$/,"");return(r/1000000n).toString()+(i?"."+i:"")}var h=require("zod");var W=require("zod");var vt=require("zod");var j=require("zod");function jl(e){let t=2166136261,n=e.length;for(let r=0;r<n;r++)t^=e.charCodeAt(r),t+=(t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24);return t>>>0}function Bo(e,t,n){return n===2?jl(jl(e+t)+"")%1e4/1e4:null}function EA(e){return e<=0?[]:new Array(e).fill(1/e)}function Uo(e,t){return e>=t[0]&&e<t[1]}function Tl(e,t){for(let[n,r]of t.entries())if(Uo(e,r))return n;return-1}function Nl(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=EA(e);n=n||r,n.length!==e&&(n=r);let i=n.reduce((s,c)=>c+s,0);(i<.99||i>1.01)&&(n=r);let a=0,o=t;return n.map(s=>{let c=a;return a+=s,[c,c+o*s]})}function Dl(e,t,n){if(!t)return null;let r=t.split("?")[1];if(!r)return null;let a=r.replace(/#.*/,"").split("&").map(o=>o.split("=",2)).filter(([o])=>o===e).map(([,o])=>o===void 0?NaN:parseInt(o))[0];return a!==void 0&&a>=0&&a<n?a:null}function Fl(e){try{return e()}catch{return!1}}function ji(e){return typeof e=="string"?e:JSON.stringify(e)}function en(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function RA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function Ml(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=TA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function kA(e,t,n){try{let r=t.replace(/[*.+?^${}()|[\]\\]/g,"\\$&").replace(/_____/g,".*");return n&&(r="\\/?"+r.replace(/(^\/|\/$)/g,"")+"\\/?"),new RegExp("^"+r+"$","i").test(e)}catch{return!1}}function jA(e,t){try{let n=new URL(t.replace(/^([^:/?]*)\./i,"https://$1.").replace(/\*/g,"_____"),"https://_____"),r=[[e.host,n.host,!1],[e.pathname,n.pathname,!0]];return n.hash&&r.push([e.hash,n.hash,!1]),n.searchParams.forEach((i,a)=>{r.push([e.searchParams.get(a)||"",i,!1])}),!r.some(i=>!kA(i[0],i[1],i[2]))}catch{return!1}}function TA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=RA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return jA(r,n);return!1}catch{return!1}}function Rs(e){for(let n of["namespace","status","url","groups"])if(Object.hasOwn(e,n))throw new TypeError(`Retired experiment field: ${n}`);let t=e;if(t.hashVersion!==void 0&&t.hashVersion!==2)throw new TypeError("Only hash version 2 is supported");if(t.filters?.some(n=>n.hashVersion!==2))throw new TypeError("Only hash version 2 is supported")}function Lo(e){for(let t of Object.values(e)){if(Array.isArray(t))throw new TypeError("Saved groups require typed list or condition entries");if(t&&Object.hasOwn(t,"useEmptyListGroup"))throw new TypeError("Retired saved group field: useEmptyListGroup")}}function ql(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Lo(e.savedGroups??{})}var NA=e=>e/2**32|0,DA=e=>e>>>0;function Vl(e,t,n,r){let i=NA(n),a=DA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Bl(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var ks=e=>e?`"${e}" `:"";function FA(e,t=""){if(typeof e!="number")throw new TypeError(ks(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(ks(t)+"expected integer >= 0, got "+e);return e}function zo(e,t,n=""){if(Bl(e)&&(t===void 0||e.length===t))return e;t!==void 0&&FA(t,"length");let r=Bl(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=ks(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var MA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Ul=(e,t)=>{MA(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function js(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Ll(e,t){zo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Ts(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $o(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function hn(e,t){return e<<32-t|e>>>t}var qA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",VA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Qr(e){if(zo(e),qA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=VA[e[n]];return t}function BA(e,t,n="opts"){return Ul(e,"defaults"),t!==void 0&&Ul(t,n),Object.assign(Object.create(null),e,t)}function zl(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=BA({},t,"info");let n=(i,a)=>e(a).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var $l=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function Gl(e,t,n){return e&t^~e&n}function Kl(e,t,n){return e&t^e&n^t&n}var Go=class{constructor(t,n,r,i){Le(this,"blockLen");Le(this,"outputLen");Le(this,"canXOF",!1);Le(this,"padOffset");Le(this,"isLE");Le(this,"buffer");Le(this,"view");Le(this,"finished",!1);Le(this,"length",0);Le(this,"pos",0);Le(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=$o(this.buffer)}update(t){js(this),zo(t);let{view:n,buffer:r,blockLen:i}=this,a=t.length,o=!1;for(let s=0;s<a;){let c=Math.min(i-this.pos,a-s);if(c===i){let u=$o(t);for(;i<=a-s;s+=i)this.process(u,s);o=!0;continue}r.set(s===0&&c===a?t:t.subarray(s,s+c),this.pos),this.pos+=c,s+=c,this.pos===i&&(this.process(n,0),this.pos=0,o=!0)}return this.length+=t.length,o&&this.roundClean(),this}digestInto(t){js(this),Ll(t,this),this.finished=!0;let{buffer:n,view:r,blockLen:i,isLE:a}=this,{pos:o}=this;n[o++]=128,n.fill(0,o),this.padOffset>i-o&&(this.process(r,0),n.fill(0)),Vl(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:$o(t),c=this.outputLen,u=c/4,d=this.get();if(c%4||u>d.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,d[m],a)}digest(){let{buffer:t,outputLen:n}=this;this.digestInto(t);let r=t.slice(0,n);return this.destroy(),r}_cloneIntoMeta(t){let{buffer:n,length:r,finished:i,destroyed:a,pos:o}=this;return t.destroyed=a,t.finished=i,t.length=r,t.pos=o,o&&t.buffer.set(n),t}clone(){return this._cloneInto()}},Hl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var UA=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Hn=new Uint32Array(64),Ns=class extends Go{constructor(n,r){super(64,n,8,!1);Le(this,"A",0);Le(this,"B",0);Le(this,"C",0);Le(this,"D",0);Le(this,"E",0);Le(this,"F",0);Le(this,"G",0);Le(this,"H",0);this.A=r[0]|0,this.B=r[1]|0,this.C=r[2]|0,this.D=r[3]|0,this.E=r[4]|0,this.F=r[5]|0,this.G=r[6]|0,this.H=r[7]|0}get(){let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:u}=this;return[n,r,i,a,o,s,c,u]}set(n,r,i,a,o,s,c,u){this.A=n|0,this.B=r|0,this.C=i|0,this.D=a|0,this.E=o|0,this.F=s|0,this.G=c|0,this.H=u|0}_cloneInto(n){return(n||(n=new this.constructor)).set(...this.get()),this._cloneIntoMeta(n)}process(n,r){for(let w=0;w<16;w++,r+=4)Hn[w]=n.getUint32(r,!1);for(let w=16;w<64;w++){let I=Hn[w-15],p=Hn[w-2],g=hn(I,7)^hn(I,18)^I>>>3,f=hn(p,17)^hn(p,19)^p>>>10;Hn[w]=f+Hn[w-7]+g+Hn[w-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:d,H:m}=this;for(let w=0;w<64;w++){let I=hn(c,6)^hn(c,11)^hn(c,25),p=m+I+Gl(c,u,d)+UA[w]+Hn[w]|0,f=(hn(i,2)^hn(i,13)^hn(i,22))+Kl(i,a,o)|0;m=d,d=u,u=c,c=s+p|0,s=o,o=a,a=i,i=p+f|0}i=i+this.A|0,a=a+this.B|0,o=o+this.C|0,s=s+this.D|0,c=c+this.E|0,u=u+this.F|0,d=d+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,d,m)}roundClean(){Ts(Hn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ts(this.buffer)}},Ds=class extends Ns{constructor(){super(32,Hl)}};var Jr=zl(()=>new Ds,$l(1));var Ql=new Map,Fs=32,Jl=new WeakMap,Zl=new WeakMap;function LA(e){return Qr(Jr(new TextEncoder().encode(String(e))))}var Ho=e=>Array.isArray(e)?e.map(Ho):typeof e=="string"||typeof e=="number"?LA(e):null,Ko=e=>typeof e=="string"?e.toLowerCase():e;function td(e){let t=Jl.get(e);return t||(t=new Set(e),Jl.set(e,t)),t}function zA(e){let t=Zl.get(e);return t||(t=new Set(e.map(Ko)),Zl.set(e,t)),t}function Zr(e){Lo(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=Fs&&td(n)}return e}function Qt(e,t,n,r){n=n||{},r||Lo(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!ed(e,a,n,r))return!1;break;case"$nor":if(ed(e,a,n,r))return!1;break;case"$and":if(!QA(e,a,n,r))return!1;break;case"$not":if(Qt(e,a,n,r))return!1;break;case"$savedGroup":if(!$A(e,a,n,r))return!1;break;default:if(!Ti(a,nd(e,i),n,!1,r))return!1}return!0}function $A(e,t,n,r){if(!t||typeof t!="object"||Array.isArray(t))return!1;let{id:i,attributeKey:a}=t;if(typeof i!="string"||r.has(i)||a!==void 0&&typeof a!="string")return!1;let o=n[i];if(!o||Array.isArray(o)||typeof o!="object")return!1;let s=new Set(r).add(i);if(o.type==="list"||o.type==="hashed"){let c=a??o.attributeKey;if(typeof c!="string"||!Array.isArray(o.values))return!1;let u=nd(e,c);return Or(o.type==="hashed"?Ho(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:Qt(e,o.condition,n,s):!1}function nd(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return null;return r}function Wl(e,t=!1){let n=`${e}${t?"/i":""}`,r=Ql.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Ql.set(n,r)),r}function Ti(e,t,n,r=!1,i=new Set){if(typeof e=="string")return r?String(t).toLowerCase()===e.toLowerCase():t+""===e;if(typeof e=="number")return t*1===e;if(typeof e=="boolean")return t!==null&&!!t===e;if(e===null)return t===null;if(Array.isArray(e)||!rd(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!HA(o,t,a[o],n,i))return!1;return!0}function rd(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function GA(e){if(e===null)return"null";if(Array.isArray(e))return"array";let t=typeof e;return["string","number","boolean","object","undefined"].includes(t)?t:"unknown"}function KA(e,t,n,r){if(!Array.isArray(e))return!1;let i=rd(t)?a=>Ti(t,a,n,!1,r):a=>Qt(a,t,n,r);for(let a=0;a<e.length;a++)if((e[a]??null)!==null&&i(e[a]))return!0;return!1}function Or(e,t,n=!1){if(n){let i;if(t.length>=Fs){let a=zA(t);i=o=>{let s=Ko(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Ko(a)===Ko(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=Fs?(i=>a=>i.has(a))(td(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Yl(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Xl(e,t,n,r=!1,i=new Set){if(!Array.isArray(e))return!1;for(let a=0;a<t.length;a++){let o=!1;for(let s=0;s<e.length;s++)if(Ti(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function HA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return en(t)===en(n);case"$vne":return en(t)!==en(n);case"$vgt":return en(t)>en(n);case"$vgte":return en(t)>=en(n);case"$vlt":return en(t)<en(n);case"$vlte":return en(t)<=en(n);case"$eq":return t===n;case"$ne":return t!==n;case"$lt":return a<o;case"$lte":return a<=o;case"$gt":return a>o;case"$gte":return a>=o;case"$exists":return n?t!=null:t==null;case"$in":return Array.isArray(n)?Or(t,n):!1;case"$ini":return Array.isArray(n)?Or(t,n,!0):!1;case"$inGroup":{let s=r[n],c=Yl(s);return c===null?!1:Or(s?.type==="hashed"?Ho(t):t,c)}case"$notInGroup":{let s=r[n],c=Yl(s);return c===null?!1:!Or(s?.type==="hashed"?Ho(t):t,c)}case"$nin":return Array.isArray(n)?!Or(t,n):!1;case"$nini":return Array.isArray(n)?!Or(t,n,!0):!1;case"$not":return!Ti(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ti(n,t.length,r,!1,i):!1;case"$elemMatch":return KA(t,n,r,i);case"$all":return Array.isArray(n)?Xl(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?Xl(t,n,r,!0,i):!1;case"$regex":try{return Wl(n).test(t)}catch{return!1}case"$regexi":try{return Wl(n,!0).test(t)}catch{return!1}case"$type":return GA(t)===n;default:return!1}}function ed(e,t,n,r){if(!t.length)return!0;for(let i of t)if(Qt(e,i,n,r))return!0;return!1}function QA(e,t,n,r){for(let i of t)if(!Qt(e,i,n,r))return!1;return!0}function Ms(e){return ql(e),{context:e,stack:{evaluatedFeatures:new Set}}}function qs(e){return{...e.attributes,...e.attributeOverrides}}function Qn(e,t,n){let r=t||"id",i="",a=qs(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Je(e,t,n){e.context.log?.(t,n)}function Qo(e,t){return t=t||0,`${e}__${t}`}function Vs(e,t){return`${e}||${t}`}function JA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Qn(e,t),o=Vs(i,ji(a)),{hashAttribute:s,hashValue:c}=Qn(e,n),u=c?Vs(s,ji(c)):null,d={};return u&&r[u]&&Object.assign(d,r[u].assignments||{}),r[o]&&Object.assign(d,r[o].assignments||{}),d}function id({context:e,expKey:t,expBucketVersion:n,expHashAttribute:r,expFallbackAttribute:i,expMinBucketVersion:a,expMeta:o}){n=n||0,a=a||0,r=r||"id",o=o||[];let s=Qo(t,n),c=JA(e,r,i);if(a>0)for(let m=0;m<a;m++){let w=Qo(t,m);if(c[w]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let d=o.findIndex(m=>m.key===u);return d<0?{variation:-1}:{variation:d}}function od(e,t,n,r){let i=Vs(t,n),a=e.stickyBucketAssignmentDocs,o=a&&a[i]?a[i].assignments||{}:{},s={...o,...r},c=JSON.stringify(o)!==JSON.stringify(s);return{key:i,doc:{attributeName:t,attributeValue:n,assignments:s},changed:c}}function ad(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Jo(e,t){let n=Ms(t),r=cd(e,null,n);return t.onExperimentEval?.(e,r),r}function Fn(e,t){return Us(e,Ms(t))}function ZA(e){return e.forcedVariations||{}}function sd(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=dd(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Bs(()=>r.onExperimentViewed?.(t,n))}function WA(e,t,n){let{context:r}=e;if(r.trackedFeatureUsage){let i=JSON.stringify(n.value);if(r.trackedFeatureUsage[t]===i)return;r.trackedFeatureUsage[t]=i}Bs(()=>r.onFeatureUsage?.(t,n))}function Bs(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function Us(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Je(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Jn(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Rs(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Je(t,"Global override",{id:e,value:i.get(e)}),Jn(t,e,i.get(e),"override");if(!r)return Je(t,"Unknown feature",{id:e}),Jn(t,e,null,"unknownFeature");if(r.rules){let a=new Set(t.stack.evaluatedFeatures);e:for(let o of r.rules){if(o.parentConditions)for(let u of o.parentConditions){t.stack.evaluatedFeatures=new Set(a);let d=Us(u.id,t);if(d.source==="cyclicPrerequisite")return Jn(t,e,null,"cyclicPrerequisite");let m={value:d.value};if(!Qt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return Je(t,"Feature blocked by prerequisite",{id:e,rule:o}),Jn(t,e,null,"prerequisite");Je(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&ld(o.filters,t)){Je(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!ud(o.condition,t)){Je(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!YA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Je(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Je(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{sd(t,u.experiment,u.result)}),Jn(t,e,o.force,"force",o.id)}if(!o.variations){Je(t,"Skip invalid rule",{id:e,rule:o});continue}let s={variations:o.variations,key:o.key||e};"coverage"in o&&(s.coverage=o.coverage),o.weights&&(s.weights=o.weights),o.hashAttribute&&(s.hashAttribute=o.hashAttribute),o.fallbackAttribute&&(s.fallbackAttribute=o.fallbackAttribute),o.disableStickyBucketing&&(s.disableStickyBucketing=o.disableStickyBucketing),o.bucketVersion!==void 0&&(s.bucketVersion=o.bucketVersion),o.minBucketVersion!==void 0&&(s.minBucketVersion=o.minBucketVersion),o.meta&&(s.meta=o.meta),o.ranges&&(s.ranges=o.ranges),o.name&&(s.name=o.name),o.phase&&(s.phase=o.phase),o.seed&&(s.seed=o.seed),o.hashVersion&&(s.hashVersion=o.hashVersion),o.filters&&(s.filters=o.filters),o.condition&&(s.condition=o.condition);let c=cd(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Jn(t,e,c.value,"experiment",o.id,s,c)}}return Je(t,"Use default value",{id:e,value:r.defaultValue}),Jn(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function cd(e,t,n){let{context:r}=n;Rs(e);let i=e.key,a=e.variations.length;if(a<2)return Je(n,"Invalid experiment",{id:i}),Et(n,e,-1,!1,t);if(r.enabled===!1)return Je(n,"Context disabled",{id:i}),Et(n,e,-1,!1,t);if(e.urlPatterns&&!Ml(r.url||"",e.urlPatterns))return Je(n,"Skip because of url targeting",{id:i}),Et(n,e,-1,!1,t);let o=Dl(i,r.url||"",a);if(o!==null)return Je(n,"Force via querystring",{id:i,variation:o}),Et(n,e,o,!1,t);let c=ZA(r)[i];if(c!==void 0)return Je(n,"Force via dev tools",{id:i,variation:c}),Et(n,e,c,!1,t);if(e.active===!1)return Je(n,"Skip because inactive",{id:i}),Et(n,e,-1,!1,t);let{hashAttribute:u,hashValue:d}=Qn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!d)return Je(n,"Skip because missing hashAttribute",{id:i}),Et(n,e,-1,!1,t);let m=-1,w=!1,I=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:S}=id(ad({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));w=f>=0,m=f,I=!!S}if(!w){if(e.filters&&ld(e.filters,n))return Je(n,"Skip because of filters",{id:i}),Et(n,e,-1,!1,t);if(e.include&&!Fl(e.include))return Je(n,"Skip because of include function",{id:i}),Et(n,e,-1,!1,t);if(e.condition&&!ud(e.condition,n))return Je(n,"Skip because of condition exp",{id:i}),Et(n,e,-1,!1,t);if(e.parentConditions){let f=new Set(n.stack.evaluatedFeatures);for(let S of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let A=Us(S.id,n);if(A.source==="cyclicPrerequisite")return Et(n,e,-1,!1,t);let P={value:A.value};if(!Qt(P,S.condition||{},r.savedGroups||{}))return Je(n,"Skip because prerequisite evaluation fails",{id:i}),Et(n,e,-1,!1,t)}}}let p=Bo(e.seed||i,d,e.hashVersion??2);if(p===null)return Je(n,"Skip because of invalid hash version",{id:i}),Et(n,e,-1,!1,t);if(!w){let f=e.ranges||Nl(a,e.coverage===void 0?1:e.coverage,e.weights);m=Tl(p,f)}if(I)return Je(n,"Skip because sticky bucket version is blocked",{id:i}),Et(n,e,-1,!1,t,void 0,!0);if(m<0)return Je(n,"Skip because of coverage",{id:i}),Et(n,e,-1,!1,t);if("force"in e)return Je(n,"Force variation",{id:i,variation:e.force}),Et(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Je(n,"Skip because QA mode",{id:i}),Et(n,e,-1,!1,t);let g=Et(n,e,m,!0,t,p,w);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:S,doc:A}=od(r,u,ji(d),{[Qo(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[S]=A;let P=r.saveStickyBucketAssignmentDoc;Bs(()=>P(A))}}return sd(n,e,g),Je(n,"In experiment",{id:i,variation:g.variationId}),g}function Jn(e,t,n,r,i,a,o){let s={value:n,on:!!n,off:!n,source:r,ruleId:i||""};return a&&(s.experiment=a),o&&(s.experimentResult=o),r!=="override"&&WA(e,t,s),s}function ud(e,t){return Qt(qs(t.context),e,t.context.savedGroups||{})}function ld(e,t){return e.some(n=>{let{hashValue:r}=Qn(t.context,n.attribute);if(!r)return!0;let i=Bo(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>Uo(i,a))})}function YA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Qn(e.context,n,r);if(!s)return!1;let c=Bo(t,s,o??2);return c===null?!1:i?Uo(c,i):a!==void 0?c<=a:!0}function Et(e,t,n,r,i,a,o){let s=!0;(n<0||n>=t.variations.length)&&(n=0,s=!1);let{hashAttribute:c,hashValue:u}=Qn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),d=t.meta?.[n]??{},m=t.variations[0];for(let[I,p]of t.variations.entries())if(I===n){m=p;break}let w={key:d.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return d.name&&(w.name=d.name),a!==void 0&&(w.bucket=a),d.passthrough&&(w.passthrough=d.passthrough),w}function dd(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
2
2
  Copyright (c) 2025 GrowthBook, Inc.
3
3
 
4
4
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
@@ -14,4 +14,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14
14
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
15
15
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
16
16
  SOFTWARE.
17
- */var Ae=j.z.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),xt=j.z.record(j.z.string().min(1).max(128),Ae).superRefine((e,t)=>{(!Ae.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),YA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Ht=xt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!j.z.strictObject({id:j.z.uuid(),attributeKey:j.z.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!YA.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),XA=j.z.discriminatedUnion("type",[j.z.strictObject({type:j.z.literal("condition"),condition:Ht}),j.z.strictObject({type:j.z.literal("list"),attributeKey:j.z.string().min(1).max(128),values:j.z.array(j.z.union([j.z.string(),j.z.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Mn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var ey=j.z.record(j.z.uuid(),XA).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Mn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),zs=j.z.tuple([j.z.number().min(0).max(1),j.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),md=j.z.strictObject({attribute:j.z.string().optional(),seed:j.z.string().min(1),hashVersion:j.z.literal(2),ranges:j.z.array(zs).min(1).max(100)}),ty=j.z.strictObject({id:j.z.string().min(1).max(128),condition:Ht,gate:j.z.boolean().optional()}),Ls={id:j.z.string().max(128).optional(),condition:Ht.optional(),parentConditions:j.z.array(ty).max(50).optional(),filters:j.z.array(md).max(20).optional()},ny=j.z.union([j.z.strictObject({...Ls}),j.z.strictObject({...Ls,force:Ae,coverage:j.z.number().min(0).max(1).optional(),range:zs.optional(),seed:j.z.string().min(1).optional(),hashAttribute:j.z.string().optional(),hashVersion:j.z.literal(2).optional()}),j.z.strictObject({...Ls,type:j.z.literal("experiment-ref"),experimentId:j.z.uuid(),values:j.z.record(j.z.string().min(1),Ae),meta:j.z.record(j.z.string().min(1),j.z.strictObject({passthrough:j.z.boolean()})).optional()})]),ry=j.z.strictObject({defaultValue:Ae,rules:j.z.array(ny).max(100)}),Wv=j.z.record(j.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),ry).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),iy=j.z.strictObject({name:j.z.string().max(80),reason:j.z.string().max(500),dateStarted:j.z.iso.datetime({offset:!0}),dateEnded:j.z.iso.datetime({offset:!0}).nullable(),coverage:j.z.number().min(0).max(1),variationWeights:j.z.array(j.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Ht,savedGroups:j.z.array(j.z.strictObject({match:j.z.enum(["any","all","none"]),ids:j.z.array(j.z.uuid()).min(1)})).max(50),namespace:j.z.strictObject({id:j.z.uuid(),ranges:j.z.array(zs).min(1)}).nullable(),seed:j.z.string().min(1).max(128)}),oy=j.z.strictObject({key:j.z.string().min(1).max(128),name:j.z.string().min(1).max(80),hypothesis:j.z.string().max(2e3),status:j.z.enum(["draft","running","stopped"]),hashAttribute:j.z.string().min(1).max(128),fallbackAttribute:j.z.string().max(128).nullable(),hashVersion:j.z.literal(2),disableStickyBucketing:j.z.boolean(),bucketVersion:j.z.number().int().min(0).max(1e3),minBucketVersion:j.z.number().int().min(0).max(1e3),variations:j.z.array(j.z.strictObject({id:j.z.string().min(1),key:j.z.string().min(1),name:j.z.string().max(80),description:j.z.string().max(500)})).min(2).max(20),phases:j.z.array(iy).min(1).max(100),releasedVariationId:j.z.string().nullable(),excludeFromPayload:j.z.boolean(),statusSchedule:j.z.strictObject({startAt:j.z.iso.datetime({offset:!0}).nullable(),stopAt:j.z.iso.datetime({offset:!0}).nullable(),stopAfter:j.z.strictObject({value:j.z.number().int().positive().max(36500),unit:j.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var ay=oy.safeExtend({filters:j.z.array(md).optional()}),sy=j.z.strictObject({experiments:j.z.record(j.z.uuid(),ay),savedGroups:ey}),Ni=j.z.strictObject({attributeName:j.z.string(),attributeValue:j.z.string(),assignments:j.z.record(j.z.string(),j.z.string())}),Yv=j.z.strictObject({snapshot:sy,attributes:xt,results:xt,stickyBucketAssignmentDocs:j.z.record(j.z.string(),Ni)}),Xv=j.z.strictObject({variantKey:j.z.string().nullable(),bucketVersion:j.z.number().int().min(0),source:j.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:j.z.number().min(0).max(1).optional(),stickyBucketUsed:j.z.boolean().optional(),hashUsed:j.z.boolean().optional()});function Zn(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var cy=vt.z.enum(["active","inactive"]),uy=vt.z.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},xt),ly=vt.z.strictObject({id:vt.z.string().trim().min(1).max(255),name:vt.z.string().trim().min(1).max(255),status:cy,metadata:uy}),iw=ly.extend({internal_id:vt.z.uuid(),project_id:vt.z.uuid(),environment_id:vt.z.uuid(),created_at:vt.z.iso.datetime({offset:!0}),updated_at:vt.z.iso.datetime({offset:!0})}),gd=vt.z.union([vt.z.strictObject({id:vt.z.string().trim().min(1).max(255)}),vt.z.strictObject({internalId:vt.z.uuid()})]),ow=vt.z.enum(["customer","merchandise","context"]),aw=vt.z.enum(["system","stored","request"]),sw=vt.z.enum(["customer","merchandise","mixed"]),fd=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function $s(e,t={},n=new Set){if(Zn(e).some(fd))return!0;for(let r of Mn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&fd(i.attributeKey)||i?.type==="condition"&&$s(i.condition,t,n))return!0}return!1}var hd=require("zod"),dy=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,An=hd.z.string().max(16).regex(dy,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var mw=W.z.enum(["draft","active","paused","archived"]),Wn=W.z.discriminatedUnion("type",[W.z.object({type:W.z.literal("percent"),percentOff:W.z.number().min(1).max(100).multipleOf(.01)}).strict(),W.z.object({type:W.z.literal("amount"),amountOffCents:W.z.number().int().min(1).max(1e8),currency:he}).strict()]),tn=W.z.discriminatedUnion("type",[W.z.object({type:W.z.literal("once")}).strict(),W.z.object({type:W.z.literal("repeating"),months:W.z.number().int().min(1).max(36)}).strict(),W.z.object({type:W.z.literal("forever")}).strict()]),Ad=[W.z.object({type:W.z.literal("all")}).strict(),W.z.object({type:W.z.literal("plans"),planIds:W.z.array(W.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],py=W.z.discriminatedUnion("type",[...Ad,W.z.strictObject({type:W.z.literal("merchandise"),scope:W.z.discriminatedUnion("type",[W.z.strictObject({type:W.z.literal("all")}),W.z.strictObject({type:W.z.literal("selected"),merchandiseIds:W.z.array(W.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),W.z.strictObject({type:W.z.literal("condition"),condition:Ht})])})]),Gs=W.z.discriminatedUnion("type",[...Ad,W.z.strictObject({type:W.z.literal("merchandise"),scope:W.z.strictObject({type:W.z.enum(["all","selected","condition"])})})]),my=W.z.strictObject({firstPurchaseOnly:W.z.boolean(),condition:Ht}),fw=W.z.object({name:W.z.string().trim().min(1).max(80),description:W.z.string().max(500),discount:Wn,duration:tn,appliesTo:py,eligibility:my,selfClaimEnabled:W.z.boolean().default(!1),startsAt:W.z.iso.datetime().nullable(),endsAt:W.z.iso.datetime().nullable(),totalLimit:W.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:W.z.number().int().min(1).max(10),grantWindowHours:W.z.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=>!$s(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"]}),gw=W.z.object({code:W.z.string().trim().transform(e=>e.toUpperCase()).pipe(W.z.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:W.z.number().int().min(1).max(1e6).nullable(),expiresAt:W.z.iso.datetime().nullable(),firstPurchaseOnly:W.z.boolean(),minimumAmountCents:W.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:he.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Di=W.z.object({id:W.z.uuid(),couponId:W.z.uuid(),status:W.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:W.z.iso.datetime(),expiresAt:W.z.iso.datetime(),coupon:W.z.object({name:W.z.string(),discount:Wn,duration:tn,appliesTo:Gs}).strict()}).strict(),yd=W.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var vd=h.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Ks=h.z.string().regex(/^(0|[1-9]\d{0,14})$/),Wr=h.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),fy=h.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Fi=fy,qn=ge.refine(e=>/[1-9]/.test(e)),Bt=h.z.iso.datetime({offset:!0}),Zo=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"))},gy=h.z.array(h.z.object({upTo:qn.nullable(),unitAmountMinor:vd,flatAmountMinor:h.z.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&&Zo(t.upTo)>Zo(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),hy=h.z.discriminatedUnion("kind",[h.z.object({kind:h.z.literal("flat"),units:qn,unitAmountMinor:vd}).strict(),h.z.object({kind:h.z.enum(["graduated","volume"]),units:qn,tiers:gy}).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"),Ay=h.z.strictObject({interval:h.z.enum(["month","year"]),count:h.z.number().int().min(1).max(12),anchor:h.z.enum(["membership","calendar"])}),Mi=h.z.object({currency:he,pricing:hy,billingCycle:Ay.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var bd={requestId:h.z.uuid(),productVersionId:h.z.uuid(),internal_feature_id:h.z.uuid(),currency:he},wd=h.z.strictObject({interval:h.z.enum(["hour","day","week","month"]),intervalCount:h.z.number().int().min(1).max(12),limit:h.z.number().int().min(1).max(1e6)}),Od=h.z.discriminatedUnion("kind",[h.z.object({...bd,kind:h.z.literal("auto_topup"),threshold:Mo,quantity:qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:wd.optional()}).strict(),h.z.object({...bd,kind:h.z.literal("postpaid"),maxAmountMinorPerPeriod:Fi,maxOutstandingMinor:Fi}).strict()]),Sd={productVersionId:h.z.uuid(),internal_feature_id:h.z.uuid(),currency:he},_d=h.z.discriminatedUnion("kind",[h.z.object({...Sd,kind:h.z.literal("auto_topup"),threshold:Mo,quantity:qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:wd.optional(),purchaseAmountMinor:Fi,purchaseUnits:qn}).strict(),h.z.object({...Sd,kind:h.z.literal("postpaid"),maxAmountMinorPerPeriod:Fi,maxOutstandingMinor:Fi,cashPrice:Mi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Wo=h.z.object({id:h.z.uuid(),terms:_d,status:h.z.enum(["prepared","active","revoked","blocked"]),createdAt:Bt,acceptedAt:Bt.nullable(),effectiveAt:Bt.nullable(),revokedAt:Bt.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"),Cd=h.z.object({authorizationId:h.z.uuid(),terms:_d,setupUrl:h.z.url().nullable()}).strict(),Pd=h.z.object({authorizationId:h.z.uuid(),accepted:h.z.literal(!0)}).strict(),Ed=h.z.object({authorizationId:h.z.uuid(),requestId:h.z.uuid()}).strict(),Rd=h.z.object({internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable(),interval:h.z.enum(["day","week","month","year"]),anchor:h.z.enum(["billing_cycle","utc"]).optional(),basis:h.z.enum(["usage","credits"]),filter:St.optional(),limit:ge.nullable(),thresholds:h.z.array(h.z.number().positive().max(1)).max(8),includedThresholds:h.z.array(h.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:h.z.array(qn).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&&Zo(t)>Zo(i)}),"Notification thresholds must increase"),yy=Rd.safeExtend({requestId:h.z.uuid()}),xd={control:h.z.literal("overage"),requestId:h.z.uuid(),internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable()},by=h.z.discriminatedUnion("action",[h.z.strictObject({...xd,action:h.z.literal("set"),allowed:h.z.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.z.boolean()}),h.z.strictObject({...xd,action:h.z.literal("remove")})]),kd=h.z.union([yy,by]),Sy=h.z.strictObject({internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable(),allowed:h.z.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.z.boolean(),interval:h.z.enum(["day","week","month","year"]),startsAt:Bt,endsAt:Bt,used:h.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:h.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:h.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),xy=h.z.object({internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable(),interval:h.z.enum(["day","week","month","year"]),anchor:h.z.enum(["billing_cycle","utc"]).optional(),basis:h.z.enum(["usage","credits"]),filter:St.optional(),startsAt:Bt,endsAt:Bt,used:Kt,reserved:Kt,limit:ge.nullable(),thresholds:h.z.array(h.z.number().positive().max(1)).max(8),notifiedThresholds:h.z.array(h.z.number().positive().max(1)).max(1024),includedThresholds:h.z.array(h.z.number().positive().max(1)).max(8).optional(),includedAllowance:h.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:h.z.array(h.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:h.z.array(qn).max(8).optional(),notifiedAbsoluteThresholds:h.z.array(qn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||ge.safeParse(e.used).success&&ge.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Iy=h.z.object({authorizationId:h.z.uuid(),status:h.z.enum(["idle","pending","blocked"]),taskId:h.z.uuid().nullable(),invoiceId:h.z.uuid().nullable(),hostedInvoiceUrl:h.z.url().nullable(),purchaseCount:h.z.number().int().nonnegative(),purchaseWindowEndsAt:Bt.nullable(),attemptCount:h.z.number().int().nonnegative(),failedAttemptCount:h.z.number().int().nonnegative(),suspendedAt:Bt.nullable(),nextAttemptAt:Bt.nullable(),failureReason:h.z.string().min(1).max(240).nullable()}).strict(),jd=h.z.object({internal_feature_id:h.z.uuid().optional(),entityId:h.z.uuid().optional()}).strict(),Hs=h.z.object({authorizations:h.z.array(Wo).max(100),limits:h.z.array(Rd).max(100),overages:h.z.array(Sy).max(100).optional(),windows:h.z.array(xy).max(200),autoTopups:h.z.array(Iy).max(100),limited:h.z.boolean()}).strict(),vy=h.z.object({id:h.z.uuid(),internal_feature_id:h.z.uuid(),productVersionId:h.z.uuid(),authorizationId:h.z.uuid(),entityId:h.z.uuid().nullable(),units:ge,amountMinor:Wr,cashPrice:Mi}).strict(),qi=h.z.object({id:h.z.uuid(),sourceKind:h.z.enum(["product","usage","manual"]),providerInvoiceId:h.z.string().min(1).max(240).nullable(),status:h.z.enum(["accruing","open","pending","paid","failed","void"]),currency:he,startsAt:Bt.nullable(),endsAt:Bt.nullable(),amountMinor:h.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:h.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Ks,paidAmountMinor:Ks,refundedAmountMinor:Ks,createdAt:Bt,hostedInvoiceUrl:h.z.url().nullable(),adjustment:h.z.object({originalInvoiceId:h.z.uuid(),amountMinor:h.z.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:Bt.nullable(),reason:h.z.string().min(1).max(500).optional()}).strict().nullable(),lines:h.z.array(vy).max(100),linesLimited:h.z.boolean()}).strict(),Td=h.z.object({invoiceId:h.z.uuid(),accepted:h.z.literal(!0)}).strict(),Nd=h.z.strictObject({requestId:h.z.uuid(),originalInvoiceId:h.z.uuid(),amountMinor:h.z.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:h.z.string().trim().min(1).max(500)}),Dd=h.z.object({after:h.z.uuid().nullable(),limit:h.z.number().int().min(1).max(100)}).strict(),Fd=h.z.object({rows:h.z.array(qi).max(100),nextCursor:h.z.uuid().nullable()}).strict(),Id=h.z.strictObject({id:h.z.string(),coupon:h.z.string(),start:h.z.number().nonnegative(),end:h.z.number().nullable()}),wy=h.z.strictObject({subscriptionId:h.z.string(),customerId:h.z.string(),accountId:h.z.string(),sourceItems:h.z.array(h.z.strictObject({id:h.z.string(),price_id:h.z.string(),quantity:h.z.number().int(),discounts:h.z.array(Id).optional()})).max(100),items:h.z.array(h.z.strictObject({id:h.z.string(),price:h.z.string(),quantity:h.z.number().int(),discounts:h.z.array(h.z.strictObject({coupon:h.z.string().optional(),terms:h.z.strictObject({id:h.z.string(),name:h.z.string().optional(),percent_off:h.z.number().optional(),amount_off:h.z.number().optional(),currency:h.z.string().optional(),duration:h.z.enum(["once","forever","repeating"]),duration_in_months:h.z.number().optional()}).optional(),discount:h.z.string().optional(),receipt:Id.optional()})).max(20)})).max(100)}),Md=h.z.strictObject({membershipId:h.z.uuid(),requestId:h.z.uuid(),grantIds:h.z.array(h.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),qd=h.z.strictObject({membershipId:h.z.uuid(),operationId:h.z.uuid(),status:h.z.enum(["pending","effective"]),execution:wy.nullable(),grants:h.z.array(h.z.strictObject({id:h.z.uuid(),couponId:h.z.uuid(),name:h.z.string(),discount:Wn,duration:tn,startedAt:Bt.nullable()})).max(20)});var Yr=require("zod");var Vd=Yr.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Bd=Yr.z.number().int().min(1).max(1e3),Yo=Yr.z.object({cap:ge.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Yr.z.number().positive().max(1e4).nullable(),cycles:Yr.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var Vn=require("zod");var Ud=Vn.z.strictObject({itemKey:Vn.z.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:Vn.z.uuid(),includedAmount:Vn.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Vn.z.number().int().min(0).max(1e4),terms:Vo,pricing:ki.optional(),unitAmountMinor:Vn.z.number().int().min(0).max(1e8),productId:Vn.z.string().min(1).max(255).nullable(),priceId:Vn.z.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{jl(e.includedAmount,e.terms.units,e.quantity),qo({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"})}});var Y=require("zod");var _r=ge.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Vi=Y.z.string().min(1).max(120),Xo=Y.z.enum(["cap","overflow"]),nn=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Bi=e=>{try{return e()}catch{return!1}},Ui=Y.z.discriminatedUnion("operation",[Y.z.object({operation:Y.z.literal("quote"),overageBehavior:Xo.optional(),internal_feature_id:Y.z.uuid(),entityId:Y.z.uuid().optional(),quantity:_r,properties:St}).strict(),Y.z.object({operation:Y.z.literal("consume"),overageBehavior:Xo.optional(),occurredAt:Y.z.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.z.uuid(),entityId:Y.z.uuid().optional(),quantity:ge,properties:St,idempotencyKey:Vi}).strict(),Y.z.object({operation:Y.z.literal("reserve"),occurredAt:Y.z.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.z.uuid(),entityId:Y.z.uuid().optional(),quantity:_r,properties:St,idempotencyKey:Vi,expiresInSeconds:Y.z.number().int().min(1).max(86400)}).strict(),Y.z.object({operation:Y.z.literal("confirm"),operationId:Y.z.uuid(),quantity:_r,properties:St.optional(),idempotencyKey:Vi}).strict(),Y.z.object({operation:Y.z.literal("refund"),operationId:Y.z.uuid(),quantity:_r,idempotencyKey:Vi}).strict(),Y.z.object({operation:Y.z.literal("release"),operationId:Y.z.uuid(),idempotencyKey:Vi}).strict()]),Qs=Y.z.object({internal_credit_feature_id:Y.z.uuid().nullable(),internal_metered_feature_id:Y.z.uuid(),dimension:Y.z.string().min(1).max(64),counterKey:Y.z.string().min(1).max(240),cycleStart:Y.z.iso.datetime({offset:!0}),unitCost:ge,units:_r,amount:Kt,tier:Y.z.number().int().min(1).max(12).nullable()}).strict(),Cr=Y.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Ld(e,t){let n=e.reduce((r,i)=>r+nn(i.units,12),0n)-nn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var zd=Y.z.discriminatedUnion("funding",[Y.z.strictObject({funding:Y.z.literal("balance"),sourceId:Y.z.uuid(),rolloverId:Y.z.uuid().nullable(),units:Cr.refine(e=>/[1-9]/.test(e)),amount:Kt}),Y.z.strictObject({funding:Y.z.literal("unbilled"),units:Cr.refine(e=>/[1-9]/.test(e))}),Y.z.object({funding:Y.z.literal("prepaid"),sourceId:Y.z.uuid(),units:_r,amount:Kt,pricing:Y.z.array(Qs).min(1).max(12)}).strict().refine(e=>Bi(()=>e.pricing.reduce((t,n)=>t+nn(n.units,6),0n)===nn(e.units,6)&&e.pricing.reduce((t,n)=>t+nn(n.amount,12),0n)===nn(e.amount,12)&&e.pricing.every(t=>nn(t.unitCost,6)*nn(t.units,6)===nn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),Y.z.object({funding:Y.z.literal("postpaid"),invoiceLineId:Y.z.uuid().nullable(),units:_r,authorizationId:Y.z.uuid()}).strict()]),ea=Y.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),$d=Y.z.object({allowed:Y.z.boolean(),internal_feature_id:Y.z.uuid(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Xo.optional(),reason:ea.nullable(),allocations:Y.z.array(zd).max(500)}).strict().refine(e=>Bi(()=>e.allowed?e.reason===null&&Ld(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Bi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&nn(e.requestedQuantity,6)>=nn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Li=Y.z.object({id:Y.z.uuid(),internal_feature_id:Y.z.uuid(),kind:Y.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:Y.z.uuid().nullable(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Xo.optional(),accepted:Y.z.boolean(),reason:Y.z.enum([...ea.options,"expired"]).nullable(),createdAt:Y.z.iso.datetime({offset:!0}),reservationStatus:Y.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Y.z.iso.datetime({offset:!0}).nullable(),allocations:Y.z.array(zd).max(500)}).strict().refine(e=>Bi(()=>e.accepted?e.reason===null&&Ld(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Bi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&nn(e.requestedQuantity,6)>=nn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var Ee=require("zod");var Pr=Ee.z.iso.datetime({offset:!0}),Gd=ge.refine(e=>/[1-9]/.test(e)),Kd=Ee.z.strictObject({interval:Vd.exclude(["lifetime"]),count:Bd}),Oy=Ee.z.strictObject({action:Ee.z.literal("create"),requestId:Ee.z.uuid(),internal_feature_id:Ee.z.uuid(),entityId:Ee.z.uuid().nullable(),amount:Gd.nullable(),expiresAt:Pr.nullable(),reset:Kd.nullable(),rollover:Yo.nullable(),nextResetAt:Pr.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"),Hd=Ee.z.discriminatedUnion("action",[Oy,Ee.z.strictObject({action:Ee.z.literal("update"),requestId:Ee.z.uuid(),grantId:Ee.z.uuid(),revision:Ee.z.number().int().nonnegative(),amount:Gd.nullable(),expiresAt:Pr.nullable(),rollover:Yo.nullable(),nextResetAt:Pr.nullable()}),Ee.z.strictObject({action:Ee.z.enum(["add","subtract","set_remaining"]),requestId:Ee.z.uuid(),grantId:Ee.z.uuid(),revision:Ee.z.number().int().nonnegative(),amount:ge}),Ee.z.strictObject({action:Ee.z.literal("revoke"),requestId:Ee.z.uuid(),grantId:Ee.z.uuid(),revision:Ee.z.number().int().nonnegative()})]),Js=Ee.z.strictObject({id:Ee.z.uuid(),internal_feature_id:Ee.z.uuid(),entityId:Ee.z.uuid().nullable(),amount:ge.nullable(),reset:Kd.nullable(),rollover:Yo.nullable(),nextResetAt:Pr.nullable(),startsAt:Pr,expiresAt:Pr.nullable(),revision:Ee.z.number().int().nonnegative(),revoked:Ee.z.boolean(),available:Kt,held:Kt,spent:Kt}),Qd=Ee.z.strictObject({customerId:Ee.z.uuid(),after:Ee.z.uuid().nullable(),limit:Ee.z.number().int().min(1).max(100)}),Jd=Ee.z.strictObject({rows:Ee.z.array(Js).max(100),nextCursor:Ee.z.uuid().nullable()});var ne=require("zod");var _n=ne.z.iso.datetime({offset:!0}),Zd=ne.z.strictObject({invoiceId:ne.z.uuid(),after:ne.z.string().min(1).max(180).nullable(),limit:ne.z.number().int().min(1).max(100)}),_y=ne.z.strictObject({kind:ne.z.literal("product"),key:ne.z.string(),productVersionId:ne.z.uuid(),productName:ne.z.string(),itemKey:ne.z.string(),entityId:ne.z.uuid().nullable(),quantity:ne.z.number().positive(),subtotalMinor:ne.z.string().regex(/^-?\d+$/),discountMinor:ne.z.string().regex(/^\d+$/),taxMinor:ne.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ne.z.string().regex(/^-?\d+$/),startsAt:_n.nullable(),endsAt:_n.nullable(),providerLineId:ne.z.string().nullable(),providerItemId:ne.z.string()}),Wd=ne.z.strictObject({invoice:qi,items:ne.z.array(ne.z.discriminatedUnion("kind",[_y,ne.z.strictObject({kind:ne.z.literal("invoice_credit"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),units:ge,reserved:ge,amountMinor:Wr,grossAmountMinor:Wr,creditsAppliedMinor:Wr,properties:St,cashPrice:Mi,providerItemId:ne.z.string().nullable(),creditProviderItemId:ne.z.string().nullable()}),ne.z.strictObject({kind:ne.z.literal("usage"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),name:ne.z.string(),units:ge,reserved:ge,amountMinor:Wr,cashPrice:Mi})])).max(100),nextCursor:ne.z.string().min(1).max(180).nullable()}),Cy=ne.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Zs=ne.z.strictObject({from:_n,to:_n,entityId:ne.z.uuid().optional(),snapshotAt:_n.nullable(),after:ne.z.strictObject({at:_n,id:ne.z.uuid(),position:ne.z.number().int().nonnegative()}).nullable(),limit:ne.z.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"),Yd=ne.z.strictObject({customerId:ne.z.uuid(),entityId:ne.z.uuid().nullable(),from:_n,to:_n,snapshotAt:_n,totals:ne.z.array(ne.z.strictObject({internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),consumed:Kt,refunded:Kt,net:Cy})).max(1e3),rows:ne.z.array(ne.z.strictObject({operationId:ne.z.uuid(),position:ne.z.number().int().nonnegative(),kind:ne.z.enum(["consume","confirm","refund"]),originalId:ne.z.uuid().nullable(),occurredAt:_n,internal_feature_id:ne.z.uuid(),entitlementName:ne.z.string(),sourceId:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),creditName:ne.z.string(),units:Cr,amount:Kt,pricing:ne.z.array(Qs).max(12),properties:St})).max(100),nextCursor:Zs.shape.after});var T=require("zod");var ln=require("zod");var Py=ln.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Ey=ln.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ta=ln.z.strictObject({internal_feature_id:ln.z.uuid(),entityId:ln.z.uuid().nullable()}),Xd=ta.extend({quantity:ge,expectedRevision:ln.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:ln.z.string().min(1).max(120),properties:St.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),zi=ta.extend({operationId:ln.z.uuid().nullable(),usage:ge,capacity:Py.nullable(),remaining:Ey.nullable(),withinLimit:ln.z.boolean(),revision:ln.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ln.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Ut=T.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),yn=T.z.iso.datetime({offset:!0}),Ry=T.z.enum(["access","metered","credit"]),$i={internal_feature_id:T.z.uuid(),key:Ir,name:T.z.string().min(1).max(120),kind:Ry},ep=T.z.object({customerId:T.z.uuid(),snapshotAt:yn,memberships:T.z.array(T.z.object({id:T.z.uuid(),productId:T.z.string().min(1).max(255),productVersionId:T.z.uuid(),billingProductVersionId:T.z.uuid(),version:T.z.number().int().positive(),key:T.z.string().min(1).max(64),name:T.z.string().min(1).max(120),groupId:T.z.string().max(255).nullable(),membershipType:T.z.enum(["main","addon"]),status:T.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:T.z.boolean(),accessEnabled:T.z.boolean(),renewalChange:T.z.object({productVersionId:T.z.uuid(),name:T.z.string().min(1).max(120),version:T.z.number().int().positive(),effectiveAt:yn,benefitsAppliedAt:yn.nullable(),timing:T.z.enum(["immediate","renewal"]),changeKind:T.z.enum(["plan","seats","quantity"]),feature:T.z.strictObject({internal_feature_id:T.z.uuid(),name:T.z.string().min(1).max(80),fromQuantity:T.z.number().int().min(0).max(1e4),toQuantity:T.z.number().int().min(0).max(1e4)}).optional(),seat:T.z.object({key:T.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:T.z.number().int().min(0).max(1e4),toQuantity:T.z.number().int().min(0).max(1e4)}).strict().nullable(),status:T.z.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:T.z.object({phase:T.z.enum(["paid","trial"]),startsAt:yn,endsAt:yn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:T.z.boolean(),balances:T.z.array(T.z.object({...$i,usageType:T.z.enum(["consumable","non_consumable"]).nullable(),accessible:T.z.boolean(),unlimited:T.z.boolean(),available:Ut,held:Ut,debt:Ut,nextExpiresAt:yn.nullable(),usage:zi.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:T.z.boolean()}).strict(),tp=T.z.enum(["source","usage","transaction","invoice","debt","settlement"]),na=T.z.object({at:yn,id:T.z.uuid(),type:tp}).strict(),np=T.z.object({type:tp.nullable(),resourceKey:Ir.optional(),kind:T.z.enum(["purchase","refund"]).optional(),topup:T.z.boolean().optional(),from:T.z.iso.date().nullable(),to:T.z.iso.date().nullable(),after:na.nullable(),limit:T.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Xr={id:T.z.uuid(),occurredAt:yn},ky=T.z.discriminatedUnion("type",[T.z.strictObject({...Xr,type:T.z.literal("invoice"),status:T.z.string().min(1).max(80),paid:Ut,refunded:Ut,currency:he,externalId:T.z.string().nullable()}),T.z.object({...Xr,...$i,type:T.z.literal("source"),reason:T.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ut,unlimited:T.z.boolean(),status:T.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:yn,expiresAt:yn.nullable(),orderId:T.z.uuid().nullable(),parentSourceId:T.z.uuid().nullable()}).strict(),T.z.object({...Xr,type:T.z.literal("usage"),internal_feature_id:T.z.uuid(),name:T.z.string().min(1).max(120),kind:T.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:T.z.uuid().nullable(),quantity:ge,accepted:T.z.boolean(),reason:T.z.enum([...ea.options,"expired"]).nullable(),properties:St,reservationStatus:T.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:yn.nullable(),charges:T.z.array(T.z.discriminatedUnion("funding",[T.z.strictObject({funding:T.z.literal("balance"),sourceId:T.z.uuid(),rolloverId:T.z.uuid().nullable(),units:Cr,amount:Ut}),T.z.strictObject({funding:T.z.literal("unbilled"),units:Cr}),T.z.object({...$i,funding:T.z.literal("prepaid"),amount:Ut}).strict(),T.z.object({funding:T.z.literal("postpaid"),invoiceId:T.z.uuid(),invoiceLineId:T.z.uuid(),authorizationId:T.z.uuid(),units:ge,currency:he}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),T.z.object({...Xr,type:T.z.literal("transaction"),purpose:T.z.enum(["product","invoice"]),productVersionId:T.z.uuid().nullable(),productName:T.z.string().min(1).max(120).nullable(),productVersion:T.z.number().int().positive().nullable(),invoiceId:T.z.uuid().nullable(),orderId:T.z.uuid(),originalId:T.z.uuid().nullable(),kind:T.z.enum(["purchase","refund"]),amountMinor:T.z.number().int().nonnegative().max(2e8).nullable(),currency:he.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),T.z.object({...Xr,...$i,type:T.z.literal("debt"),sourceId:T.z.uuid(),transactionId:T.z.uuid(),amount:Ut}).strict(),T.z.object({...Xr,...$i,type:T.z.literal("settlement"),sourceId:T.z.uuid(),debtId:T.z.uuid(),kind:T.z.enum(["payment","usage_refund","payment_return"]),amount:Ut}).strict()]),rp=T.z.object({customerId:T.z.uuid(),rows:T.z.array(ky).max(50),nextCursor:na.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var le=require("zod"),op=le.z.object({customerId:le.z.uuid()}).strict(),ap=le.z.discriminatedUnion("action",[le.z.object({customerId:le.z.uuid(),requestId:le.z.uuid(),action:le.z.literal("assign"),poolId:le.z.uuid(),memberCustomerId:le.z.uuid()}).strict(),le.z.strictObject({customerId:le.z.uuid(),requestId:le.z.uuid(),action:le.z.literal("assign_entity"),poolId:le.z.uuid(),entityId:le.z.uuid()}),le.z.object({customerId:le.z.uuid(),requestId:le.z.uuid(),action:le.z.literal("release"),poolId:le.z.uuid(),slotId:le.z.uuid()}).strict()]),Gi=le.z.number().int().nonnegative(),Ws=le.z.iso.datetime({offset:!0}),Ys=le.z.strictObject({internalId:le.z.uuid(),id:le.z.string(),name:le.z.string().nullable(),version:le.z.number().int().positive()}),ip=le.z.enum(["active","past_due"]),Xs=le.z.strictObject({customerId:le.z.uuid(),licenses:le.z.array(le.z.strictObject({id:le.z.uuid(),linkId:le.z.uuid(),parent:le.z.strictObject({customerProductId:le.z.uuid(),status:ip,product:Ys}),product:Ys,planLicense:le.z.strictObject({id:le.z.uuid(),prepaidOnly:le.z.boolean(),isCustom:le.z.boolean()}).nullable(),granted:Gi,included:Gi,paidQuantity:Gi,usage:Gi,remaining:Gi,createdAt:Ws}).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:le.z.array(le.z.strictObject({id:le.z.uuid(),linkId:le.z.uuid(),status:ip,product:Ys,entity:le.z.strictObject({internalId:le.z.uuid(),id:le.z.string().nullable(),name:le.z.string().nullable()}).nullable(),beneficiary:le.z.strictObject({internalId:le.z.uuid(),id:le.z.string().nullable(),name:le.z.string().nullable()}).nullable(),startedAt:Ws.nullable(),endedAt:Ws.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:le.z.boolean()});var se=require("zod"),Ki=se.z.enum(["email","sms","voice","push"]),$w=se.z.enum(["resend","twilio","fcm","apns"]);var Gw=se.z.string().regex(/^\+[1-9]\d{1,14}$/),jy=se.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Ty=se.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Ny=se.z.strictObject({subject:Ty,html:se.z.string().min(1).max(131072).optional(),text:se.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),Dy=se.z.strictObject({body:se.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),Fy=se.z.strictObject({text:se.z.string().trim().min(1).max(4e3),language:se.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:se.z.number().int().min(1).max(900)}),My=se.z.record(se.z.string().min(1).max(64),se.z.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"),qy=se.z.strictObject({title:se.z.string().trim().min(1).max(200),body:se.z.string().trim().min(1).max(2e3),url:se.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:My.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),sp=se.z.discriminatedUnion("channel",[se.z.strictObject({channel:se.z.literal("email"),content:Ny}),se.z.strictObject({channel:se.z.literal("sms"),content:Dy}),se.z.strictObject({channel:se.z.literal("voice"),content:Fy}),se.z.strictObject({channel:se.z.literal("push"),content:qy})]),cp=se.z.strictObject({requestId:se.z.uuid(),customerId:se.z.uuid(),connectionId:se.z.uuid().optional(),message:sp,expiresAt:se.z.iso.datetime({offset:!0})}),Vy=se.z.array(se.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),By=se.z.discriminatedUnion("kind",[se.z.strictObject({kind:se.z.literal("all")}),se.z.strictObject({kind:se.z.literal("customers"),customerIds:Vy})]),Kw=se.z.strictObject({name:se.z.string().trim().min(1).max(120),connectionId:se.z.uuid().optional(),message:sp,audience:By,frequencyLimit:se.z.number().int().min(1).max(100)}),up=se.z.strictObject({requestId:se.z.uuid(),channel:Ki,state:se.z.enum(["allowed","denied"]),expectedRevision:se.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),lp=se.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),dp=se.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Hw=se.z.strictObject({meter:jy,estimatedUnits:se.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:se.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Se=require("zod");var te=require("zod");var Er=require("zod");var Hi=Er.z.strictObject({internalFeatureId:Er.z.uuid(),name:Er.z.string().min(1).max(120),includedAmount:Er.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Er.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:Er.z.number().int().min(1).max(100),terms:Vo});var tt=require("zod");var fp=require("zod");var Rr=require("zod"),pp=Rr.z.enum(["stripe","apple","google","merchant"]),mp=Rr.z.enum(["membership","credit_pack","lifetime"]),Ww=Rr.z.enum(["active","grace","suspended","inactive","revoked"]),Yw=Rr.z.strictObject({currency:Rr.z.string().regex(/^[A-Z]{3}$/),micros:Rr.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ei=fp.z.object({provider:pp,currency:he}).strict();var Yn=tt.z.strictObject({internal_feature_id:tt.z.uuid(),quantity:ge.refine(e=>/[1-9]/.test(e)),properties:St,entityId:tt.z.uuid().optional()}),gp=tt.z.strictObject({requirement:Yn,commerce:ei.optional(),paywallId:tt.z.uuid().optional()}),Uy=tt.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),ec=tt.z.strictObject({productId:tt.z.string().min(1),productVersionId:tt.z.string().min(1),name:tt.z.string().min(1).max(120),action:tt.z.enum(["purchase","upgrade","addon","topup"]),membershipId:tt.z.string().min(1).nullable(),currency:he,amountMinor:tt.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:tt.z.enum(["free","week","month","year","one_time"]),intervalCount:tt.z.number().int().min(1).max(156)}),kr=tt.z.strictObject({internal_feature_id:tt.z.string().min(1),name:tt.z.string().min(1).max(120),kind:tt.z.enum(["access","metered","credit"]),quantity:ge,allowed:tt.z.boolean(),reason:Uy.nullable(),preview:tt.z.strictObject({scenario:tt.z.enum(["feature_flag","usage_limit"]),candidates:tt.z.array(ec).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),aO=tt.z.strictObject({paywallId:tt.z.uuid(),requirement:Yn});var ia=te.z.object({plan:te.z.string().min(1).max(200).optional(),coupon:te.z.uuid().optional(),promotionCode:te.z.uuid().optional(),picker:te.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ra=te.z.object({text:te.z.string().optional(),label:te.z.string().optional(),alt:te.z.string().optional(),html:te.z.string().max(32768).optional(),price:te.z.object({current:te.z.string(),original:te.z.string().nullable(),period:te.z.string()}).optional(),code:te.z.string().optional(),countdownAt:te.z.iso.datetime().optional(),planId:te.z.string().min(1).max(200).optional(),planVersionId:te.z.string().min(1).max(200).optional(),currency:he.optional(),couponId:te.z.uuid().optional(),offerId:te.z.uuid().optional(),unavailable:te.z.boolean().optional(),unavailableReason:te.z.string().optional(),missing:te.z.array(te.z.string()).optional()}).strict(),ti=te.z.object({paywall:kr.optional(),nodes:te.z.record(te.z.string(),te.z.object({base:ra,picker:te.z.string().optional(),byPlan:te.z.record(te.z.string(),ra).optional()}).strict()),plans:te.z.record(te.z.string(),te.z.object({id:te.z.string().min(1).max(200),versionId:te.z.string().min(1).max(200),available:te.z.boolean(),name:te.z.string(),price:te.z.string(),period:te.z.string(),currency:he.optional(),amountMinor:te.z.number().int().nonnegative().optional(),interval:te.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:te.z.number().int().positive().optional(),prepaid:te.z.array(Hi).max(100).optional()}).strict()),pickers:te.z.record(te.z.string(),te.z.object({options:te.z.array(te.z.string().min(1).max(200)).max(20),selected:te.z.string().min(1).max(200).nullable()}).strict()),quantities:te.z.record(te.z.string(),te.z.strictObject({minimum:te.z.number().int().nonnegative(),maximum:te.z.number().int().nonnegative(),step:te.z.number().int().positive(),value:te.z.number().int().nonnegative(),label:te.z.string(),available:te.z.boolean()})).optional(),diagnostics:te.z.array(te.z.object({nodeId:te.z.string(),message:te.z.string()}).strict())}).strict();function hp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var b=require("zod");function Ly(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Ap(e){let t={};function n(r){var i;if(Ly(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}var Cn=require("zod"),yp=Cn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),oa=Cn.z.strictObject({tiers:Cn.z.array(Cn.z.strictObject({id:yp,name:Cn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Cn.z.array(Cn.z.strictObject({productVersionId:Cn.z.string().min(1).max(200),tierId:yp,period:Cn.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function aa(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var oe=require("zod");var zy=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],bp=oe.z.enum(zy),Sp=oe.z.object({source:bp,layout:oe.z.enum(["full","compact"]),resourceKey:Ir.optional(),pageSize:oe.z.number().int().min(1).max(50),showSources:oe.z.boolean(),allowPurchase:oe.z.boolean(),outputs:oe.z.object({billing_adjustment:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),wt=oe.z.string().max(2e3),xp=oe.z.object({id:oe.z.string().max(100),label:wt,detail:oe.z.array(wt).max(12),value:wt.optional(),status:wt.optional(),facts:oe.z.array(oe.z.object({label:wt,value:wt}).strict()).max(1e3),purchaseId:oe.z.uuid().optional(),invoiceUrl:oe.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:oe.z.array(oe.z.strictObject({action:oe.z.literal("invoice_open"),label:wt})).max(1).optional(),membershipActions:oe.z.array(oe.z.object({value:oe.z.string().max(100),label:wt}).strict()).max(3).optional()}).strict(),$y=oe.z.object({key:Ir,name:wt,spendable:wt,reserved:wt,available:wt,expiry:wt.nullable(),sources:oe.z.array(xp).max(50),sourceCount:oe.z.number().int().nonnegative(),sourcePage:oe.z.number().int().positive(),hasNextSources:oe.z.boolean(),hasPreviousSources:oe.z.boolean()}).strict(),Gy=oe.z.object({source:bp,status:oe.z.enum(["idle","loading","ready","error"]),stale:oe.z.boolean(),preview:oe.z.boolean(),errorCode:oe.z.string().max(80).optional(),errorMessage:wt.optional(),resources:oe.z.array($y).max(500),rows:oe.z.array(xp).max(50),hasNext:oe.z.boolean(),hasPrevious:oe.z.boolean(),page:oe.z.number().int().positive(),filter:oe.z.string().max(40),updatedAt:oe.z.iso.datetime().optional(),buyingId:oe.z.uuid().optional(),membershipBusy:oe.z.boolean().optional(),billingBusy:oe.z.boolean().optional(),membershipReview:oe.z.object({title:wt,note:wt,facts:oe.z.array(oe.z.object({label:wt,value:wt}).strict()).max(100)}).strict().optional(),membershipResult:wt.optional()}).strict(),Ip=oe.z.object({nodes:oe.z.record(oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Gy)}).strict(),gO=oe.z.object({nodeId:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:oe.z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:oe.z.string().max(100).optional()}).strict();var Hy=4,Sn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Ji=b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Te=b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Qy=b.z.enum(["none","xs","sm","md","lg","xl"]),Jy=b.z.enum(["none","sm","md","lg","full"]),tc=b.z.string().regex(/^#[0-9a-fA-F]{6}$/),Op=b.z.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),nc=b.z.union([Op,b.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),b.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),b.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),vp=b.z.object({primary:tc,background:tc,text:tc,radius:Jy,font:b.z.enum(["system","serif","rounded","mono"])}).strict(),Zi=b.z.union([b.z.enum(["primary","text","muted","background","surface"]),b.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),je=(e,t)=>b.z.number().int().min(e).max(t),wp=b.z.union([b.z.enum(["fit","fill"]),je(1,1200)]),Zy=b.z.object({top:je(0,200),right:je(0,200),bottom:je(0,200),left:je(0,200)}).strict(),Wy=b.z.object({top:je(-100,200),right:je(-100,200),bottom:je(-100,200),left:je(-100,200)}).strict(),_p=b.z.object({x:je(0,100),y:je(0,100)}).strict(),Yy=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("color"),color:Zi}).strict(),b.z.object({type:b.z.literal("linear"),angle:je(0,360),stops:b.z.array(b.z.object({color:Zi,at:je(0,100)}).strict()).min(2).max(4)}).strict(),b.z.object({type:b.z.literal("image"),src:nc,fit:b.z.enum(["cover","contain"]),position:_p.optional()}).strict()]),Xy=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("rect"),radius:b.z.union([je(0,200),b.z.object({topLeft:je(0,200),topRight:je(0,200),bottomRight:je(0,200),bottomLeft:je(0,200)}).strict()])}).strict(),b.z.object({type:b.z.literal("pill")}).strict()]),eb=b.z.object({width:je(0,12),color:Zi,style:b.z.enum(["solid","dashed"])}).strict(),tb=b.z.object({x:je(-40,40),y:je(-40,40),blur:je(0,80),spread:je(-20,40),color:Zi}).strict(),nb=b.z.object({font:b.z.enum(["system","serif","rounded","mono"]),size:je(8,96),weight:b.z.number().int().min(100).max(900).multipleOf(100),lineHeight:b.z.number().min(.8).max(3),letterSpacing:b.z.number().min(-5).max(20),color:Zi,align:b.z.enum(["start","center","end"]),italic:b.z.boolean(),decoration:b.z.enum(["none","underline","line-through"]),transform:b.z.enum(["none","uppercase"])}).strict().partial(),jr=b.z.object({width:wp,height:wp,padding:Zy,margin:Wy,gap:je(0,120),grow:b.z.union([b.z.boolean(),b.z.number().min(0).max(12)]),background:Yy,opacity:b.z.number().min(0).max(1),clipContent:b.z.boolean(),shape:Xy,border:eb,shadow:tb,text:nb}).strict().partial(),Jt={id:Ji,name:b.z.string().trim().min(1).max(60).optional(),hidden:b.z.boolean().optional(),style:jr.optional(),fallback:Te.optional()},rb=b.z.object({...Jt,type:b.z.literal("text"),productField:b.z.enum(["name","price","trial","period"]).optional(),feature:b.z.object({id:b.z.uuid(),field:b.z.enum(["name","allowance"])}).strict().optional(),text:Te,variant:b.z.enum(["title","heading","body","caption"])}).strict(),ib=b.z.object({...Jt,type:b.z.literal("image"),src:nc,localizedSrc:b.z.record(An,nc).optional(),alt:Te,aspect:b.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:b.z.enum(["cover","contain"]),position:_p.optional()}).strict(),ob=b.z.object({...Jt,type:b.z.literal("button"),label:Te,variant:b.z.enum(["primary","secondary","link"]),action:Te,purpose:b.z.enum(["purchase","navigation","close"]).optional(),bind:ia.optional()}).strict(),ab=b.z.object({...Jt,type:b.z.literal("divider")}).strict(),sb=b.z.object({...Jt,type:b.z.literal("customer_data"),title:Te,data:Sp}).strict(),cb=b.z.object({...Jt,type:b.z.literal("spacer"),size:Qy}).strict(),ub=b.z.object({...Jt,type:b.z.literal("custom_html"),html:b.z.record(An,b.z.string().max(Sn.customHtml)),css:b.z.string().max(Sn.customCss)}).strict(),lb=b.z.object({...Jt,type:b.z.literal("price"),fallback:Te,parts:b.z.object({current:jr.optional(),original:jr.optional(),period:jr.optional()}).strict().optional()}).strict(),db=b.z.object({...Jt,type:b.z.literal("coupon_code"),label:Te,fallback:Te}).strict(),pb=b.z.object({...Jt,type:b.z.literal("countdown"),source:b.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:b.z.iso.datetime().optional(),granularity:b.z.enum(["day","hour","minute","second"]),expired:Te,fallback:Te}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),mb=b.z.object({...Jt,type:b.z.literal("plan_picker"),label:Te,fallback:Te,planIds:b.z.array(b.z.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:b.z.string().min(1).max(200).optional(),grouping:oa.safeExtend({monthLabel:Te,yearLabel:Te,unavailableLabel:Te}).optional(),states:b.z.object({selected:jr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!aa(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),fb=b.z.object({...Jt,type:b.z.literal("quantity_picker"),bind:ia.optional(),label:Te,fallback:Te,internalFeatureId:b.z.uuid(),minimumQuantity:je(0,1e4),maximumQuantity:je(0,1e4),defaultQuantity:je(0,1e4),step:je(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),gb=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("input"),label:Te,keyboard:b.z.enum(["text","email","tel","url"]),maxLength:je(1,500)}).strict(),b.z.object({type:b.z.literal("multiselect"),label:Te,min:je(0,50),max:je(1,50)}).strict(),b.z.object({type:b.z.literal("select"),label:Te,defaultIndex:je(0,49),purpose:b.z.enum(["option","product","tier"]).optional(),pickerId:Ji.optional(),selectedStyle:jr.optional()}).strict(),b.z.object({type:b.z.literal("tabs"),label:Te,defaultIndex:je(0,49),purpose:b.z.literal("tier").optional()}).strict(),b.z.object({type:b.z.literal("toggle"),label:Te,defaultEnabled:b.z.boolean()}).strict(),b.z.object({type:b.z.literal("carousel"),label:Te}).strict()]),bn={...Jt,type:b.z.literal("stack"),direction:b.z.enum(["vertical","horizontal","overlay"]),align:b.z.enum(["start","center","end","stretch"]),justify:b.z.enum(["start","center","end","between"]),productSlot:b.z.object({index:je(0,19),period:b.z.enum(["month","year"]).optional(),requireBinding:b.z.boolean().optional()}).strict().optional(),interaction:gb.optional(),states:b.z.object({selected:jr.optional()}).strict().optional(),purpose:b.z.literal("benefits").optional(),purchaseAction:Te.optional(),buttonVariant:b.z.enum(["primary","secondary","link"]).optional(),bind:ia.optional()},Cp=b.z.lazy(()=>b.z.object({...Jt,type:bn.type,direction:bn.direction,align:bn.align,justify:bn.justify,children:b.z.array(hb).max(Sn.children),productSlot:bn.productSlot,interaction:bn.interaction,states:bn.states,purpose:bn.purpose,purchaseAction:bn.purchaseAction,buttonVariant:bn.buttonVariant,bind:bn.bind}).strict()),hb=b.z.lazy(()=>b.z.union([Cp,rb,ib,ob,ab,cb,ub,lb,db,pb,mb,fb,sb])),Ab=b.z.union([b.z.string().max(500),b.z.number().finite(),b.z.boolean(),b.z.null()]),Qi={id:Te,event:Te,properties:b.z.record(Te,Ab).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},yb=b.z.discriminatedUnion("type",[b.z.object({...Qi,type:b.z.literal("navigate"),close:b.z.literal(!1),pageId:Ji}).strict(),b.z.object({...Qi,type:b.z.literal("event"),close:b.z.boolean()}).strict(),b.z.object({...Qi,type:b.z.literal("close"),close:b.z.literal(!0)}).strict(),b.z.object({...Qi,type:b.z.literal("open_url"),close:b.z.boolean(),url:Op}).strict(),b.z.object({...Qi,type:b.z.literal("claim_offer"),close:b.z.boolean(),couponId:b.z.uuid()}).strict()]),bb=b.z.object({defaultLocale:An,locales:b.z.record(An,b.z.record(Te,b.z.string().max(Sn.stringLength)))}).strict(),Sb=b.z.enum(["popup","paywall","onboarding","page","banner"]);var xb=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("modal"),size:b.z.enum(["sm","md","lg"])}).strict(),b.z.object({type:b.z.literal("sheet"),size:b.z.enum(["sm","md","lg"])}).strict(),b.z.object({type:b.z.literal("fullscreen")}).strict(),b.z.object({type:b.z.literal("inline")}).strict()]);var Ib=b.z.object({kind:b.z.literal("screen"),schemaVersion:b.z.literal(Hy),name:b.z.string().trim().min(1).max(80),surface:Sb,initialPageId:Ji.optional(),presentation:xb,theme:vp,pages:b.z.array(b.z.object({id:Ji,name:b.z.string().trim().min(1).max(60),root:Cp,theme:vp.optional(),editorPosition:b.z.object({x:b.z.number().finite().min(-1e5).max(1e5),y:b.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Sn.pages),strings:bb,actions:b.z.array(yb).max(Sn.actions)}).strict();function Lt(e,t){for(let n of e.pages)Xn(n.root,t)}var rn=Ib.superRefine((e,t)=>{let n=Sn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>Sn.locales&&r(`\u6700\u591A ${Sn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let d of e.actions)a.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let o=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),o.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let s=new Set,c=0,u=!1;Lt(e,(d,m)=>{if(c++,m>Sn.depth&&(u=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!a.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let w of Object.keys(d.html))i.includes(w)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`);if(d.type==="image")for(let w of Object.keys(d.localizedSrc??{}))i.includes(w)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${Sn.depth} \u5C42`)});function Xn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Xn(i,t,n+1,e)}function sa(e){let t=[],n=new Set;return Lt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function vb(e,t,n){if(t.field==="html"){let r;return Lt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Wi(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function er(e){let t=sa(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!vb(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function wb(e,t){let n=null;return Xn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Wi(e,t){for(let n of e.pages){let r=wb(n.root,t);if(r)return r}return null}var Rt=require("zod"),ft=Rt.z.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"),rc=Rt.z.strictObject({type:Rt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Rt.z.boolean(),enum:Rt.z.array(Rt.z.string().max(255)).min(1).max(100).optional()}),ni=rc.extend({type:Rt.z.enum([...rc.shape.type.options,"array"]),items:rc.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"})}),ri=ni.safeExtend({source:Rt.z.discriminatedUnion("type",[Rt.z.strictObject({type:Rt.z.literal("input")}),Rt.z.strictObject({type:Rt.z.literal("node")}),Rt.z.strictObject({type:Rt.z.enum(["parameter","attribute"]),key:ft})])}),wO=Rt.z.record(ft,ri),ic=Rt.z.record(ft,ft).refine(e=>Object.keys(e).length<=20);function dn(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=>dn(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&&Rt.z.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 oc(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&&oc(e.items,t.items)}function ca(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let d of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,d)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(d)||Number(d)>=u.length)){c=!1;break}u=u[d]}}if(!(!c||u===void 0)){if(!dn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function ii(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 Pp(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"||!dn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var tr=require("zod");var xn=tr.z.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"),Pn=tr.z.discriminatedUnion("source",[tr.z.strictObject({source:tr.z.literal("literal"),value:Ae}),tr.z.strictObject({source:tr.z.literal("variable"),key:tr.z.string().min(1).max(255),path:xn.optional()})]);function Ep(e,t){if(!t)return e;for(let n of xn.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 ac(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ca(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Ae.parse(Ep(n[e.key],e.path)))}function sc(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&&!xn.safeParse(r).success?null:{key:n,path:r}}function cc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Lt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(hp))]}function ua(e){return cc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function on(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),d=c.replace(/^-/,""),m=d.replace(".","").length,w=(d.includes(".")?d.indexOf("."):m)+Number(u),I=w<=0?2-w+m:w>=m?w:m+1;n+=I+(c.startsWith("-")?1:0)-s.length}}return n}var nr=Se.z.enum(["page","popup","banner"]),Ob=3e5,Rp=Se.z.strictObject({type:Se.z.enum(["string","number","boolean","strings","json"]),nullable:Se.z.boolean()}),_b=Se.z.strictObject({inputs:Se.z.record(Te,Rp.extend({required:Se.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Se.z.record(Te,Rp).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Cb=Se.z.strictObject({kind:nr,schemaVersion:Se.z.literal(1),name:Se.z.string().trim().min(1).max(80),screen:rn,contract:_b}),la=Cb.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"]),on(e)>Ob&&n("Content document exceeds its byte budget",[])});function Pb(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 Eb=la.superRefine((e,t)=>{for(let n of ua(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&&!Pb(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}er(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),kp=Se.z.strictObject({id:Se.z.uuid(),kind:nr,projectId:Se.z.uuid(),environmentId:Se.z.uuid(),name:Se.z.string(),revision:Se.z.number().int().nonnegative(),status:Se.z.enum(["draft","published","archived"]),publishedVersionId:Se.z.uuid().nullable(),createdAt:Se.z.iso.datetime({offset:!0}),updatedAt:Se.z.iso.datetime({offset:!0})}),MO=kp.extend({draft:la}),qO=Se.z.strictObject({rows:Se.z.array(kp).max(200),nextCursor:Se.z.uuid().nullable()}),uc=Se.z.strictObject({id:Se.z.uuid(),kind:nr,resourceId:Se.z.uuid(),projectId:Se.z.uuid(),environmentId:Se.z.uuid(),version:Se.z.number().int().positive(),sourceRevision:Se.z.number().int().nonnegative(),document:Eb,createdAt:Se.z.iso.datetime({offset:!0})}),VO=uc.omit({document:!0}),BO=Se.z.discriminatedUnion("action",[Se.z.strictObject({action:Se.z.literal("create"),kind:nr,id:Se.z.uuid(),document:la}),Se.z.strictObject({action:Se.z.literal("save"),kind:nr,id:Se.z.uuid(),revision:Se.z.number().int().nonnegative(),document:la}),Se.z.strictObject({action:Se.z.enum(["publish","archive"]),kind:nr,id:Se.z.uuid(),revision:Se.z.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"})});var lc=require("zod"),oi={funnelId:lc.z.uuid().optional(),funnelVersionId:lc.z.uuid().optional()};var et=require("zod");var De=require("zod");var Ze=require("zod"),zO=Ze.z.discriminatedUnion("action",[Ze.z.strictObject({action:Ze.z.literal("create"),couponId:Ze.z.uuid(),productBindingId:Ze.z.uuid(),storeOfferId:Ze.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ze.z.enum(["introductory","promotional"])}),Ze.z.strictObject({action:Ze.z.literal("set_enabled"),id:Ze.z.uuid(),revision:Ze.z.number().int().nonnegative(),enabled:Ze.z.boolean()})]),$O=Ze.z.array(Ze.z.strictObject({id:Ze.z.uuid(),couponId:Ze.z.uuid(),productBindingId:Ze.z.uuid(),storeOfferId:Ze.z.string().min(1).max(255).nullable(),storeOfferType:Ze.z.enum(["introductory","promotional"]),enabled:Ze.z.boolean(),revision:Ze.z.number().int().nonnegative()})).max(500),ai=Ze.z.strictObject({offerKind:Ze.z.enum(["none","introductory","promotional"]),offerId:Ze.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ze.z.number().int().min(0).max(1e8),trialDays:Ze.z.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"})}),GO=Ze.z.record(Ze.z.uuid(),ai).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var dc=De.z.object({type:De.z.literal("native_purchase"),receiptId:De.z.uuid(),orderId:De.z.uuid(),productVersionId:De.z.uuid(),provider:De.z.enum(["apple","google"]),productId:De.z.string().min(1).max(255),productKind:mp,replacement:De.z.strictObject({sourceOrderId:De.z.uuid(),sourceProductId:De.z.string().min(1).max(255),policy:De.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:De.z.array(De.z.uuid()).max(50)}).nullable(),appAccountToken:De.z.uuid().optional(),obfuscatedAccountId:De.z.string().min(1).max(64).optional(),obfuscatedProfileId:De.z.uuid().optional(),basePlanId:De.z.string().min(1).max(255).optional(),offerId:De.z.string().min(1).max(255).optional(),offerKind:De.z.enum(["none","introductory","promotional"]),currency:he,catalogAmountMinor:De.z.number().int().nonnegative().max(1e8),discountMinor:De.z.number().int().nonnegative().max(1e8),trialDays:De.z.number().int().min(1).max(730).nullable(),seatBundle:De.z.array(De.z.strictObject({key:De.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:De.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:De.z.strictObject({offerId:De.z.string().min(1).max(255),keyId:De.z.string().min(1).max(255),nonce:De.z.uuid(),signature:De.z.string().min(1).max(1024),timestamp:De.z.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"})});var l=require("zod");var we=require("zod/v4"),jp=require("zod/v4"),Rb=jp.z.registry(),{BillingInterval:Tp}=(()=>{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:kb}=(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')."})})}))(we.z),{withSpecDefault:jb}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Rb),{COMMON:Np}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Tb}={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:Nb}=(e=>({COMMON_SET:new Set(e)}))(Np),{hasNoDuplicateCurrencies:Dp}={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:Fp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Db}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(we.z),{Infinite:Fb}={Infinite:"inf"},{TierBehavior:Mb}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Mp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:qb}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Vb}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Bb}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Ub}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(we.z),{ApiCreditTierSchema:qp}=(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."})})}))(we.z),{VIOLATION_MESSAGES:Lb}={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:Vp}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(we.z),{ModelMarkupsSchema:zb}=((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()}))(we.z,Vp),{InvoiceUsageEntrySchema:$b}=(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()}))(we.z),{AttachDiscountSchema:Bp}=(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."})}))(we.z),{CustomLineItemSchema:Gb}=(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."})})}))(we.z),{UnixMsTimestampSchema:Kb}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(we.z),{CreateInvoicePreviewLineSchema:Hb}=(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()})}))(we.z),{ReissueInvoiceParamsSchema:pc}=(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."})})}))(we.z),{InvoiceModeParamsSchema:Tr}=(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."})}))(we.z),{InvoiceTemplateSchema:Qb}=(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."})})}))(we.z),{BasePriceSchema:Jb}=((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."})})}))(we.z,Tp,kb),{CURRENCY_CODES:Zb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Np,Tb,Nb),{ApiPriceProcessorsSchema:Up}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(we.z,Db),{AllocatedBillingFieldSchema:Wb}=((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'."})}))(we.z,qb),{CreditDimensionNameSchema:Yb}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(we.z,Vb,Bb),{ApiCreditMatchSchema:Lp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Ub),{findCreditTierViolations:Xb}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(Lb),{ApiCreditMultiplierSchema:eS}=((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."})}))(we.z,Lp),{ProviderMarkupsSchema:tS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(we.z,Vp),{InvoiceFeatureQuantitySchema:zp}=((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."})}))(we.z,Mp,$b),{CreateInvoicePreviewSchema:mc}=((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()})}))(we.z,Hb),{SUPPORTED_SET:nS}=(e=>({SUPPORTED_SET:new Set(e)}))(Zb),{ApiCreditDimensionBaseSchema:rS}=((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."})})}))(we.z,Lp),{refineGraduatedTiers:$p}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(Xb),{ApiFeatureMarkupsOverrideSchema:iS}=((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."})})}))(we.z,tS,zb),{isValidCurrencyCode:oS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(nS),{ApiCreditDimensionSchema:aS}=((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()])}))(we.z,rS,qp,$p),{CurrencyCodeSchema:Gp}=((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')."})}))(we.z,oS),{AdditionalCurrencyTierSchema:sS}=((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"]})}))(we.z,Gp),{ApiCreditSchemaItemBaseSchema:Kp}=((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."})})}))(we.z,Yb,aS,eS),{ApiFlatCreditSchemaItemSchema:cS}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Kp,we.z),{AdditionalCurrencyPriceSchema:uS}=((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."})})}))(we.z,Gp),{AdditionalCurrencyTierArraySchema:lS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(we.z,sS,Dp,Fp),{ApiGraduatedCreditSchemaItemSchema:dS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Kp,we.z,qp,$p),{AdditionalCurrencyPriceArraySchema:Hp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(we.z,uS,Dp,Fp),{ApiUsageTierWithCurrenciesSchema:pS}=((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()}))}))(we.z,Fb,lS),{ApiCreditSchemaItemSchema:mS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(we.z,dS,cS),{BasePriceParamsSchema:fS}=((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."})}))(Jb,jb,we.z,Hp),{PlanItemPriceParamsSchema:gS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(we.z,Hp,pS,Mb,Tp,Mp,Wb),{ApiFeatureOverrideSchema:hS}=((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."})})}))(we.z,mS,iS),{InvoiceBasePriceParamsSchema:Qp}=((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()}))(fS,Up),{InvoiceItemPriceParamsSchema:AS}=((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()}))(gS,Up),{InvoiceLicenseQuantitySchema:yS}=((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()}))(we.z,Qp,zp),{InvoiceCustomizeItemSchema:bS}=((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()}))(we.z,AS,hS),{InvoiceCustomizeSchema:SS}=((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."})}))(we.z,Qp,bS),{InvoicePlanParamsSchema:xS}=((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()}))(we.z,SS,zp,yS,Bp),{CreateInvoiceParamsSchema:si}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(we.z,xS,Gb,Bp,Kb);var Wp=l.z.strictObject({requestId:l.z.uuid(),predecessorOperationId:l.z.uuid().optional(),invoiceMode:Tr.optional(),entityId:l.z.uuid().optional(),billingSubscriptionId:l.z.uuid().optional(),newBillingSubscription:l.z.literal(!0).optional(),offerId:l.z.uuid().optional(),nativeOffer:ai.optional(),plans:l.z.array(l.z.strictObject({productVersionId:l.z.uuid(),seatQuantities:l.z.record(To,l.z.number().int().min(0).max(1e4)).optional(),featureQuantities:l.z.record(l.z.uuid(),l.z.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:l.z.enum(["stripe","apple","google","merchant"]),currency:he}).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"),Dr=l.z.strictObject({operationId:l.z.uuid()}),kt=l.z.number().int().min(0).max(1e8),IS=l.z.strictObject({lineId:l.z.uuid(),productVersionId:l.z.uuid(),productName:l.z.string().min(1).max(80),interval:l.z.enum(["free","week","month","year","one_time"]),intervalCount:l.z.number().int().min(1).max(156).optional(),baseAmountMinor:kt,seats:l.z.array(l.z.strictObject({key:To,quantity:l.z.number().int().min(0).max(1e4),includedQuantity:l.z.number().int().min(0).max(1e4),maximumQuantity:l.z.number().int().min(0).max(1e4),unitAmountMinor:kt})).max(20),prepaid:l.z.array(Ud).max(100).optional(),catalogAmountMinor:kt,trial:l.z.strictObject({days:l.z.number().int().min(1).max(730),cardRequired:l.z.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+qo({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"),Yp=l.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),vS=l.z.strictObject({id:Yp,name:l.z.string().min(1).max(40),percent_off:l.z.number().gt(0).max(100).optional(),amount_off:l.z.number().int().positive().optional(),currency:l.z.string().regex(/^[a-z]{3}$/).optional(),duration:l.z.enum(["once","repeating","forever"]),duration_in_months:l.z.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"),wS=l.z.strictObject({subscriptionId:l.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:l.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:l.z.array(l.z.strictObject({id:l.z.string(),price_id:l.z.string(),quantity:l.z.number().int().nonnegative(),discounts:l.z.array(l.z.strictObject({id:l.z.string(),coupon:l.z.string(),start:l.z.number(),end:l.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:l.z.number().int().nonnegative(),amountMinor:l.z.number().int().positive(),periodStartMs:l.z.number(),periodEndMs:l.z.number()}),Xp=l.z.strictObject({invoiceMode:Tr.optional(),append:wS.optional(),provider:l.z.literal("stripe"),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:l.z.enum(["payment","subscription"]),lineItems:l.z.array(l.z.strictObject({price:l.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:l.z.number().int().min(1).max(1e4),priceId:l.z.uuid(),productName:l.z.string().min(1).max(80),amountMinor:l.z.number().int().min(0).max(1e8),currency:l.z.string().regex(/^[a-z]{3}$/),interval:l.z.enum(["week","month","year","one_off"]),intervalCount:l.z.number().int().min(1).max(52),slot:l.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:l.z.strictObject({mode:l.z.enum(["graduated","volume"]),tiers:l.z.array(l.z.strictObject({upTo:l.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:l.z.number().int().min(0).max(1e8),flatAmountMinor:l.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:l.z.array(l.z.strictObject({coupon:Yp,terms:vS})).max(1),trialPeriodDays:l.z.number().int().min(1).max(730).nullable(),metadata:l.z.strictObject({grooveCheckoutId:l.z.uuid(),grooveCustomerId:l.z.uuid()}),expiresAt:l.z.iso.datetime({offset:!0})}),ci=l.z.strictObject({operationId:l.z.uuid(),entityId:l.z.uuid().nullable(),billingSubscriptionId:l.z.uuid().nullable(),discount:l.z.strictObject({offerId:l.z.uuid(),couponId:l.z.uuid(),discount:Wn,duration:tn,amountMinor:kt,allocations:l.z.array(l.z.strictObject({productVersionId:l.z.uuid(),amountMinor:kt})).min(1).max(20),expiresAt:l.z.iso.datetime({offset:!0})}).nullable(),charge:l.z.strictObject({effectiveAt:l.z.iso.datetime({offset:!0}),periodEndsAt:l.z.iso.datetime({offset:!0}),debitMinor:kt,discountMinor:kt,taxMinor:kt,totalMinor:kt}).nullable(),expiresAt:l.z.iso.datetime({offset:!0}),provider:l.z.enum(["stripe","apple","google","merchant"]),nativeOffer:ai.optional(),currency:he,lines:l.z.array(IS).min(1).max(20),catalogAmountMinor:kt,automaticTax:l.z.boolean(),execution:l.z.union([Xp,Po]).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"),ui=l.z.strictObject({operationId:l.z.uuid(),orderId:l.z.uuid(),append:l.z.boolean().optional(),invoiceMode:l.z.boolean().optional(),status:l.z.enum(["pending","complete","cancelled","failed"]),executor:l.z.enum(["indiana","merchant"]),checkoutUrl:l.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:l.z.union([Xp,Po]).nullable(),currency:he,catalogAmountMinor:kt,taxMinor:kt,totalMinor:l.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:l.z.boolean(),nativePurchase:dc.nullable(),confirmedAt:l.z.iso.datetime({offset:!0}).nullable().optional(),quote:ci.optional(),merchantExecution:Sr.nullable().optional(),problem:Ei.nullable().optional(),authority:jo.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"),pa=l.z.strictObject({enabled:l.z.literal(!0),featureIds:l.z.array(l.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),em=l.z.strictObject({requestId:l.z.uuid(),invoiceMode:Tr.optional(),membershipId:l.z.uuid(),carryOverBalances:pa.optional(),carryOverUsages:pa.optional(),membershipIds:l.z.array(l.z.uuid()).min(1).max(20).optional(),prorationBehavior:l.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:l.z.enum(["immediate","renewal","store"]),change:l.z.discriminatedUnion("type",[l.z.strictObject({type:l.z.literal("plan"),productVersionId:l.z.uuid()}),l.z.strictObject({type:l.z.literal("seats"),licenseKey:To,quantity:l.z.number().int().min(0).max(1e4)}),l.z.strictObject({type:l.z.literal("quantity"),internal_feature_id:l.z.uuid(),quantity:l.z.number().int().min(0).max(1e4)}),l.z.strictObject({type:l.z.literal("cancel")}),l.z.strictObject({type:l.z.literal("uncancel")}),l.z.strictObject({type:l.z.literal("billing_cycle"),billingCycleAnchor:l.z.union([l.z.literal("now"),l.z.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"),da=l.z.string().regex(/^price_[A-Za-z0-9]+$/),Jp=l.z.strictObject({grooveUpdateId:l.z.uuid(),grooveCustomerId:l.z.uuid()}),Zp=l.z.strictObject({price:da.nullable(),priceId:l.z.uuid().optional(),quantity:l.z.number().int().min(0).max(1e4)}),tm=l.z.strictObject({provider:l.z.literal("stripe"),invoiceMode:Tr.optional(),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:l.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:l.z.enum(["update","cancel","schedule","release"]),update:l.z.strictObject({items:l.z.array(Zp).max(20),remove:l.z.array(da).max(20),restoreItems:l.z.array(l.z.strictObject({price:da,quantity:l.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:l.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:l.z.number().int().positive().optional(),paymentBehavior:l.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:l.z.boolean().optional(),clearCancelAt:l.z.literal(!0).optional(),billingCycleAnchorNow:l.z.literal(!0).optional(),metadata:Jp}).nullable(),cancel:l.z.strictObject({prorate:l.z.literal(!1),invoiceNow:l.z.literal(!1)}).nullable(),schedule:l.z.strictObject({currentItems:l.z.array(l.z.strictObject({price:da,quantity:l.z.number().int().min(0).max(1e4)})).max(20),nextItems:l.z.array(Zp).min(1).max(20),switchAt:l.z.number().int().positive(),interval:l.z.enum(["week","month","year"]),intervalCount:l.z.number().int().min(1).max(52),resetBillingCycleAnchor:l.z.literal(!0).optional(),metadata:Jp}).nullable(),release:l.z.strictObject({schedule:l.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:l.z.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"),ma=l.z.strictObject({carryOverBalances:pa.optional(),carryOverUsages:pa.optional(),operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),timing:l.z.enum(["immediate","renewal"]),effectiveAt:l.z.iso.datetime({offset:!0}),expiresAt:l.z.iso.datetime({offset:!0}),currency:he,creditMinor:kt,debitMinor:kt,discountMinor:kt,taxMinor:kt,totalMinor:kt,retainedProductVersionIds:l.z.array(l.z.uuid()).max(19),execution:l.z.union([tm,Eo])}),OS=l.z.strictObject({operationId:l.z.uuid(),invoiceMode:l.z.boolean().optional(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),status:l.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:l.z.enum(["immediate","renewal"]),effectiveAt:l.z.iso.datetime({offset:!0}),checkoutUrl:l.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:l.z.enum(["indiana","merchant"]),execution:l.z.union([tm,Eo]).nullable(),confirmedAt:l.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Sr.nullable().optional(),problem:Ei.nullable().optional(),quote:ma.optional(),authority:jo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),_S=l.z.strictObject({operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),timing:l.z.literal("store"),effectiveAt:l.z.null(),expiresAt:l.z.iso.datetime({offset:!0}),currency:he,creditMinor:l.z.null(),debitMinor:l.z.null(),discountMinor:l.z.null(),taxMinor:l.z.null(),totalMinor:l.z.null(),retainedProductVersionIds:l.z.array(l.z.uuid()).max(19),store:l.z.strictObject({provider:l.z.enum(["apple","google"]),productId:l.z.string().min(1).max(255),catalogAmountMinor:kt,policy:l.z.enum(["apple_store","google_full_price"])})}),CS=l.z.strictObject({operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),status:l.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:l.z.literal("store"),effectiveAt:l.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:l.z.null(),nativePurchase:dc.nullable()}),nm=l.z.union([ma,_S]),fc=l.z.union([OS,CS]),Yi=l.z.number().int().positive().max(2e8),Nr=l.z.number().int().min(0).max(2e8),rm=l.z.strictObject({requestId:l.z.uuid(),invoiceId:l.z.uuid(),mode:l.z.enum(["full","partial"]),amountMinor:Yi.optional(),entitlementAction:l.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),im=l.z.strictObject({provider:l.z.literal("stripe"),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:l.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Yi,currency:l.z.string().regex(/^[a-z]{3}$/),metadata:l.z.strictObject({indianaRefundId:l.z.uuid()}),idempotencyKey:l.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:l.z.array(l.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),gc=l.z.strictObject({operationId:l.z.uuid(),invoiceId:l.z.uuid(),providerInvoiceId:l.z.string().min(1).max(200),currency:he,paidMinor:Nr,refundedMinor:Nr,pendingMinor:Nr,amountMinor:Yi,mode:l.z.enum(["full","partial"]),entitlementAction:l.z.enum(["retain","revoke"]),revokes:l.z.strictObject({customerProductIds:l.z.array(l.z.uuid()).max(100),subscriptionIds:l.z.array(l.z.string().min(1).max(200)).max(20)}),execution:l.z.union([im,Ro]),expiresAt:l.z.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"),fa=l.z.strictObject({operationId:l.z.uuid(),invoiceId:l.z.uuid(),providerInvoiceId:l.z.string().min(1).max(200),status:l.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:l.z.enum(["indiana","merchant"]),currency:he,amountMinor:Yi,mode:l.z.enum(["full","partial"]),entitlementAction:l.z.enum(["retain","revoke"]),refundId:l.z.string().min(1).max(200).nullable(),quote:gc.optional(),execution:l.z.union([im,Ro]).nullable(),confirmedAt:l.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Sr.nullable().optional(),problem:Ei.nullable().optional(),authority:jo.optional(),failureReason:l.z.string().min(1).max(200).nullable(),createdAt:l.z.iso.datetime({offset:!0}),completedAt:l.z.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"),s_=l.z.strictObject({invoiceId:l.z.uuid(),currency:he,paidMinor:Nr,refundedMinor:Nr,pendingMinor:Nr,refundableMinor:Nr,executor:l.z.enum(["indiana","merchant"]).nullable(),canRefund:l.z.boolean(),operations:l.z.array(fa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),c_=l.z.strictObject({requestId:l.z.uuid(),mode:l.z.enum(["full","partial"]),amountMinor:Yi.optional(),entitlementAction:l.z.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 om=et.z.strictObject({requestId:et.z.uuid(),targets:et.z.array(et.z.strictObject({membershipId:et.z.uuid(),action:et.z.enum(["cancel","uncancel"]),timing:et.z.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"),ga=et.z.strictObject({batchId:et.z.uuid()}),PS=et.z.strictObject({operationId:et.z.uuid(),membershipIds:et.z.array(et.z.uuid()).min(1).max(20),provider:et.z.enum(["stripe","apple","google"]),action:et.z.enum(["cancel","uncancel"]),timing:et.z.enum(["immediate","renewal"]),status:et.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ma.nullable(),managementUrl:et.z.url().nullable(),failureCode:et.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Xi=et.z.strictObject({batchId:et.z.uuid(),ready:et.z.boolean(),status:et.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:et.z.iso.datetime({offset:!0}),acceptedAt:et.z.iso.datetime({offset:!0}).nullable(),groups:et.z.array(PS).min(1).max(100)});var Pe=require("zod"),ES=Pe.z.string().trim().min(1).max(240),hc={requestId:Pe.z.uuid(),reason:ES},ha=Pe.z.discriminatedUnion("action",[Pe.z.strictObject({...hc,action:Pe.z.literal("start"),productVersionId:Pe.z.uuid(),entityId:Pe.z.uuid().optional(),days:Pe.z.number().int().min(1).max(730).optional()}),Pe.z.strictObject({...hc,action:Pe.z.literal("extend"),membershipId:Pe.z.uuid(),days:Pe.z.number().int().min(1).max(730)}),Pe.z.strictObject({...hc,action:Pe.z.literal("end"),membershipId:Pe.z.uuid()})]),am=Pe.z.strictObject({operationId:Pe.z.uuid()}),sm=Pe.z.iso.datetime({offset:!0}),RS=Pe.z.strictObject({provider:Pe.z.literal("stripe"),executor:Pe.z.enum(["indiana","merchant"]),accountId:Pe.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Pe.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Pe.z.union([Pe.z.literal("now"),sm]),prorationBehavior:Pe.z.literal("none")}),Ac=Pe.z.strictObject({operationId:Pe.z.uuid(),action:Pe.z.enum(["start","extend","end"]),status:Pe.z.enum(["pending","effective"]),managedBy:Pe.z.enum(["indiana","stripe"]),membershipIds:Pe.z.array(Pe.z.uuid()).min(1).max(20),endsAt:sm.nullable(),execution:RS.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"),p_=Pe.z.strictObject({groupId:Pe.z.uuid(),productVersionId:Pe.z.uuid(),enabled:Pe.z.boolean()});var He=require("zod");var cm=He.z.strictObject({requestId:He.z.uuid(),currency:he,makeDefault:He.z.boolean()}),um=He.z.strictObject({setupId:He.z.uuid()}),kS=He.z.strictObject({provider:He.z.literal("stripe"),executor:He.z.literal("merchant"),accountId:He.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:He.z.literal("setup"),currency:He.z.string().regex(/^[a-z]{3}$/),customer:He.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:He.z.uuid(),metadata:He.z.strictObject({grooveProjectId:He.z.uuid(),grooveEnvironmentId:He.z.uuid(),grooveCustomerId:He.z.uuid(),groovePaymentSetupId:He.z.uuid()}),setDefaultPaymentMethod:He.z.boolean(),expiresAt:He.z.iso.datetime({offset:!0})}),yc=He.z.strictObject({id:He.z.uuid(),provider:He.z.literal("stripe"),status:He.z.enum(["prepared","complete","expired"]),currency:he,makeDefault:He.z.boolean(),url:He.z.url().nullable(),createdAt:He.z.iso.datetime({offset:!0}),expiresAt:He.z.iso.datetime({offset:!0}),completedAt:He.z.iso.datetime({offset:!0}).nullable(),execution:kS.nullable()});var Ot=require("zod"),lm=Ot.z.union([Ot.z.string(),Ot.z.number(),Ot.z.boolean(),Ot.z.null()]),dm=Ot.z.strictObject({customerId:Ot.z.uuid()}),pm=Ot.z.strictObject({customerId:Ot.z.uuid(),provider:Ot.z.literal("stripe"),checkedAt:Ot.z.iso.datetime({offset:!0}),status:Ot.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ot.z.number().int().nonnegative(),differences:Ot.z.array(Ot.z.strictObject({subscriptionId:Ot.z.string().startsWith("sub_"),itemId:Ot.z.string().nullable(),field:Ot.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:lm,actual:lm})).max(1e4)});var ye=require("zod");var Aa=ye.z.iso.datetime({offset:!0}),ya=ye.z.strictObject({createdAt:Aa,id:ye.z.uuid()}),ba=ye.z.strictObject({customerId:ye.z.uuid().optional(),entityId:ye.z.uuid().optional(),productId:ye.z.string().min(1).max(256).optional(),provider:ye.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:ye.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:ya.optional(),limit:ye.z.number().int().min(1).max(100).optional()}),bc={id:ye.z.uuid(),customerId:ye.z.uuid(),entityId:ye.z.uuid().nullable(),productId:ye.z.string().min(1).max(256),productVersionId:ye.z.uuid(),name:ye.z.string().min(1).max(120),provider:ye.z.enum(["stripe","apple","google","merchant","free"]),createdAt:Aa},jS=ye.z.strictObject({...bc,status:ye.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ye.z.boolean(),billingSubscriptionId:ye.z.uuid().nullable()}),TS=ye.z.strictObject({...bc,status:ye.z.enum(["active","ended","refunded"]),orderId:ye.z.uuid().nullable(),transactionId:ye.z.uuid().nullable(),currency:he.nullable(),amountMinor:ye.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),NS=ye.z.strictObject({...bc,status:ye.z.enum(["blocked","resolved"]),conflict:ye.z.strictObject({detectedAt:Aa,blockingMembershipIds:ye.z.array(ye.z.uuid()).min(1).max(100),transactionId:ye.z.uuid()}),resolvedAt:Aa.nullable()}),mm=ba.extend({status:ye.z.enum(["blocked","resolved"]).optional()}),fm=ye.z.strictObject({customerId:ye.z.uuid(),orderId:ye.z.uuid()}),gm=ye.z.strictObject({orderId:ye.z.uuid(),status:ye.z.enum(["blocked","resolved"])}),hm=ye.z.strictObject({items:ye.z.array(jS).max(100),nextCursor:ya.nullable()}),Am=ye.z.strictObject({items:ye.z.array(TS).max(100),nextCursor:ya.nullable()}),ym=ye.z.strictObject({items:ye.z.array(NS).max(100),nextCursor:ya.nullable()});var We=require("zod");var bm=We.z.union([We.z.strictObject({intent:We.z.literal("read"),requestId:We.z.uuid(),purchaseIntentId:We.z.uuid()}),We.z.strictObject({requestId:We.z.uuid(),provider:We.z.literal("apple"),purchaseIntentId:We.z.uuid(),productId:We.z.string().min(1).max(255).optional(),signedTransaction:We.z.string().min(1).max(131072)}),We.z.strictObject({requestId:We.z.uuid(),provider:We.z.literal("google"),purchaseIntentId:We.z.uuid(),productId:We.z.string().min(1).max(255).optional(),purchaseToken:We.z.string().min(1).max(16384)})]),Sm=We.z.strictObject({requestId:We.z.uuid(),orderId:We.z.uuid(),purchaseIntentId:We.z.uuid(),status:We.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:he,refunded:We.z.boolean(),completion:We.z.strictObject({transactionIds:We.z.array(We.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:We.z.boolean()}).nullable()});var U=require("zod"),xc=U.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),DS=U.z.record(U.z.string(),U.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),FS=3,eo=20,MS=FS*eo,Sc=U.z.strictObject({type:U.z.literal("product"),productId:xc}),xm={type:U.z.literal("group"),key:U.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:U.z.string().trim().min(1).max(80)},qS=U.z.discriminatedUnion("type",[Sc,U.z.strictObject({...xm,items:U.z.array(Sc).max(eo)})]),VS=U.z.discriminatedUnion("type",[Sc,U.z.strictObject({...xm,items:U.z.array(qS).max(eo)})]),BS=U.z.array(VS).max(eo).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>eo||i>MS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ic(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ic(t))}var li=U.z.strictObject({lookupKey:U.z.string().trim().min(1).max(200),displayName:U.z.string().trim().min(1).max(1500),items:BS,metadata:DS}),US=U.z.strictObject({product:U.z.record(U.z.string(),U.z.json()),prices:U.z.array(U.z.record(U.z.string(),U.z.json())),entitlements:U.z.array(U.z.record(U.z.string(),U.z.json())),freeTrials:U.z.array(U.z.record(U.z.string(),U.z.json())),licenses:U.z.array(U.z.record(U.z.string(),U.z.json()))}),Im=li.extend({id:U.z.uuid(),projectId:U.z.uuid(),environmentId:U.z.uuid(),state:U.z.enum(["active","archived"]),isCurrent:U.z.boolean(),revision:U.z.number().int().nonnegative(),publishedVersionId:U.z.uuid().nullable(),createdAt:U.z.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"})}),vm=U.z.strictObject({id:U.z.uuid(),offeringId:U.z.uuid(),projectId:U.z.uuid(),environmentId:U.z.uuid(),version:U.z.number().int().positive(),document:li,productEvidence:U.z.record(xc,US),createdAt:U.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Ic(e.document);(!n.length||$S(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"})}),LS=U.z.strictObject({rows:U.z.array(Im).max(200),versions:U.z.array(vm).max(500)}),x_=U.z.discriminatedUnion("action",[U.z.strictObject({action:U.z.literal("create"),document:li}),U.z.strictObject({action:U.z.literal("save"),id:U.z.uuid(),revision:U.z.number().int().nonnegative(),document:li}),U.z.strictObject({action:U.z.enum(["publish","set_current","archive","restore"]),id:U.z.uuid(),revision:U.z.number().int().nonnegative()})]),I_=U.z.strictObject({record:Im,version:vm.nullable()}),wm=U.z.discriminatedUnion("type",[U.z.strictObject({type:U.z.literal("current")}),U.z.strictObject({type:U.z.literal("id"),id:U.z.uuid()}),U.z.strictObject({type:U.z.literal("lookup_key"),lookupKey:U.z.string().min(1).max(200)}),U.z.strictObject({type:U.z.literal("version"),versionId:U.z.uuid()})]),zS=U.z.strictObject({internalId:xc,id:U.z.string(),name:U.z.string().nullable(),version:U.z.number().int().positive(),archived:U.z.boolean()}),v_=LS.extend({products:U.z.array(zS).max(500),pagination:U.z.strictObject({rows:U.z.string().nullable(),versions:U.z.string().nullable(),products:U.z.string().nullable()}).optional()});function $S(e){let t=[];Ic(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}var to=require("zod");var Om=to.z.strictObject({id:to.z.uuid(),offeringId:to.z.uuid(),version:to.z.number().int().positive(),document:li});var ht=require("zod");var de=require("zod");var Fr=require("zod");var Sa=Fr.z.strictObject({items:Fr.z.array(Fr.z.strictObject({productVersionId:Fr.z.string().min(1).max(200),label:Fr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Fr.z.string().min(1).max(200).nullable(),grouping:oa.optional()});function _m(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}var gt=require("zod"),GS=gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xa=gt.z.discriminatedUnion("type",[gt.z.object({type:gt.z.literal("fixed"),productVersionId:gt.z.string().min(1).max(200)}).strict(),gt.z.object({type:gt.z.literal("picker"),pickerId:GS,allowedProductVersionIds:gt.z.array(gt.z.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")]),Bn=gt.z.discriminatedUnion("type",[gt.z.object({type:gt.z.literal("modal"),size:gt.z.enum(["sm","md","lg"])}).strict(),gt.z.object({type:gt.z.literal("sheet"),size:gt.z.enum(["sm","md","lg"])}).strict(),gt.z.object({type:gt.z.literal("fullscreen")}).strict(),gt.z.object({type:gt.z.literal("inline")}).strict()]);var vc=de.z.discriminatedUnion("type",[de.z.strictObject({type:de.z.literal("event"),event:de.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),de.z.strictObject({type:de.z.literal("open_url"),url:de.z.url().refine(e=>new URL(e).protocol==="https:")})]),KS=rn,HS=de.z.discriminatedUnion("type",[de.z.object({type:de.z.literal("checkout"),product:xa}).strict(),de.z.object({type:de.z.literal("close")}).strict(),de.z.object({type:de.z.literal("action"),action:vc}).strict()]),di=de.z.object({schemaVersion:de.z.literal(3),kind:de.z.literal("paywall"),name:de.z.string().trim().min(1).max(80),presentation:Bn,requirement:Yn.optional(),products:Sa,offeringVersionId:de.z.uuid().nullable(),offeringId:de.z.uuid(),screen:KS,buttons:de.z.record(de.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),HS)}).strict(),F_=di.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 JS(e))t.addIssue({code:"custom",message:r});for(let r of QS(e))t.addIssue({code:"custom",message:r});er(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 QS(e){let t=e.products.items.map(a=>a.productVersionId),n=Ap(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&&(!aa(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Lt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let d=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(d)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Lt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function JS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Xn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let d=e.screen.actions.find(w=>w.id===u);d?.type==="navigate"&&r.get(s.id).push(d.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Cm=de.z.object({id:de.z.uuid(),projectId:de.z.uuid(),environmentId:de.z.uuid(),revision:de.z.number().int().nonnegative(),state:de.z.enum(["active","archived"]),publishedVersionId:de.z.uuid().nullable(),updatedAt:de.z.iso.datetime({offset:!0}),draft:di}).strict(),M_=de.z.object({rows:de.z.array(Cm).max(200),nextCursor:de.z.uuid().nullable()}).strict(),q_=Cm.omit({draft:!0}).extend({name:de.z.string(),productCount:de.z.number().int().nonnegative()}).strict(),V_=de.z.discriminatedUnion("action",[de.z.object({action:de.z.literal("save"),id:de.z.uuid().nullable(),revision:de.z.number().int().nonnegative(),document:di}).strict(),de.z.object({action:de.z.enum(["publish","archive"]),id:de.z.uuid(),revision:de.z.number().int().nonnegative()}).strict()]),B_=de.z.object({paywalls:de.z.array(de.z.object({id:de.z.uuid(),paywallId:de.z.uuid(),version:de.z.number().int().positive(),name:de.z.string().min(1).max(80),presentation:Bn,buttons:di.shape.buttons}).strict()).max(500),limited:de.z.boolean()}).strict();var Oe=require("zod");var Nt=require("zod");var pi=Nt.z.string().regex(/^[a-f0-9]{64}$/),ZS=ra.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Pm=Nt.z.strictObject({couponDigests:Nt.z.record(Nt.z.uuid(),pi),variables:Nt.z.record(An,Nt.z.record(Nt.z.uuid(),Nt.z.partialRecord(Nt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Nt.z.string()))),locales:Nt.z.record(An,ti.extend({nodes:Nt.z.record(Nt.z.string(),Nt.z.strictObject({base:ZS})),plans:Nt.z.object({}).strict(),pickers:Nt.z.object({}).strict()}).omit({paywall:!0}))});var Fe=require("zod");var no=require("zod"),wc=no.z.strictObject({eventsEnabled:no.z.boolean(),experimentViewsEnabled:no.z.boolean(),featureUsageEnabled:no.z.boolean()}),G_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Em(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var Oc=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),WS=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(Oc).max(100)}),YS=$.z.strictObject({id:$.z.string().min(1).max(255),condition:Ht,gate:$.z.boolean().optional()}),XS=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),Rm={condition:Ht.optional(),parentConditions:$.z.array(YS).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(WS).max(100).optional(),ranges:$.z.array(Oc).max(20).optional(),meta:$.z.array(XS).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},mi=$.z.strictObject({...Rm,key:$.z.string().min(1).max(255),variations:$.z.tuple([Ae,Ae]).rest(Ae).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),_c=$.z.strictObject({value:Ae,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),ex=$.z.strictObject({...Rm,id:$.z.string().max(255).optional(),force:Ae.optional(),variations:$.z.array(Ae).min(2).max(20).optional(),key:$.z.string().optional(),range:Oc.optional(),tracks:$.z.array($.z.strictObject({experiment:mi,result:_c})).max(100).optional()}),tx=$.z.strictObject({defaultValue:Ae.optional(),rules:$.z.array(ex).max(500).optional()}),ro=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:Ht})])),pn=$.z.strictObject({scope:ze,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),tx),savedGroups:ro,experiments:$.z.record($.z.uuid(),mi)});var io=pn.extend({analyticsConfig:wc,remoteFeatures:Fe.z.array(Fe.z.string().min(1).max(255)).max(500)}),Cc=io.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"})}),km=Fe.z.strictObject({attributes:xt,features:Fe.z.array(Fe.z.string().min(1).max(255)).max(500).optional(),customerId:Fe.z.uuid().optional()}),nx=Fe.z.strictObject({value:Ae,source:Fe.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Fe.z.boolean(),off:Fe.z.boolean(),ruleId:Fe.z.string(),experimentResult:_c.optional()}),Ia=Fe.z.strictObject({generation:pn.shape.generation,evaluatedAt:pn.shape.evaluatedAt,expiresAt:pn.shape.expiresAt,features:Fe.z.record(Fe.z.string(),nx),merchandiseContext:Fe.z.strictObject({merchandiseId:Fe.z.uuid(),merchandise:xt}).optional()}),jm=Fe.z.strictObject({customerId:Fe.z.uuid().optional(),events:Fe.z.array(Fe.z.strictObject({eventUuid:Fe.z.uuid(),timestamp:Fe.z.iso.datetime({offset:!0}),name:Fe.z.string().min(1).max(255),merchandise:gd.optional(),properties:Fe.z.record(Fe.z.string(),Ae).default({}),deviceId:Fe.z.string().min(1).max(255).optional(),sessionId:Fe.z.string().min(1).max(255).optional()})).min(1).max(100)}),Tm=Fe.z.strictObject({inserted:Fe.z.number().int().nonnegative(),duplicates:Fe.z.number().int().nonnegative(),rejected:Fe.z.number().int().nonnegative(),skipped:Fe.z.number().int().nonnegative(),analyticsConfig:wc});var L=require("zod");function Pc(e,t=[]){let n=[];Lt(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(sa(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function Nm(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Nm(t)??[])}}function rx(e){let t=e.pages.map(i=>{let a=Nm(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(sa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function Dm(e,t=[]){let n=rn.parse(structuredClone(rx(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=Pc(n,t);if(i.length)throw new Error(i.join("; "));return n}var Q=require("zod");var F=require("zod");var at=require("zod"),va=at.z.strictObject({schemaVersion:at.z.literal(1),renderKey:at.z.string().min(1).max(256),routeTemplate:at.z.string().startsWith("/").max(2048),selectors:at.z.array(at.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:at.z.array(at.z.number().int().min(0)).min(1),absent:at.z.array(at.z.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),Fm=at.z.strictObject({renderKey:at.z.string().min(1).max(256),routeKey:at.z.string().min(1).max(256),stateKey:at.z.string().min(1).max(256),documentKey:at.z.string().min(1).max(256),documentHash:at.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:at.z.string().min(1).max(256),entryMode:at.z.enum(["hard","soft"]),match:at.z.strictObject({present:at.z.array(at.z.number().int().min(0)),absent:at.z.array(at.z.number().int().min(0))})});var rr=require("zod"),ix=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Ec="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ox=rr.z.string().regex(new RegExp(`^${Ec}/${Ec}/${Ec}/manifest\\.json$`)),Mm=rr.z.strictObject({kind:rr.z.literal("gcs-resumable"),url:rr.z.url(),bucket:rr.z.enum(ix),objectKey:ox,byteLength:rr.z.number().int().positive(),expiresAt:rr.z.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var pt=F.z.string().min(1).max(256),an=F.z.string().regex(/^[a-f0-9]{64}$/),wa=F.z.strictObject({versionId:F.z.uuid(),manifestDigest:an,sourceGraphDigest:an,pageKey:pt,stateKey:pt,documentKey:pt,documentHash:an,elementKey:pt.optional(),nodeId:pt.optional(),contentHash:an.optional(),renderKey:pt.optional()}),qm=F.z.strictObject({pageKey:pt,documentKey:pt,expectedDocumentHash:an,renderKey:pt.optional(),nodeId:pt,elementKey:pt,expectedContentHash:an,property:F.z.enum(["text","fontSize","color"]),value:F.z.union([F.z.string().max(4e3),F.z.number().finite()])}),Vm=F.z.strictObject({versionId:F.z.uuid(),manifestDigest:an,sourceGraphDigest:an,pageKey:pt,stateKey:pt,documentKey:pt,documentHash:an,renderKey:pt.optional(),patches:F.z.array(qm.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),ax=/^[a-z][a-z0-9-]{0,39}$/,oo=F.z.string().regex(ax),kc=F.z.enum(["web","ios","android"]),s1=F.z.discriminatedUnion("action",[F.z.strictObject({action:F.z.literal("register"),requestId:F.z.uuid(),client:oo,platform:kc,label:F.z.string().trim().min(1).max(100),sha256:an,bytes:F.z.number().int().min(1),transferBytes:F.z.number().int().min(1)}),F.z.strictObject({action:F.z.literal("complete"),versionId:F.z.uuid()}),F.z.strictObject({action:F.z.literal("current"),versionId:F.z.uuid(),expectedCurrent:F.z.uuid().nullable()}),F.z.strictObject({action:F.z.literal("delivery"),enabled:F.z.boolean()}),F.z.strictObject({action:F.z.literal("changes"),versionId:F.z.uuid(),experimentId:F.z.uuid(),variationId:pt,changesetId:F.z.uuid().nullable(),expectedRevision:an.nullable(),editorUrl:F.z.string().url().max(2048),patches:F.z.array(qm).max(200)})]),jc=F.z.strictObject({id:F.z.uuid(),projectId:F.z.uuid(),environmentId:F.z.uuid(),clientKey:oo,platform:kc,label:F.z.string(),sha256:an,bytes:F.z.number().int().positive(),objectKey:F.z.string(),state:F.z.enum(["uploading","ready","rejected"]),isCurrent:F.z.boolean(),revision:F.z.number().int().nonnegative(),createdAt:F.z.string(),expiresAt:F.z.string(),readyAt:F.z.string().nullable(),summary:F.z.record(F.z.string(),F.z.json()),routeTree:F.z.json().nullable(),validation:F.z.record(F.z.string(),F.z.json())}),sx=F.z.strictObject({key:oo,platform:kc,currentId:F.z.uuid().nullable()}),c1=F.z.strictObject({rows:F.z.array(jc).max(100),nextCursor:F.z.uuid().nullable(),clients:F.z.array(sx).max(20)}),Rc=F.z.strictObject({storedBytes:F.z.number().int().nonnegative(),reservedBytes:F.z.number().int().nonnegative(),chargedBytes:F.z.number().int().nonnegative(),versions:F.z.number().int().nonnegative(),objects:F.z.number().int().nonnegative(),orphanObjects:F.z.number().int().nonnegative(),missingReadyObjects:F.z.number().int().nonnegative(),unknownObjectSizes:F.z.number().int().nonnegative(),byteLimit:F.z.number().int().positive(),versionLimit:F.z.number().int().positive(),remainingBytes:F.z.number().int().nonnegative()}),u1=F.z.strictObject({asOf:F.z.iso.datetime({offset:!0}),reclamation:F.z.literal("manual-review-required"),buckets:F.z.strictObject({source:Rc,runtime:Rc,previews:Rc})}),l1=F.z.strictObject({version:jc,actorId:F.z.uuid(),claims:F.z.record(F.z.string(),F.z.json())}),d1=F.z.strictObject({version:jc,upload:Mm.nullable()}),p1=F.z.object({format:F.z.literal("indiana-route-state-index"),schemaVersion:F.z.literal(3),routes:F.z.array(F.z.object({routeKey:pt,path:F.z.string(),documentKey:pt,documentHash:an,initialStateKey:pt,initialRenderKey:pt})),renders:F.z.array(Fm)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),m1=F.z.strictObject({rows:F.z.array(F.z.object({id:F.z.uuid(),name:F.z.string(),status:F.z.string(),variations:F.z.array(F.z.object({id:pt,key:pt,name:F.z.string().optional()}).loose())}).loose()),limited:F.z.boolean()}),f1=F.z.strictObject({enabled:F.z.boolean(),allowedOrigins:F.z.array(F.z.string())});var Mr=require("zod");var Bm=Mr.z.strictObject({id:Mr.z.uuid(),name:Mr.z.string().trim().min(1).max(80),client:oo,source:wa,event:Mr.z.enum(["screen_enter","button_click"]),cooldownSeconds:Mr.z.number().int().min(0).max(2592e3),behavior:Mr.z.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"})});var Ve=require("zod");var Tc=Ae,cx=["parameters","answers","results","variables"];function Nc(e){return cx.some(t=>e===t||e.startsWith(t+"."))}function Dc(e){let t={};for(let[r,i]of Object.entries(ca(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Nc(r))),variables:t}}var ct=require("zod");var Oa=ct.z.discriminatedUnion("kind",[ct.z.object({kind:ct.z.literal("ledger"),cursor:na}).strict(),ct.z.object({kind:ct.z.literal("billing"),cursor:ct.z.uuid()}).strict()]),ux=ct.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ir=ct.z.record(ct.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ct.z.union([ct.z.string().max(500),ct.z.boolean(),ct.z.array(ct.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),lx=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Fc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Fc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||lx.test(n)||Fc(r,t+1)))}var dx=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,or=ct.z.record(ux,Ae).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Fc(e)&&!dx.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var Um=ct.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_a=ct.z.array(ct.z.object({variable:Um,componentId:Um,required:ct.z.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),w1=ct.z.object({bindings:_a,answers:ir,values:ct.z.record(ct.z.string(),Ae).optional()}).strict();var Lm=require("zod"),Ca=Lm.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Mc=Ve.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),zm=Ve.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),$m=or.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),qc=Ve.z.record(Mc,Ve.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),px=Pn,Gm=Ve.z.strictObject({type:Ve.z.literal("external_task"),endpointId:Ve.z.uuid(),taskKey:Mc,inputs:Ve.z.record(Mc,px).refine(e=>Object.keys(e).length<=20),outputs:qc}),Km=Ve.z.strictObject({maxAttempts:Ve.z.number().int().min(1).max(5),retryDelaySeconds:Ve.z.number().int().min(1).max(30),backoff:Ve.z.enum(["fixed","exponential"]),requestTimeoutSeconds:Ve.z.number().int().min(1).max(10),timeoutSeconds:Ve.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var j1=Ve.z.strictObject({outcome:Ve.z.enum(["success","failure"]),data:$m});var T1=Ve.z.discriminatedUnion("operation",[Ve.z.strictObject({operation:Ve.z.literal("signal"),runId:Ve.z.uuid(),nodeId:zm,eventName:Ca,eventId:Ve.z.uuid(),data:$m}),Ve.z.strictObject({operation:Ve.z.literal("read_results"),runId:Ve.z.uuid()})]),N1=Ve.z.strictObject({scope:ze,runId:Ve.z.uuid(),eventId:Ve.z.uuid(),accepted:Ve.z.boolean()}),mx=Ve.z.record(zm,Tc),D1=Ve.z.strictObject({scope:ze,runId:Ve.z.uuid(),results:mx});var In={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Hm="00000000-0000-0000-0000-000000000000";var J=require("zod");var Qe=require("zod");var B1=Qe.z.enum(["local","remote"]),Vc=Qe.z.strictObject({port:Qe.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Ae.optional(),sticky:Qe.z.array(Qe.z.strictObject({expected:Ni.nullable(),next:Ni})).max(100),exposures:Qe.z.array(Ae).max(100),features:Qe.z.array(Ae).max(100)}),Qm=Qe.z.strictObject({type:Qe.z.literal("evaluate"),receiptId:Qe.z.uuid(),environmentId:Qe.z.uuid(),policyRevision:Qe.z.number().int().nonnegative(),attributes:xt,sticky:Qe.z.record(Qe.z.string(),Ni)}),Jm=Qm.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative()}),Bc=Qm.omit({type:!0,receiptId:!0}).extend({type:Qe.z.literal("evaluate_segment")}),Zm=Qe.z.strictObject({nodeId:Qe.z.string().min(1).max(64),result:Vc}),Wm=Bc.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative(),parameters:or,answers:ir,variables:Qe.z.record(Qe.z.string(),Ae)});var ae=require("zod");var Uc=ae.z.array(ae.z.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"),Pa=ae.z.intersection(xt,ae.z.looseObject({tags:Uc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ea=ae.z.string().trim().max(80),Ra=ae.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ka=ae.z.union([ae.z.email().max(254),ae.z.literal("")]),ja=ae.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Ym=ae.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Xm=ae.z.object({externalUserId:Ym.optional(),name:Ea.default(""),email:ka.default(""),phone:Ra.optional(),attributes:Pa.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Ta=ae.z.discriminatedUnion("type",[ae.z.strictObject({type:ae.z.literal("id"),value:ae.z.uuid()}),ae.z.strictObject({type:ae.z.literal("externalUserId"),value:Ym})]),Na=ae.z.strictObject({name:Ea.optional(),email:ka.optional(),phone:Ra.optional(),attributes:Pa.optional(),fingerprint:ja.optional()}),Da=e=>!e.customerData||e.customer?.type==="externalUserId",Fa="customerData requires an externalUserId customer",fi=ae.z.object({id:ae.z.uuid(),externalUserId:ae.z.string().min(1).max(255).nullable(),name:Ea,email:ka,phone:Ra.optional(),attributes:Pa,createdAt:ae.z.iso.datetime()}).strict(),ef=ae.z.object({customer:fi,changed:ae.z.boolean(),replayed:ae.z.boolean()}).strict(),fx=ae.z.discriminatedUnion("type",[ae.z.object({type:ae.z.literal("id"),value:ae.z.uuid()}).strict(),ae.z.object({type:ae.z.literal("externalUserId"),value:ae.z.string().trim().min(1).max(255)}).strict()]),gx=ae.z.object({name:Ea.optional(),email:ka.optional(),phone:Ra.optional(),attributes:Pa.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ae.z.array(ae.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ae.z.strictObject({add:Uc,remove:Uc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Lc=ae.z.object({lookup:fx}).strict(),tf=Lc.extend({requestId:ae.z.uuid(),patch:gx}).strict(),nf=ae.z.object({search:ae.z.string().trim().max(200).default(""),tag:ae.z.string().trim().max(40).default(""),planId:ae.z.string().max(200).default(""),versionId:ae.z.string().max(200).default(""),holdingStatus:ae.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ae.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ae.z.union([ae.z.iso.datetime(),ae.z.literal("")]).default(""),createdUntil:ae.z.union([ae.z.iso.datetime(),ae.z.literal("")]).default(""),offset:ae.z.coerce.number().int().min(0).max(1e5).default(0),limit:ae.z.coerce.number().int().min(1).max(100).default(50)}).strict(),rf=ae.z.object({customers:fi.array(),hasMore:ae.z.boolean(),total:ae.z.number().int().nonnegative().nullable(),evaluatedAt:ae.z.iso.datetime()}).strict();var ao=J.z.discriminatedUnion("type",[J.z.strictObject({type:J.z.literal("literal"),value:Ae}),J.z.strictObject({type:J.z.literal("variable"),key:ft,path:xn.optional()}),J.z.strictObject({type:J.z.literal("feature"),featureKey:J.z.string().min(1).max(128)})]),hx=J.z.strictObject({requestId:J.z.uuid(),decisionId:J.z.uuid(),customerId:J.z.uuid(),externalUserId:J.z.string().min(1).max(255).nullable(),versionId:J.z.uuid(),receiptId:J.z.uuid(),value:Ae}),Ax={funnelId:J.z.uuid(),requestId:J.z.uuid(),customer:Ta,customerData:Na.optional(),attributes:xt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},Z1=J.z.discriminatedUnion("operation",[J.z.strictObject({operation:J.z.literal("decide"),...Ax}).refine(Da,Fa),J.z.strictObject({operation:J.z.literal("read_decision"),decisionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("evaluate_decision"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),receiptId:J.z.uuid(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),result:Vc}),J.z.strictObject({operation:J.z.literal("feature_config"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("commit_decision_segment"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),steps:J.z.array(Zm).max(32),boundary:J.z.strictObject({nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative()}).optional()}),J.z.strictObject({operation:J.z.literal("segment_configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid().optional()}),J.z.strictObject({operation:J.z.literal("local_configuration"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("report_used"),decisionId:J.z.uuid(),eventId:J.z.uuid(),occurredAt:J.z.iso.datetime({offset:!0}),reference:J.z.string().min(1).max(128).optional()})]),W1=J.z.strictObject({scope:ze,decisionId:J.z.uuid(),requestId:J.z.uuid(),status:J.z.enum(["pending","completed","failed"]),decision:hx.nullable(),evaluation:J.z.discriminatedUnion("type",[Jm,Wm]).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"),Y1=J.z.strictObject({scope:ze,decisionId:J.z.uuid(),eventId:J.z.uuid(),source:J.z.literal("caller_reported")});var _t=require("zod");var of=_t.z.strictObject({type:_t.z.literal("bundle"),paywall:Pn.optional(),offering:Pn.optional(),coupons:Pn,data:Pn}),yx=e=>_t.z.strictObject({type:_t.z.literal(e),id:_t.z.uuid()}),rC=_t.z.strictObject({type:_t.z.literal("bundle"),paywallVersionId:_t.z.uuid().optional(),offeringVersionId:_t.z.uuid().optional(),couponIds:_t.z.array(_t.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Ae});var iC=_t.z.strictObject({type:_t.z.literal("bundle"),offering:yx("offering_version").nullable(),paywall:_t.z.strictObject({versionId:_t.z.uuid(),paywallId:_t.z.uuid(),offeringVersionId:_t.z.uuid()}).nullable(),coupons:_t.z.array(Di).max(20),data:Ae});var mn=require("zod");var sn=require("zod");var af=sn.z.union([sn.z.string(),sn.z.number().finite(),sn.z.boolean(),sn.z.null()]),bx=sn.z.union([af,sn.z.array(af).min(1).max(20)]),Sx=sn.z.record(xn,bx).refine(e=>Object.keys(e).length<=10),sf=sn.z.strictObject({path:xn,type:sn.z.enum(["string","number","boolean","strings"]),nullable:sn.z.boolean().optional(),aggregation:sn.z.enum(["count","exists"]).optional(),where:Sx.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 xx=["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"],cf=mn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ix=Pn,uf=mn.z.discriminatedUnion("type",[Gm,mn.z.strictObject({type:mn.z.literal("claim_offer"),coupon:Pn}),mn.z.strictObject({type:mn.z.literal("event"),event:cf}),mn.z.strictObject({type:mn.z.literal("api"),operation:mn.z.enum(xx),inputs:mn.z.record(xn,Ix).refine(e=>Object.keys(e).length<=40),outputs:mn.z.record(cf,sf).refine(e=>Object.keys(e).length<=20)})]);var ot=Ca,vx=Q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),cn={id:ot,name:Q.z.string().trim().min(1).max(80),position:Q.z.strictObject({x:Q.z.number().finite(),y:Q.z.number().finite()}).optional()},wx={success:ot,cancel:ot,unavailable:ot,failure:ot},zc=Q.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),$c=Q.z.enum(["same_window","new_window"]),Ox=Q.z.discriminatedUnion("type",[Q.z.strictObject({...cn,type:Q.z.literal("entry"),next:ot,triggers:Q.z.array(Bm).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.z.strictObject({...cn,type:Q.z.literal("screen"),screenId:ot,presentation:Bn,outputs:Q.z.record(ot,ot),offering:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("variable"),key:ft}),Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()})]).optional()}),Q.z.strictObject({...cn,type:Q.z.literal("offering"),configuration:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()}),Q.z.strictObject({source:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("coupon"),couponId:Q.z.uuid(),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("coupons"),couponIds:Q.z.array(Q.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("output"),value:Q.z.discriminatedUnion("type",[...ao.options,of,Q.z.strictObject({type:Q.z.literal("selection"),screenId:ot,offeringKey:ft})])}),Q.z.strictObject({...cn,type:Q.z.literal("condition"),cases:Q.z.array(Q.z.strictObject({condition:Ht,target:ot})).min(1).max(50),default:ot}),Q.z.strictObject({...cn,type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("split"),experimentId:Q.z.uuid(),applyPageExperiment:Q.z.literal(!0).optional(),routes:Q.z.record(vx,ot).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ot}),Q.z.strictObject({...cn,type:Q.z.literal("action"),...wx,execution:Km,action:uf,writes:ic.optional()}),Q.z.strictObject({...cn,type:Q.z.literal("external_page"),appManifest:wa.optional(),url:zc,openIn:$c,opened:ot,failed:ot}),Q.z.strictObject({...cn,type:Q.z.literal("end"),outcome:Q.z.enum(["completed","closed","ineligible","failed"]),output:ao.optional()}),Q.z.strictObject({...cn,type:Q.z.literal("wait"),writes:ic.optional(),wait:Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("duration"),delaySeconds:Q.z.number().int().min(1).max(2592e3),elapsed:ot}),Q.z.strictObject({type:Q.z.literal("event"),eventName:ot,outputs:qc,timeoutSeconds:Q.z.number().int().min(1).max(2592e3),received:ot,timeout:ot})])})]),Gc=Q.z.strictObject({version:Q.z.literal(5),entry:ot,nodes:Q.z.array(Ox).min(1).max(In.flowNodes)}),Kc=Gc.superRefine((e,t)=>{_x(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ma(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 _x(e,t){let n=[],r=new Map(e.nodes.map(d=>[d.id,d])),i=(d,m,w)=>{n.push(d),t?.({message:d,reason:m,path:w?["nodes",e.nodes.indexOf(w)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(d=>d.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(d=>d.type==="screen").length>In.pages||e.nodes.filter(d=>!["screen","entry","end","output"].includes(d.type)).length>In.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let d of e.nodes){for(let m of Ma(d))m===e.entry&&i("An entry cannot be a transition target","entryTarget",d),r.has(m)||i(`Missing target ${m}`,"missingTarget",d);d.type==="screen"&&(a.has(d.screenId)&&i("Every screen has exactly one node owner","screenOwner",d),a.add(d.screenId))}let o=new Set,s=new Set,c=new Set;function u(d){if(o.has(d)){i("Flow edges must not form a cycle","cycle",r.get(d));return}if(!(s.has(d)||!r.has(d))){o.add(d),c.add(d);for(let m of Ma(r.get(d)))u(m);o.delete(d),s.add(d)}}u(e.entry);for(let d of e.nodes)c.has(d.id)||i("Every node must be reachable from Entry","unreachable",d);return[...new Set(n)]}var Hc={maxTransitions:1e4,runTimeoutSeconds:2592e3};function lf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(d=>s===d||c&&s.startsWith(d+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Zn(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}var M=require("zod");var gi=M.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),qa=e=>M.z.record(M.z.string(),Ae).refine(t=>on(t)<=e,"Funnel evidence exceeds its byte budget"),kC=M.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Jc=M.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Zc=M.z.discriminatedUnion("type",[M.z.strictObject({type:M.z.literal("flag"),key:M.z.string().min(1).max(128)}),M.z.strictObject({type:M.z.literal("experiment"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("saved_group"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("config"),key:M.z.string().min(1).max(128)}),M.z.strictObject({type:M.z.literal("constant"),key:M.z.string().min(1).max(128)}),M.z.strictObject({type:M.z.literal("paywall_version"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("offering_version"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("reward"),id:M.z.uuid()})]),so=M.z.strictObject({schemaVersion:M.z.literal(1),kind:Jc,selector:Zc.nullable(),context:qa(131072),contract:M.z.strictObject({version:M.z.number().int().positive(),evaluator:M.z.string().min(1).max(128),policyRevision:M.z.number().int().nonnegative()})}).refine(e=>on(e)<=131072,"Node input exceeds its byte budget"),df=M.z.strictObject({schemaVersion:M.z.literal(1),kind:Jc,outcome:M.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:qa(131072),route:M.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:qa(131072)}).refine(e=>on(e)<=131072,"Node result exceeds its byte budget"),jC=M.z.strictObject({schemaVersion:M.z.literal(1),operations:M.z.record(gi,M.z.strictObject({attempts:M.z.number().int().nonnegative(),maxAttempts:M.z.number().int().min(1).max(5),deadlineAt:M.z.iso.datetime({offset:!0}),retryAt:M.z.iso.datetime({offset:!0}).nullable(),error:M.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:M.z.strictObject({type:gi,id:M.z.uuid()}).nullable()}))}).refine(e=>on(e)<=65536,"Execution state exceeds its byte budget"),qr={receiptId:M.z.uuid()},Qc=M.z.iso.datetime({offset:!0}),TC=M.z.discriminatedUnion("type",[M.z.strictObject({type:M.z.literal("node_entered"),details:M.z.strictObject({kind:Jc})}),M.z.strictObject({type:M.z.literal("presentation_shown"),details:M.z.strictObject({...qr,source:M.z.literal("client"),occurredAt:Qc.optional()})}),M.z.strictObject({type:M.z.literal("decision_accepted"),details:M.z.strictObject(qr)}),M.z.strictObject({type:M.z.literal("signal_received"),details:M.z.strictObject({signalId:M.z.uuid(),nodeId:gi,eventName:gi,data:qa(8192),source:M.z.literal("server"),occurredAt:Qc})}),M.z.strictObject({type:M.z.literal("signal_consumed"),details:M.z.strictObject({...qr,signalId:M.z.uuid()})}),M.z.strictObject({type:M.z.literal("wait_elapsed"),details:M.z.strictObject(qr)}),M.z.strictObject({type:M.z.literal("wait_timeout"),details:M.z.strictObject(qr)}),M.z.strictObject({type:M.z.literal("operation_completed"),details:M.z.strictObject({...qr,operation:gi,reference:M.z.strictObject({type:gi,id:M.z.uuid()}).nullable()})}),M.z.strictObject({type:M.z.literal("execution_recovered"),details:M.z.strictObject({generation:M.z.number().int().positive(),reason:M.z.enum(["interrupted","expired_lease","delivery_failed"])})}),M.z.strictObject({type:M.z.literal("execution_failed"),details:M.z.strictObject({generation:M.z.number().int().positive(),code:M.z.string().regex(/^[a-z_]{1,64}$/)})}),M.z.strictObject({type:M.z.literal("run_completed"),details:M.z.strictObject({outcome:M.z.enum(["completed","ineligible","failed"])})}),M.z.strictObject({type:M.z.literal("run_closed"),details:M.z.strictObject({source:M.z.enum(["client","server","expiry"])})}),M.z.strictObject({type:M.z.literal("treatment_used"),details:M.z.strictObject({...qr,source:M.z.enum(["client","server"]),occurredAt:Qc,reference:M.z.string().min(1).max(128).optional()})})]);var fn=L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Cx=L.z.discriminatedUnion("type",[L.z.strictObject({id:fn,type:L.z.literal("owned"),publicData:Pm.optional(),document:rn.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")}),L.z.strictObject({id:fn,type:L.z.literal("paywall"),paywallVersionId:L.z.uuid()})]),Wc={kind:L.z.literal("funnel"),schemaVersion:L.z.literal(4),screens:L.z.array(Cx).max(In.pages),references:L.z.record(fn,Zc).refine(e=>Object.keys(e).length<=500),inputs:L.z.array(L.z.strictObject({variable:fn,screenId:fn,componentId:fn,required:L.z.boolean()})).max(In.questions),variables:L.z.record(ft,ri).refine(e=>Object.keys(e).length<=In.logicNodes),outputSchema:ni,execution:L.z.strictObject({runTimeoutSeconds:L.z.number().int().min(1).max(Hc.runTimeoutSeconds),maxTransitions:L.z.number().int().min(1).max(Hc.maxTransitions)})},WC=L.z.strictObject({...Wc,graph:Gc});function Px(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function Ba(e){return Array.isArray(e)?e.some(Ba):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Hm:Ba(n))}function Ex(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=Dm(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!Wi(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),Px(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&Ba(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Ba(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function pf(e,t){for(let{message:n,reason:r,path:i}of Ex(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function mf(e,t){let n=(I,p,g=[])=>t.addIssue({code:"custom",message:I,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(I=>[I.id,I])),a=(I,p)=>r.some(g=>g.type===I&&("id"in g?g.id:g.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(I=>I.type==="screen");(o.length!==i.size||o.some(I=>!i.has(I.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(I=>c.some(p=>I!==p&&p.startsWith(I+".")))&&n("Variable paths must not overlap","variable");function u(I,p){Object.hasOwn(e.variables,I)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(I)??new Set;g.add(p.id),s.set(I,g)}for(let[I,p]of e.graph.nodes.entries()){let g=["graph","nodes",I],f=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;f&&!a("flag",f)&&n("Flag selectors require an explicit GB resource reference","feature",g);let S=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):[],A="writes"in p?p.writes??{}:{};(S.length!==Object.keys(A).length||S.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[v,k]of Object.entries(A)){u(k,p);let N=e.variables[k],B=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[v]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[v]:void 0;(N?.source.type!=="node"||B&&N.type!==B)&&n("Node writer source or output type does not match declaration","variable",g)}if(p.type==="coupons"){let v=e.variables[p.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let k of p.couponIds)a("reward",k)||n("Coupons require Reward references","coupon",g)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let v=p.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),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",g),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",g),p.type==="screen"){let v=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),v?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let k=v.document.pages[0];if(!k){n("Owned screen requires a page","screen",g);continue}er(v.document).some(B=>!B.complete)&&n("Owned screens require complete local content","translations",g);let N=new Set(v.document.actions.map(B=>B.id));(N.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(B=>!N.has(B)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),Xn(k.root,B=>{!p.offering&&(B.type==="plan_picker"||(B.type==="stack"||B.type==="button")&&B.bind?.plan||B.type==="customer_data"&&["customer_plans","credit_packs"].includes(B.data.source))&&n("Product presentation requires an Offering Version","offering",g),B.type==="customer_data"&&Object.values(B.data.outputs??{}).some(fe=>fe!==void 0&&!N.has(fe))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",g),p.type==="end"&&p.output?.type==="literal"&&!dn(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!dn(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",g);let P=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(P?.type==="variable"&&!P.path){let v=e.variables[P.key];v&&!oc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let v=i.get(p.screenId);if(v?.type==="owned")for(let k of cc(v.document))(/^(input|params)\./.test(k)||k.startsWith("variables.")&&!sc(k.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let v of p.cases){for(let k of Mn(v.condition))a("saved_group",k)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let k of Zn(v.condition))k.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,k]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let N=p.value[v];if(N)if(N.source==="literal"){let B=v==="coupons"?N.value:[N.value];(!Array.isArray(B)||B.length>20||B.some(fe=>!dn({type:k,nullable:!1},fe)||!a(k,fe.id))||v==="coupons"&&new Set(B.map(fe=>fe.id)).size!==B.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...g,"value",v])}else{let B=e.variables[N.key];(N.path||!B||B.nullable||(v==="coupons"?B.type!=="array"||B.items?.type!=="reward"||B.items.nullable:B.type!==k))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[I,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...lf(p,c),...g?.type==="owned"?ua(g.document).map(S=>sc(S,c)?.key??S):[]];for(let S of new Set(f)){let k=function(N){if(N===p.id)return!0;if(v.has(N))return!1;v.add(N);let B=e.graph.nodes.find(Ie=>Ie.id===N);return B?(P.has(N)?B.type==="action"?[B.cancel,B.unavailable,B.failure]:B.type==="wait"&&B.wait.type==="event"?[B.wait.timeout]:[]:Ma(B)).some(k):!1};var w=k;if(!Object.hasOwn(e.variables,S)){n("Consumed variable is undeclared","variable",["graph","nodes",I]);continue}let A=e.variables[S];if(p.type==="screen"&&A.source.type==="input"&&e.inputs.some(N=>N.screenId===p.screenId&&N.variable===S)||A.source.type==="parameter"||A.source.type==="attribute")continue;let P=A.source.type==="input"?new Set(e.inputs.filter(N=>N.variable===S&&N.required).flatMap(N=>o.filter(B=>B.screenId===N.screenId).map(B=>B.id))):s.get(S)??new Set,v=new Set;(!P.size||k(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",I])}}(new Set(e.inputs.map(I=>I.variable)).size!==e.inputs.length||new Set(e.inputs.map(I=>`${I.screenId}:${I.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[I,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",I]);let g=i.get(p.screenId),f=g?.type==="owned"?Wi(g.document,p.componentId):null;if((f?.type!=="stack"||!f.interaction||!["input","toggle","select","multiselect","tabs"].includes(f.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",I]),f?.type==="stack"&&f.interaction){let S=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==S&&n("Input variable type does not match component","inputBinding",["inputs",I]);let A=e.variables[p.variable]?.enum;A&&!f.children.filter(P=>!P.hidden).every(P=>A.includes(P.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",I])}}for(let[I,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",I]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===I)&&n("Input variable requires a component binding","inputBinding",["variables",I]);let d=0,m=0;for(let I of e.screens)if(I.type==="owned"){for(let p of I.document.pages)Xn(p.root,()=>{d++});m+=I.document.actions.length}(d>In.components||m>In.actions||on(e)>In.documentBytes)&&n("Funnel document exceeds its budget","budget")}var Rx=L.z.strictObject({...Wc,graph:Kc}).superRefine(mf),hi=L.z.strictObject({...Wc,graph:Kc,displayName:L.z.string().trim().min(1).max(80)}).superRefine(mf),YC=hi.superRefine(pf),XC=Rx.superRefine(pf),Va=L.z.string().regex(Vt),co={requestId:L.z.uuid(),nodeId:fn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),customerToken:Va.optional()},kx=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("screen"),output:fn,answers:ir,selection:L.z.record(fn,L.z.union([L.z.string().max(200),L.z.boolean(),L.z.number().int().min(0).max(1e4)])).optional()}),L.z.strictObject({type:L.z.literal("paywall_quote"),featureQuantities:L.z.record(L.z.uuid(),L.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:fn,productVersionId:L.z.uuid(),offerId:L.z.uuid().optional(),nativeOffer:ai.optional(),predecessor:L.z.strictObject({operationId:L.z.uuid().nullable(),generation:L.z.number().int().positive()}).optional()}),L.z.strictObject({type:L.z.literal("paywall_confirm"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("paywall_cancel"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("client_action"),receiptId:L.z.uuid(),outcome:L.z.enum(["success","cancel","failure","opened","failed"])})]),jx=L.z.object({nodeId:fn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),components:L.z.record(fn,L.z.object({resourceKey:L.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:L.z.number().int().min(1).max(1e5),after:Oa.nullable(),filter:L.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Un=L.z.discriminatedUnion("operation",[L.z.strictObject({operation:L.z.literal("start"),funnelId:L.z.uuid(),requestId:L.z.uuid(),customer:Ta.optional(),customerData:Na.optional(),locale:L.z.string().min(1).max(35),parameters:or}).refine(Da,Fa),L.z.strictObject({operation:L.z.literal("get"),settlementRequestId:L.z.uuid().optional(),data:jx.optional(),purchase:L.z.strictObject({receiptId:L.z.uuid(),operationId:L.z.uuid()}).optional(),customerToken:Va.optional()}),L.z.strictObject({operation:L.z.literal("resume"),requestId:L.z.uuid(),customerToken:Va.optional()}),L.z.strictObject({operation:L.z.literal("submit"),...co,input:kx}),L.z.strictObject({operation:L.z.literal("back"),...co}),L.z.strictObject({operation:L.z.literal("shown"),...co}),L.z.strictObject({operation:L.z.literal("close"),...co}),L.z.strictObject({operation:L.z.literal("commit_segment"),...co,policyRevision:L.z.number().int().nonnegative(),generation:L.z.string().min(1).max(256)}),L.z.strictObject({operation:L.z.literal("review"),receiptId:L.z.uuid().optional(),customerToken:Va.optional()})]);function Ua(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(p){for(let g of Mn(p))d(g)}function d(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let g=t.savedGroups[p];g&&(i.add(p),c.set(p,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function m(p){for(let g of["hashAttribute","fallbackAttribute"])if(p[g]!==void 0&&Nc(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])w(g.id),u(g.condition)}function w(p,g=!1){let f=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!f){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,f),a.push(()=>{for(let S of f.rules??[]){m(S);for(let A of S.tracks??[])m(A.experiment)}}))}function I(p){let g=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,g),a.push(()=>m(g)))}for(let p of e.graph.nodes){p.type==="feature"&&w(p.featureKey,!0),p.type==="split"&&I(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&w(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&w(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var ie=require("zod");function ff(e,t){let n=[],r={};Lt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Lt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function gf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Lt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(d=>d.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}var Ai=require("zod");var hf=Ai.z.object({defaultLocale:An,locales:Ai.z.record(An,Ai.z.object({name:Ai.z.string().max(80),description:Ai.z.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 Tx=["customer_data","coupon_code"],Nx=ie.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Af=ie.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),La=(e,t)=>new Set(e.map(t)).size===e.length,Dx=ie.z.strictObject({currency:he,amountMinor:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Fx=ie.z.strictObject({featureId:ie.z.uuid(),name:ie.z.string().trim().min(1).max(120),allowance:ie.z.string().max(40).nullable(),access:ie.z.boolean()}),Mx=ie.z.strictObject({stripe:ie.z.strictObject({prices:ie.z.array(Dx).min(1).max(50)}).optional(),apple:ie.z.strictObject({productIds:ie.z.array(Nx).min(1).max(10)}).optional(),google:ie.z.strictObject({products:ie.z.array(ie.z.strictObject({productId:Af,basePlanId:Af.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!La(e.stripe.prices,n=>n.currency)||e.apple&&!La(e.apple.productIds,n=>n)||e.google&&!La(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),qx=ie.z.strictObject({name:ie.z.string().trim().min(1).max(80),interval:ie.z.enum(["free","week","month","year","one_time"]),intervalCount:ie.z.number().int().min(1).max(100),trial:ie.z.strictObject({days:ie.z.number().int().min(1).max(730),cardRequired:ie.z.boolean()}).nullable(),benefits:ie.z.array(Fx).max(50).refine(e=>La(e,t=>t.featureId),"Duplicate benefit"),channels:Mx,prepaid:ie.z.array(Hi).max(100).optional()}),Vx=ie.z.strictObject({digest:pi,content:ie.z.strictObject({discount:Wn,duration:tn,appliesTo:Gs,displayCopy:hf.nullable(),firstPurchaseOnly:ie.z.boolean(),qualificationRequired:ie.z.boolean(),startsAt:ie.z.iso.datetime().nullable(),endsAt:ie.z.iso.datetime().nullable(),grantWindowHours:ie.z.number().int().positive(),perCustomerLimit:ie.z.number().int().positive()})}),Bx=ie.z.discriminatedUnion("type",[ie.z.strictObject({type:ie.z.literal("checkout"),product:xa}),ie.z.strictObject({type:ie.z.literal("close")}),ie.z.strictObject({type:ie.z.literal("action"),action:vc})]),za=ie.z.strictObject({kind:ie.z.literal("paywall"),formatVersion:ie.z.literal(1),name:ie.z.string().trim().min(1).max(80),offeringVersionId:ie.z.uuid(),presentation:Bn,screen:rn,products:Sa,catalog:ie.z.record(ie.z.uuid(),qx),buttons:ie.z.record(Te,Bx),coupons:ie.z.record(ie.z.uuid(),Vx)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;ff(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Pc(r,Tx).forEach(n),er(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Lt(r,g=>{let f="bind"in g?g.bind:void 0;f?.promotionCode&&n("Promotion codes must not be published"),f?.plan&&i.add(f.plan),f?.coupon&&a.add(f.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(S=>i.add(S)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let d=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(f=>f.featureId)));for(let g of o)d.has(g)||n("Feature text must read a displayed benefit");let m=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let I=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;I=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(S=>!u.has(S))&&n("Checkout may only sell displayed Products")}I||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),yf=ie.z.strictObject({state:ie.z.enum(["published","archived"]),controlRevision:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ie.z.uuid(),versions:ie.z.record(ie.z.uuid(),ie.z.strictObject({version:ie.z.number().int().positive(),artifact:ie.z.string().min(1),sourceDigest:ie.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Zt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Yc=Oe.z.string().regex(/^[a-f0-9]{64}$/),Xc=Oe.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),eu=ze.extend({environmentId:Oe.z.uuid()}),bf=Oe.z.strictObject({features:Oe.z.array(Oe.z.string()).max(500),experiments:Oe.z.record(Oe.z.uuid(),Oe.z.array(Oe.z.string()).max(20)),savedGroups:Oe.z.array(Oe.z.string()).max(1e3)}),tu=Oe.z.strictObject({kind:Oe.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Oe.z.number().int().positive(),url:Oe.z.string().min(1).max(2048),sha256:Yc,byteLength:Oe.z.number().int().positive().max(Zt.maxArtifactBytes),generation:Yc.optional()}),Ux=Oe.z.strictObject({state:Oe.z.enum(["active","paused","archived"]),controlRevision:Xc,evaluationMode:Oe.z.enum(["local","remote"]),evaluationRevision:Xc,currentVersionId:Oe.z.uuid(),versions:Oe.z.record(Oe.z.uuid(),Oe.z.strictObject({artifact:Oe.z.string(),dependencies:bf,definitionDigest:pi.optional(),couponDigests:Oe.z.record(Oe.z.uuid(),pi).optional()}))}),nu=Oe.z.strictObject({kind:Oe.z.literal("sdk_configuration"),schemaVersion:Oe.z.literal(1),scope:eu,revision:Xc,generation:Yc,policy:Oe.z.strictObject({refreshIntervalSeconds:Oe.z.number().positive().max(15),maxControlAgeSeconds:Oe.z.number().positive().max(60)}),gb:Oe.z.strictObject({features:Oe.z.string().nullable(),pageExperiments:Oe.z.string().nullable()}),artifacts:Oe.z.record(Oe.z.string(),tu),funnels:Oe.z.record(Oe.z.uuid(),Ux),paywalls:Oe.z.record(Oe.z.uuid(),yf).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 It(e){if(Array.isArray(e))return`[${e.map(It).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)}:${It(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function ru(e){return Qr(Jr(typeof e=="string"?new TextEncoder().encode(e):e))}function Sf(e){return ru(It(e))}function xf(e,t){for(let o of Object.values(e.references))if(o.type==="flag"&&(!Object.hasOwn(t.features,o.key)||t.remoteFeatures.includes(o.key))||o.type==="experiment"&&!Object.hasOwn(t.experiments,o.id)||o.type==="saved_group"&&!Object.hasOwn(t.savedGroups,o.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=Ua(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let o of e.graph.nodes){let s=o.type==="feature"?o.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=o.type==="feature"?e.variables[o.writes.value]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(m=>[...Object.hasOwn(m,"force")?[m.force]:[],...m.variations??[],...(m.tracks??[]).flatMap(w=>w.experiment.variations)])].some(m=>m===void 0||!dn(u,m)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of Mn(o)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&a(c.condition)}};for(let o of e.graph.nodes)if(o.type==="condition")for(let s of o.cases)a(s.condition);for(let o of Object.values(n.features))for(let s of o.rules??[]){a(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}for(let c of s.tracks??[])a(c.experiment.condition)}for(let o of Object.values(n.experiments)){a(o.condition);for(let s of o.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");a(s.condition)}}for(let o of e.graph.nodes)if(o.type==="split"){let s=n.experiments[o.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!o.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return bf.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([o,s])=>[o,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function If(e){return hi.parse(e)}var vf=ht.z.strictObject({...oi,selector:ht.z.discriminatedUnion("type",[ht.z.strictObject({type:ht.z.literal("paywall"),paywallId:ht.z.uuid()}),ht.z.strictObject({type:ht.z.literal("version"),versionId:ht.z.uuid()})]),customerId:ht.z.uuid().optional(),commerce:ei,locale:ht.z.string().min(1).max(35),requirement:Yn.optional()}),uo=ht.z.strictObject({id:ht.z.uuid(),paywallId:ht.z.uuid(),version:ht.z.number().int().positive(),document:di.omit({requirement:!0,offeringId:!0}),offering:ht.z.strictObject({id:ht.z.uuid()}),content:ht.z.strictObject({environmentId:ht.z.uuid(),offeringVersionId:ht.z.uuid(),artifact:tu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:ti,check:kr.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"})}),Vr=ht.z.strictObject(uo.shape).omit({document:!0,offering:!0}).extend({content:uo.shape.content.unwrap()});function wf(e,t){let n=za.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 o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return uo.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}})}var Dt=require("zod");var Of={requestId:Dt.z.uuid(),sourceId:Dt.z.uuid(),expectedAvailable:Ut},_f=Dt.z.discriminatedUnion("action",[Dt.z.strictObject({...Of,action:Dt.z.enum(["add","subtract","set_remaining"]),amount:ge}),Dt.z.strictObject({...Of,action:Dt.z.literal("edit"),granted:ge,expiresAt:Dt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Dt.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Dt.z.number().int().nonnegative()})]),iu=Dt.z.strictObject({sourceId:Dt.z.uuid(),available:Ut,held:Ut,spent:Ut,adjustmentGrantId:Dt.z.uuid().nullable()}),Cf=iu.extend({granted:Ut,expiresAt:Dt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Dt.z.iso.datetime({offset:!0}).nullable(),revision:Dt.z.number().int().nonnegative()});var Wt=require("zod"),Pf=Wt.z.discriminatedUnion("action",[Wt.z.object({action:Wt.z.literal("upsert"),externalId:Wt.z.string().min(1).max(128),name:Wt.z.string().trim().min(1).max(80)}).strict(),Wt.z.object({action:Wt.z.literal("archive"),entityId:Wt.z.uuid()}).strict()]),Ef=Wt.z.object({id:Wt.z.uuid(),externalId:Wt.z.string().min(1).max(128),name:Wt.z.string().min(1).max(80),archived:Wt.z.boolean()}).strict();var jt=require("zod");var ar=require("zod"),kf=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Rf=ar.z.string().regex(/.+\/.+/),ou=ar.z.number().min(-100),Br=ar.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Lx=ar.z.strictObject({input:Br,output:Br,cache_read:Br.optional(),cache_write:Br.optional(),reasoning:Br.optional(),input_audio:Br.optional(),output_audio:Br.optional()}),au=(e,t)=>ar.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),zP=ar.z.strictObject({defaultMarkup:ou,providerMarkups:au(ar.z.string().min(1),ou),modelMarkups:au(Rf,ou),customModels:au(Rf,Lx.partial())});var pe=require("zod"),Ur=pe.z.iso.datetime({offset:!0}),sr=pe.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),zx=pe.z.discriminatedUnion("kind",[pe.z.object({kind:pe.z.literal("absolute"),from:Ur,to:Ur}).strict(),pe.z.object({kind:pe.z.literal("last_days"),days:pe.z.union([pe.z.literal(1),pe.z.literal(7),pe.z.literal(30),pe.z.literal(90)])}).strict(),pe.z.object({kind:pe.z.literal("billing_cycles"),membershipId:pe.z.uuid(),count:pe.z.number().int().min(1).max(12),includeCurrent:pe.z.boolean()}).strict()]),jf=pe.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"),$x=pe.z.object({key:pe.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:pe.z.array(pe.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Lr=pe.z.object({range:zx,timezone:jf,filterBy:pe.z.array($x).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:pe.z.enum(["hour","day","week","month"]),internal_feature_id:pe.z.uuid().nullable(),entityId:pe.z.uuid().nullable(),topN:pe.z.number().int().min(1).max(50).nullable(),groupBy:pe.z.union([pe.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),pe.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:pe.z.object({bucket:Ur,group:pe.z.string().max(240),isOther:pe.z.boolean(),internal_feature_id:pe.z.uuid(),resourceId:pe.z.uuid()}).strict().nullable(),limit:pe.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)"})}),Tf=pe.z.object({from:Ur,to:Ur,interval:pe.z.enum(["hour","day","week","month"]),timezone:jf,rows:pe.z.array(pe.z.object({bucket:Ur,group:pe.z.string().max(240),isOther:pe.z.boolean(),internal_feature_id:pe.z.uuid(),resourceId:pe.z.uuid(),consumedUnits:sr,refundedUnits:sr,reservedUnits:sr,charged:sr,refunded:sr,reserved:sr,netUnits:sr,netCharged:sr}).strict()).max(100),nextCursor:pe.z.object({bucket:Ur,group:pe.z.string().max(240),isOther:pe.z.boolean(),internal_feature_id:pe.z.uuid(),resourceId:pe.z.uuid()}).strict().nullable()}).strict();var yi=jt.z.string().regex(/^(0|[1-9]\d{0,29})$/),Nf=jt.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),su=jt.z.strictObject({bucket:jt.z.iso.datetime({offset:!0}),group:jt.z.string().max(240),isOther:jt.z.boolean(),internal_feature_id:jt.z.uuid()}),Df=jt.z.strictObject({...Lr.shape,groupBy:jt.z.union([jt.z.enum(["customer","entity","entitlement"]),jt.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:su.nullable()}).superRefine((e,t)=>{let n=Lr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Ff=jt.z.strictObject({from:jt.z.iso.datetime({offset:!0}),to:jt.z.iso.datetime({offset:!0}),interval:Lr.shape.interval,timezone:Lr.shape.timezone,rows:jt.z.array(jt.z.strictObject({...su.shape,eventCount:yi,units:Nf,tokenEventCount:yi,tokens:jt.z.strictObject(Object.fromEntries(kf.map(e=>[e,yi]))),totalTokens:yi,providerCostEventCount:yi,providerCostUsd:Nf,invalidTelemetryEventCount:yi})).max(100),nextCursor:su.nullable()});var ut=require("zod");var Mf=ut.z.object({requestId:ut.z.uuid(),items:ut.z.array(ut.z.object({customerId:ut.z.uuid(),command:Ui.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"),qf=ut.z.object({batchId:ut.z.uuid(),after:ut.z.number().int().min(-1).max(999),limit:ut.z.number().int().min(1).max(100)}).strict(),Vf=ut.z.object({batchId:ut.z.uuid(),status:ut.z.enum(["queued","complete"]),total:ut.z.number().int().min(1).max(1e3),processed:ut.z.number().int().min(0).max(1e3),items:ut.z.array(ut.z.object({position:ut.z.number().int().min(0).max(999),customerId:ut.z.uuid(),idempotencyKey:ut.z.string().min(1).max(120),status:ut.z.enum(["queued","accepted","rejected","failed"]),receipt:Li.nullable(),errorCode:ut.z.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:ut.z.number().int().min(0).max(999).nullable()}).strict();var E=require("zod");var Gx=E.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Bf=E.z.enum(["draft","active","paused","archived"]),Uf=E.z.string().min(1).max(256),Lf=E.z.array(Uf).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Kx=E.z.strictObject({duration:E.z.enum(["day","week","month","year"]),length:E.z.number().int().min(1).max(3660)}),Hx=E.z.strictObject({internal_feature_id:E.z.uuid(),allowance:E.z.number().nonnegative().max(1e15).nullable(),expiry:Kx.nullable()}),Qx=E.z.discriminatedUnion("type",[E.z.strictObject({type:E.z.literal("feature_grant"),grants:E.z.array(Hx).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),E.z.strictObject({type:E.z.literal("free_product"),productId:Uf,duration:tn}),E.z.strictObject({type:E.z.literal("invoice_credits"),amount:E.z.number().positive().max(1e8),duration:tn,rollover:E.z.boolean(),productIds:Lf})]),Jx=E.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),zf=E.z.object({key:Jx,name:E.z.string().trim().min(1).max(80),configuration:Qx}).strict(),$f=E.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),cu=E.z.object({code:$f,maxUses:E.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:E.z.boolean()}).strict(),Gf=E.z.object({key:E.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:E.z.string().trim().min(1).max(80),rewardId:E.z.uuid(),redeemOn:E.z.enum(["customer_creation","checkout"]),receivedBy:E.z.enum(["referrer","all"]),maxRedemptions:E.z.number().int().min(1).max(1e6).nullable(),productIds:Lf,excludeTrial:E.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Kf={id:E.z.uuid(),projectId:E.z.uuid(),environmentId:E.z.uuid(),revision:E.z.number().int().nonnegative(),status:Bf,createdAt:E.z.iso.datetime({offset:!0}),updatedAt:E.z.iso.datetime({offset:!0})},Zx=zf.extend(Kf).strict(),Wx=Gf.safeExtend(Kf).strict(),XP=E.z.strictObject({id:E.z.uuid(),key:E.z.string(),name:E.z.string(),type:Gx,status:Bf}),eE=E.z.discriminatedUnion("action",[E.z.object({action:E.z.literal("save"),id:E.z.uuid().nullable(),revision:E.z.number().int().nonnegative(),input:zf}).strict(),E.z.object({action:E.z.enum(["activate","pause","resume","archive","delete"]),id:E.z.uuid(),revision:E.z.number().int().nonnegative()}).strict()]),tE=E.z.discriminatedUnion("action",[E.z.object({action:E.z.literal("save"),id:E.z.uuid().nullable(),revision:E.z.number().int().nonnegative(),input:Gf}).strict(),E.z.object({action:E.z.enum(["activate","pause","resume","archive","delete"]),id:E.z.uuid(),revision:E.z.number().int().nonnegative()}).strict()]),Hf=E.z.object({id:E.z.uuid(),rewardId:E.z.uuid(),programId:E.z.uuid().nullable(),customerId:E.z.uuid(),referrerId:E.z.uuid().nullable(),status:E.z.enum(["pending","applied","unavailable"]),result:E.z.record(E.z.string(),E.z.unknown()).nullable(),createdAt:E.z.iso.datetime({offset:!0})}).strict(),Qf=E.z.object({code:$f,requestId:E.z.uuid()}).strict(),Jf=E.z.strictObject({redemptionId:E.z.uuid(),currency:he,requestId:E.z.uuid(),accepted:E.z.literal(!0)}),Yx=E.z.strictObject({type:E.z.literal("checkout"),orderId:E.z.uuid(),productVersionId:E.z.uuid(),currency:he,duration:tn,renewalAmountMinor:E.z.number().int().positive().max(1e8),status:E.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:E.z.url().nullable()}),Zf=E.z.discriminatedUnion("type",[Yx,E.z.strictObject({type:E.z.literal("subscription"),operationId:E.z.uuid(),membershipId:E.z.uuid(),productVersionId:E.z.uuid(),currency:he,duration:tn,renewalAmountMinor:E.z.number().int().positive().max(1e8),status:E.z.enum(["pending","running","applied","failed"])})]),Wf=E.z.object({programId:E.z.uuid(),requestId:E.z.uuid()}).strict(),Yf=E.z.object({id:E.z.uuid(),programId:E.z.uuid(),code:cu.shape.code,createdAt:E.z.iso.datetime({offset:!0})}).strict(),nE=E.z.object({rows:E.z.array(Zx).max(100),nextCursor:E.z.uuid().nullable()}).strict(),rE=E.z.object({rows:E.z.array(Wx).max(100),nextCursor:E.z.uuid().nullable()}).strict(),Xx=cu.extend({id:E.z.uuid(),redemptions:E.z.number().int().nonnegative()}).strict(),e0=E.z.strictObject({id:E.z.uuid(),programId:E.z.uuid().nullable(),customerId:E.z.uuid().nullable(),referrerId:E.z.uuid().nullable(),code:E.z.string().nullable(),status:E.z.enum(["pending","triggered","applied"]),createdAt:E.z.iso.datetime({offset:!0})}),iE=E.z.object({codes:E.z.array(Xx).max(100),redemptions:E.z.array(e0).max(100),customers:E.z.record(E.z.uuid(),E.z.string()),codesCursor:E.z.uuid().nullable(),redemptionsCursor:E.z.uuid().nullable()}).strict(),oE=E.z.discriminatedUnion("action",[E.z.object({action:E.z.literal("create"),rewardId:E.z.uuid(),revision:E.z.number().int().nonnegative(),input:cu}).strict(),E.z.object({action:E.z.literal("remove"),rewardId:E.z.uuid(),revision:E.z.number().int().nonnegative(),codeId:E.z.uuid()}).strict()]);var x=require("zod");var Z=require("zod"),En={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},lo=e=>new Set(e).size===e.length,uu=Z.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),t0=Z.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),po=Z.z.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"))),n0=Z.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Xf=Z.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var eg=Z.z.strictObject({id:Z.z.uuid(),repo:t0,platform:Z.z.enum(["github","gitlab","bitbucket"]),branches:Z.z.array(po).min(1).max(4).refine(lo),workflow:Z.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.z.array(Z.z.uuid()).min(1).max(4).refine(lo),include:Z.z.array(Xf).min(1).max(16),exclude:Z.z.array(Xf).max(16),methods:Z.z.array(Z.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(lo),maxAgeHours:Z.z.number().int().min(1).max(720)}),tg=eg.extend({revision:Z.z.number().int().positive()}),sE=Z.z.strictObject({repository:eg,expectedRevision:Z.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),ng=Z.z.strictObject({repositoryId:Z.z.uuid(),branch:po}),r0=Z.z.array(uu).max(En.keys).refine(lo),rg=Z.z.strictObject({repository:tg.omit({keyIds:!0}),branch:po,keys:r0,keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/)}),i0=Z.z.strictObject({filePath:n0,startingLineNumber:Z.z.number().int().min(1).max(1e7)}),lu=Z.z.strictObject({protocol:Z.z.literal(1),repositoryId:Z.z.uuid(),branch:po,workflow:Z.z.string().max(200),configurationRevision:Z.z.number().int().positive(),keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/),commit:Z.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.z.uuid(),runNumber:Z.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.z.number().int().min(1).max(1e4),scannerVersion:Z.z.literal("1"),scannedAt:Z.z.iso.datetime({offset:!0}),coverage:Z.z.strictObject({complete:Z.z.literal(!0),files:Z.z.number().int().min(0).max(En.files),sourceBytes:Z.z.number().int().min(0).max(En.sourceBytes),unresolvedCalls:Z.z.number().int().min(0).max(1e6),unsupportedFiles:Z.z.number().int().min(0).max(En.files)}),features:Z.z.array(Z.z.strictObject({key:uu,refs:Z.z.array(i0).max(En.referencesPerKey)})).max(En.keys)}).superRefine((e,t)=>{lo(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)>En.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),du=Z.z.strictObject({scanId:Z.z.uuid(),commit:Z.z.string(),receivedAt:Z.z.string(),references:Z.z.number().int().nonnegative(),removedReferences:Z.z.number().int().nonnegative()}),o0=du.extend({repositoryId:Z.z.uuid(),branch:po,workflow:Z.z.string(),digest:Z.z.string(),configurationRevision:Z.z.number().int().positive(),runNumber:Z.z.number().int().positive(),runAttempt:Z.z.number().int().positive(),scannedAt:Z.z.string(),keySetHash:Z.z.string(),coverage:lu.shape.coverage}),a0=Z.z.strictObject({repositories:Z.z.array(tg).max(En.repositories),scans:Z.z.array(o0).max(En.repositories*En.branches)}),s0=Z.z.strictObject({key:uu,references:Z.z.number().int().nonnegative(),coveredTargets:Z.z.number().int().nonnegative(),expiredTargets:Z.z.number().int().nonnegative(),uncertainTargets:Z.z.number().int().nonnegative()}),cE=Z.z.strictObject({available:Z.z.boolean().default(!0),settings:a0,expectedTargets:Z.z.number().int().min(0).max(80),features:Z.z.array(s0).max(2001),truncated:Z.z.boolean()});var At=require("zod");var c0=At.z.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"]),u0=At.z.strictObject({provider:At.z.literal("stripe"),accountId:At.z.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:At.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:c0,occurredAt:At.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:At.z.record(At.z.string(),At.z.unknown()).and(At.z.object({id:At.z.string().min(1).max(255),object:At.z.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:At.z.boolean()}))}),ig=At.z.union([u0,pl]),og=At.z.strictObject({id:At.z.uuid(),eventId:At.z.string().min(1).max(200),source:At.z.literal("merchant"),providerVerified:At.z.literal(!1),outcome:At.z.string().min(1).max(100)});var Ft=require("zod"),sg={customerId:Ft.z.uuid(),eventId:Ft.z.string().trim().min(1).max(200),grantId:Ft.z.uuid(),occurredAt:Ft.z.iso.datetime({offset:!0})},cg=Ft.z.strictObject({...sg,productVersionId:Ft.z.uuid(),subscriptionId:Ft.z.string().trim().min(1).max(255)}),ug=Ft.z.strictObject({...sg,merchandiseId:Ft.z.uuid()}),lg=Ft.z.union([cg,ug]),ag={id:Ft.z.uuid(),couponId:Ft.z.uuid(),status:Ft.z.literal("redeemed"),source:Ft.z.literal("merchant"),recordedAt:Ft.z.iso.datetime({offset:!0})},dg=Ft.z.union([cg.extend(ag),ug.extend(ag)]);var re=require("zod");var pu=re.z.strictObject({name:re.z.string().trim().min(1).max(255),memo:re.z.string().max(1e4).nullable().optional(),footer:re.z.string().max(1e4).nullable().optional(),net_terms_days:re.z.number().int().positive().nullable().optional()}),l0=pu.extend({id:re.z.string().min(1).max(255),created_at:re.z.number().nullable()}),pg=re.z.strictObject({items:re.z.array(l0).max(50),nextCursor:re.z.uuid().nullable()}),fE=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),values:pu}),re.z.strictObject({action:re.z.literal("update"),id:re.z.string().min(1).max(255),values:pu}),re.z.strictObject({action:re.z.literal("delete"),id:re.z.string().min(1).max(255)})]),mg=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),params:si}),re.z.strictObject({action:re.z.enum(["finalize","send","pay","void"]),requestId:re.z.uuid(),invoiceId:re.z.uuid()}),re.z.strictObject({action:re.z.literal("reissue"),requestId:re.z.uuid(),invoiceId:re.z.uuid(),params:pc})]),mu=re.z.strictObject({id:re.z.uuid(),customerId:re.z.uuid(),providerInvoiceId:re.z.string().nullable(),status:re.z.enum(["draft","open","paid","void","uncollectible"]),currency:re.z.string(),totalMinor:re.z.string().regex(/^-?\d+$/),paidMinor:re.z.string().regex(/^\d+$/),refundedMinor:re.z.string().regex(/^\d+$/),hostedInvoiceUrl:re.z.url().nullable(),createdAt:re.z.number(),collectionMethod:re.z.enum(["send_invoice","charge_automatically"]).nullable()}),fg=mu.extend({lines:re.z.array(re.z.strictObject({id:re.z.uuid(),description:re.z.string(),amountMinor:re.z.string().regex(/^-?\d+$/),netAmountMinor:re.z.string().regex(/^-?\d+$/),quantity:re.z.number().nullable(),periodStart:re.z.number().nullable(),periodEnd:re.z.number().nullable()})).max(1e3)}),bi=re.z.strictObject({taskId:re.z.uuid(),status:re.z.enum(["ready","running","done","dead"]),invoice:mu.nullable(),errorCode:re.z.string().nullable()}),gg=re.z.strictObject({items:re.z.array(mu).max(50),nextCursor:re.z.uuid().nullable(),operations:re.z.array(bi).max(50),operationsLimited:re.z.boolean()});var d0=x.z.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"]),hg={scope:ze,permissions:x.z.array(d0),expiresAt:x.z.iso.datetime().nullable()},iR=x.z.discriminatedUnion("kind",[x.z.object({...hg,kind:x.z.literal("server"),keyId:x.z.string().min(1)}),x.z.object({...hg,kind:x.z.literal("customer"),customerId:x.z.string().min(1),identityKind:x.z.enum(["identified","guest"]),expiresAt:x.z.iso.datetime()})]),z=x.z.object({requestId:x.z.uuid(),scope:ze}).strict(),p0=Xm.safeExtend({fingerprint:ja.optional()}).strict(),m0=z.extend({customer:fi,created:x.z.boolean()});function Ag(){return z.extend({offer:Di.nullable(),reason:yd.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:cp,response:z.extend({message:x.z.object({messageId:x.z.uuid(),channel:Ki,acceptedAt:x.z.iso.datetime({offset:!0}),status:x.z.enum(["accepted","sending","completed","canceled"]),replayed:x.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:x.z.strictObject({messageId:x.z.uuid()}),response:z.extend({message:x.z.object({id:x.z.uuid(),channel:Ki,status:x.z.enum(["accepted","sending","completed","canceled"]),deliveries:x.z.array(x.z.object({id:x.z.uuid(),status:lp,attempts:x.z.number().int().nonnegative(),receipts:x.z.array(x.z.object({kind:dp,occurredAt:x.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Ju,response:z.extend({installation:br})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Zu,response:z.extend({installation:br})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Oo,response:z.extend({installation:br})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:x.z.strictObject({channel:Ki}),response:z.extend({preference:ds})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:up,response:z.extend({preference:ds})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:x.z.strictObject({cursor:x.z.uuid().optional()}),response:z.extend({templates:pg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),params:si}),response:z.extend({preview:mc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),requestId:x.z.uuid(),params:si}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:bi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:mg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:bi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),taskId:x.z.uuid()}),response:z.extend({operation:bi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),cursor:x.z.uuid().optional()}),response:z.extend({invoices:gg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),invoiceId:x.z.uuid()}),response:z.extend({invoice:fg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:ng,response:z.extend({config:rg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:lu,response:z.extend({receipt:du})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:x.z.strictObject({}),response:z.extend({payload:io})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:km,response:z.merge(Ia)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:jm,response:z.merge(Tm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),sourceId:x.z.uuid()}),response:z.extend({balance:Cf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:_f}),response:z.extend({balance:iu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:x.z.strictObject({internal_feature_id:x.z.uuid(),customerId:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:x.z.uuid(),config:_s,model_markups:Fo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),query:ta}),response:z.extend({usage:zi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:Xd}),response:z.extend({usage:zi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:Hd}),response:z.extend({grant:Js})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Qd,response:z.extend({grants:Jd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:x.z.union(bm.options.map(e=>e.extend({customerId:x.z.uuid().optional(),customerToken:x.z.string().regex(Vt).optional()}))),response:z.extend({operation:Sm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:cm.extend({customerId:x.z.uuid().optional()}),response:z.extend({setup:yc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:um.extend({customerId:x.z.uuid().optional()}),response:z.extend({setup:yc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:om.safeExtend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ga.extend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ga.extend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ga.extend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:x.z.discriminatedUnion("action",[ha.options[0].extend({customerId:x.z.uuid()}),ha.options[1].extend({customerId:x.z.uuid()}),ha.options[2].extend({customerId:x.z.uuid()})]),response:z.extend({trial:Ac})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:am.extend({customerId:x.z.uuid()}),response:z.extend({trial:Ac})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ba,response:z.extend({subscriptions:hm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ba,response:z.extend({purchases:Am})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:mm,response:z.extend({conflicts:ym})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:fm,response:z.extend({resolution:gm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:dm,response:z.extend({verification:pm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Wp.safeExtend({...oi,customerId:x.z.uuid().optional()}),response:z.extend({quote:ci})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:ig,response:z.extend({record:og})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional(),intent:x.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:ui})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional()}),response:z.extend({operation:ui})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:em.safeExtend({customerId:x.z.uuid().optional()}),response:z.extend({quote:nm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional(),intent:x.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:fc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional()}),response:z.extend({operation:fc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:rm.safeExtend({customerId:x.z.uuid()}),response:z.extend({quote:gc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Dr.extend({customerId:x.z.uuid()}),response:z.extend({operation:fa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Dr.extend({customerId:x.z.uuid()}),response:z.extend({operation:fa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:jd,response:z.extend({controls:Hs})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Od,response:z.extend({prepared:Cd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Pd,response:z.extend({authorization:Wo})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Md,response:z.extend({coupons:qd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Ed,response:z.extend({authorization:Wo})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Dd,response:z.extend({invoices:Fd})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Nd.extend({customerId:x.z.uuid()}),response:z.extend({operation:bi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Td,response:z.extend({invoice:qi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:kd}).strict(),response:z.extend({controls:Hs})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Pf}).strict(),response:z.extend({entity:Ef})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid().nullable(),query:Df}),response:z.extend({analytics:Ff})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:x.z.object({customerId:x.z.uuid().nullable(),query:Lr}).strict(),response:z.extend({analytics:Tf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Mf,response:z.extend({batchId:x.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:qf,response:z.extend({batch:Vf})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:gp.extend({customerId:x.z.string().min(1).optional()}),response:z.extend({check:kr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:x.z.strictObject({kind:nr,selector:x.z.discriminatedUnion("type",[x.z.strictObject({type:x.z.literal("resource"),id:x.z.uuid()}),x.z.strictObject({type:x.z.literal("version"),id:x.z.uuid()})]),customerId:x.z.string().min(1).optional()}),response:z.extend({content:uc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:vf,response:z.extend({paywall:Vr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:x.z.strictObject({...oi,selector:wm,customerId:x.z.string().min(1).optional(),commerce:ei,requirement:Yn.optional()}),response:z.extend({offering:Om,candidates:x.z.array(ec).max(20),availability:x.z.array(x.z.strictObject({productVersionId:x.z.uuid(),available:x.z.boolean(),reason:x.z.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:kr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).strict(),response:z.extend({holdings:ep})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),query:np}).strict(),response:z.extend({ledger:rp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Zd.extend({customerId:x.z.uuid().optional()}),response:z.extend({detail:Wd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Zs.safeExtend({customerId:x.z.uuid().optional()}),response:z.extend({statement:Yd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),command:Ui.options[0]}).strict(),response:z.extend({quote:$d})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:x.z.union([x.z.strictObject({eventName:x.z.string().min(1),quantity:ge.optional(),properties:St.optional(),entityId:x.z.uuid().optional(),idempotencyKey:x.z.string().min(1).max(120)}),x.z.strictObject({internal_feature_id:x.z.uuid(),quantity:ge.optional(),properties:St.optional(),entityId:x.z.uuid().optional(),idempotencyKey:x.z.string().min(1).max(120)})])}),response:z.extend({receipts:x.z.array(Li).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Ui.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Li})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Qf,response:z.extend({redemption:Hf})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Wf,response:z.extend({referralCode:Yf})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Jf,response:z.extend({checkout:Zf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:op,response:z.extend({seats:Xs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:ap,response:z.extend({seats:Xs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:p0,response:m0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Lc,response:z.extend({customer:fi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:nf,response:z.extend(rf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:tf,response:z.extend(ef.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:x.z.object({customerId:x.z.uuid()}).strict(),response:z.extend(Kn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:x.z.strictObject({}),response:z.extend(Kn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),sessionId:x.z.uuid().optional()}),response:z.extend({revoked:x.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ja.optional()}),response:z.extend({customerId:x.z.uuid(),guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:x.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Kn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:x.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:x.z.uuid()}),response:z.extend({customer:fi,switched:x.z.boolean(),replayed:x.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:x.z.strictObject({code:x.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:x.z.uuid()}),response:Ag()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:x.z.object({}).strict(),response:z.extend({offers:x.z.array(Di)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:x.z.object({customerId:x.z.string().min(1).max(255).optional(),couponId:x.z.uuid(),...oi,requestId:x.z.uuid(),couponContentDigest:x.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Ag()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:lg,response:z.extend({receipt:dg})}},oR={sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,recordCouponRedemption:O.recordCouponRedemption,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};var $a=require("zod");var mo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function fu(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(d=>Qt(t.attributes??{},d.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new mo("Required GB Feature is unavailable");i=Fn(e.featureKey,t),o=i.value,Object.assign(r,ii(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new mo("Required GB Experiment is unavailable");if(a=Jo(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new mo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Fn(e.configuration.featureKey,t).value;o={type:"offering_version",id:$a.z.uuid().parse(u)},Object.assign(r,ii(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,ii(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function yg(e,t,n){$a.z.uuid().parse(e),$a.z.number().int().nonnegative().parse(t);let r=Qr(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)}`}var K=require("zod");var cr=K.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),f0=K.z.enum(["running","waiting","completed","closed","ineligible","failed"]),g0=K.z.discriminatedUnion("type",[Bc,K.z.strictObject({type:K.z.literal("wait"),receiptId:K.z.uuid(),kind:K.z.enum(["timer","event","operation"]),deadline:K.z.iso.datetime({offset:!0}).nullable(),eventName:cr.optional()}),K.z.strictObject({type:K.z.literal("open_url"),receiptId:K.z.uuid(),url:zc,openIn:$c}),K.z.strictObject({type:K.z.literal("event"),receiptId:K.z.uuid(),event:cr})]),Ga=K.z.strictObject({type:K.z.literal("funnel"),id:K.z.uuid(),versionId:K.z.uuid()}),h0={id:cr,presentation:Bn,outputs:K.z.array(cr).max(250),inputs:_a,values:K.z.record(K.z.string(),Ae).optional(),offeringKey:ft.optional(),capabilities:ti,customerData:Ip,dataCursors:K.z.record(cr,Oa.nullable())},A0=K.z.strictObject({...h0,content:K.z.strictObject({type:K.z.literal("document"),document:rn})}),gu=K.z.strictObject({id:K.z.uuid(),source:Ga,revision:K.z.number().int().nonnegative(),visit:K.z.number().int().nonnegative(),nodeId:cr,nodeType:K.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:f0,stopped:K.z.boolean(),canBack:K.z.boolean(),authenticated:K.z.boolean(),locale:K.z.string().min(1).max(35),answers:ir,parameters:or,variables:K.z.record(K.z.string(),Ae),output:Ae.nullable(),screen:A0.nullable(),paywall:K.z.strictObject({receiptId:K.z.uuid(),resolution:K.z.union([uo,Vr]),quote:ci.nullable(),operation:ui.nullable(),purchaseRequestId:K.z.uuid().nullable(),selectionGeneration:K.z.number().int().nonnegative().optional(),canReselect:K.z.boolean().optional()}).nullable(),instruction:g0.nullable(),pendingRequest:K.z.strictObject({requestId:K.z.uuid(),authenticationRequired:K.z.boolean()}).nullable(),runExpiresAt:K.z.iso.datetime({offset:!0}),credentialExpiresAt:K.z.iso.datetime({offset:!0}).nullable()}),fo=K.z.strictObject({scope:ze,run:gu,settlement:K.z.strictObject({requestId:K.z.uuid(),state:K.z.enum(["pending","unknown","settled"]),operationId:K.z.uuid().nullable(),receiptId:K.z.uuid().nullable().optional()}).optional(),purchase:K.z.strictObject({receiptId:K.z.uuid(),quote:ci.nullable(),operation:ui.nullable(),canReselect:K.z.boolean().optional()}).optional(),review:K.z.strictObject({activeOperationId:K.z.uuid().nullable(),pages:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),nodeId:cr,visit:K.z.number().int().nonnegative()})).max(100),page:K.z.strictObject({receiptId:K.z.uuid(),nodeId:cr,visit:K.z.number().int().nonnegative(),document:rn,answers:ir,inputs:_a,values:K.z.record(K.z.string(),Ae).optional()}).nullable(),coupons:K.z.array(K.z.strictObject({grantId:K.z.uuid(),status:K.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:K.z.string().nullable()})).max(100),purchases:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),operationId:K.z.uuid(),status:K.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:K.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:K.z.uuid().optional()}),bg=fo.extend({run:gu.extend({paywall:gu.shape.paywall.unwrap().extend({resolution:Vr}).nullable()})});var Sg="X-Indiana-Server-Key";var Re=require("zod");var Si=Re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ig=Re.z.strictObject({entry:Si,nodes:Re.z.array(Re.z.strictObject({id:Si,type:Re.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Re.z.record(Re.z.string(),Si),writes:Re.z.record(ft,ft),resources:Re.z.strictObject({screenId:Si.optional(),paywallVersionId:Re.z.uuid().optional(),couponId:Re.z.uuid().optional(),couponIds:Re.z.array(Re.z.uuid()).max(20).optional(),experimentId:Re.z.uuid().optional(),featureKey:Re.z.string().optional(),offeringVersionId:Re.z.uuid().optional()})})).min(1).max(500)}),xg={scope:ze,funnelId:Re.z.uuid(),versionId:Re.z.uuid(),evaluationRevision:Re.z.number().int().nonnegative(),expiresAt:Re.z.iso.datetime({offset:!0}).nullable(),topology:Ig},Ka=Re.z.discriminatedUnion("evaluationMode",[Re.z.strictObject({...xg,evaluationMode:Re.z.literal("local"),growth:pn,conditions:Re.z.record(Si,Re.z.array(Re.z.strictObject({condition:Ht,port:Re.z.string()})))}),Re.z.strictObject({...xg,evaluationMode:Re.z.literal("remote")})]),y0=Ka.options[0].extend({evaluation:Re.z.strictObject({maxTransitions:Re.z.number().int().min(1).max(1e4),variables:Re.z.record(ft,ri),outputSchema:ni,terminals:Re.z.record(Si,Re.z.strictObject({outcome:Re.z.enum(["completed","closed","ineligible","failed"]),output:ao.nullable()}))})});function b0(e){return Ig.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Re.z.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 hu(e){let t=hi.parse(e.document),n=e.evaluationMode==="local"?pn.parse(e.payload):null;if(n&&(n.scope.projectId!==e.scope.projectId||n.scope.environment!==e.scope.environment))throw new Error("GB payload belongs to another App or environment");let r={scope:e.scope,funnelId:e.funnelId,versionId:e.versionId,evaluationRevision:e.evaluationRevision,evaluationMode:e.evaluationMode,expiresAt:n?.expiresAt??null,topology:b0(t)};return Ka.parse(e.evaluationMode==="remote"?r:{...r,growth:Ua(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function vg(e){let t=hu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=hi.parse(e.document);return y0.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}]]}))}})}var Ye=require("zod");var wg=Ye.z.string().regex(/^[a-f0-9]{64}$/),S0=mi.omit({variations:!0,active:!0}).extend({changeId:wg,variations:Ye.z.array(Ye.z.strictObject({urlRedirect:Ye.z.string().max(2048)})).min(2).max(20)}),Og=Ye.z.strictObject({environmentId:Ye.z.uuid(),trackExposures:Ye.z.boolean(),generation:wg,experiments:Ye.z.array(S0).max(100),savedGroups:ro}),x0=Ye.z.strictObject({eventUuid:Ye.z.uuid(),timestamp:Ye.z.iso.datetime({offset:!0}).optional(),deviceId:Ye.z.string().min(1).max(128),sessionId:Ye.z.string().min(1).max(128).optional(),url:Ye.z.url().max(2048),pageTitle:Ye.z.string().max(512).optional(),experimentKey:Ye.z.string().min(1).max(255),variationKey:Ye.z.string().min(1).max(64)}),FR=Ye.z.strictObject({events:Ye.z.array(x0).min(1).max(20)}),MR=Ye.z.strictObject({inserted:Ye.z.number().int().nonnegative(),duplicates:Ye.z.number().int().nonnegative(),skipped:Ye.z.number().int().nonnegative(),rejected:Ye.z.array(Ye.z.strictObject({index:Ye.z.number().int().nonnegative(),reason:Ye.z.string()}))});var yt=require("zod");var I0=yt.z.strictObject({selector:yt.z.string().min(1).max(2048),action:yt.z.enum(["set","append","remove"]),attribute:yt.z.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:yt.z.string().max(5e4).optional(),parentSelector:yt.z.string().max(2048).optional(),insertBeforeSelector:yt.z.string().max(2048).optional()}),v0=yt.z.strictObject({variation:yt.z.string().min(1).max(128),description:yt.z.string().max(2e3).default(""),css:yt.z.string().max(1e5).default(""),js:yt.z.string().max(1e5).default(""),domMutations:yt.z.array(I0).max(200).default([]),iam:Vm.optional(),renderGuard:va.optional()}),Au=v0.omit({variation:!0,description:!0,iam:!0}),w0=mi.omit({variations:!0,active:!0}).extend({changeId:yt.z.string().regex(/^[a-f0-9]{64}$/),variations:yt.z.tuple([Au,Au]).rest(Au).refine(e=>e.length<=20)}),_g=yt.z.strictObject({trackExposures:yt.z.boolean(),environmentId:yt.z.uuid(),generation:yt.z.string().regex(/^[a-f0-9]{64}$/),experiments:yt.z.array(w0).max(100),savedGroups:ro});var nt=require("zod");var bu=32,O0=522240;function Su(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 _0=nt.z.strictObject({nodeId:nt.z.string().min(1).max(64),visit:nt.z.number().int().nonnegative(),revision:nt.z.number().int().nonnegative()}),yu=nt.z.record(nt.z.string(),Ae),C0=nt.z.strictObject({id:nt.z.uuid(),nodeId:nt.z.string().min(1).max(64),visit:nt.z.number().int().nonnegative(),input:nt.z.strictObject({schemaVersion:so.shape.schemaVersion,kind:so.shape.kind,selector:so.shape.selector,contract:so.shape.contract}),context:yu,removed:nt.z.array(nt.z.string()).max(100),attributes:yu,removedAttributes:nt.z.array(nt.z.string()).max(100),result:df,offeringVersionId:nt.z.uuid().nullable(),events:nt.z.strictObject({entered:nt.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:nt.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),KR=nt.z.strictObject({schemaVersion:nt.z.literal(1),mode:nt.z.enum(["local","remote"]),versionId:nt.z.uuid(),generation:nt.z.number().int().positive(),base:_0,context:yu,steps:nt.z.array(C0).min(1).max(bu)}).refine(e=>on(e)<=O0,"Segment exceeds its byte budget");var xu=class extends Error{constructor(n,r){super(r);Le(this,"code",n);this.name="FunnelLocalCalculationError"}},Cg=(e,t)=>new xu(e,t),P0=e=>({experiments:e.experiments,features:e.features});function E0(e,t=Cg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Zr(e.growth.savedGroups),i=P0(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Fn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,d;if(c.type==="condition"){let w=e.conditions[c.id];if(!w)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=fu({id:c.id,name:c.id,type:"condition",cases:w.map(I=>({condition:I.condition,target:c.outputs[I.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");d=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=fu({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);d=I.value,u=I.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)d=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...d===void 0?{}:{value:d}}}}}function R0(e,t){let n=Ka.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=E0(n,t);return(o,s)=>(i(),k0(a,o,s))}function k0(e,t,n){let r=xt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function j0(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,d={expected:n.sticky[u]??null,next:s};c<0?r.push(d):r[c]=d},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(Ae.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(Ae.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function Pg(e,t,n,r=Cg){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,d=n.visit,m=!1,w,I=g=>(w??(w=R0(e,r)),j0(w,g,{attributes:Dc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<bu;g++){let f=a.get(u);if(!f||!Su(f))break;if(d>=t.execution.maxTransitions&&(d>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let S,A;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")S=I(f.id),f.type==="offering"&&(S.value={type:"offering_version",id:String(S.value)}),f.type==="condition"?A=S.port==="default"?f.default:f.cases[Number(S.port.slice(5))]?.target:f.type==="split"?A=S.port==="notParticipating"?f.notParticipating:f.routes[S.port]:(f.type==="feature"||f.type==="offering")&&(A=f.next);else if(S={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(A=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(S.value={type:"offering_version",id:f.configuration.versionId},A=f.next),f.type==="end"||f.type==="output"){let v=f.type==="end"?f.output:f.value;if(S=v?.type==="feature"?I(f.id):{...S,port:"value",value:v?.type==="literal"?v.value:v?.type==="variable"?ac({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},v&&(S.value===void 0||!dn(t.outputSchema,S.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:S}];if(on({steps:P})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:S}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let v=f.type==="coupons"?f.couponIds.map(N=>({type:"reward",id:N})):f.type==="coupon"?{type:"reward",id:f.couponId}:S.value;if(v===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=ii(f,{value:v});Pp(t.variables,f,k),Object.assign(o,k)}for(let v of S.sticky)s[`${v.next.attributeName}||${v.next.attributeValue}`]=structuredClone(v.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!A)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=A,d++}let p=a.get(u);return{steps:c,...!m&&p&&!Su(p)?{boundary:{nodeId:u,visit:d}}:{}}}var be=require("zod");var Ha=be.z.string().regex(/^[a-f0-9]{64}$/),T0=be.z.strictObject({release:Ha,render:va,button:be.z.strictObject({selector:be.z.string().min(1).max(512),elementKey:be.z.string().min(1).max(256),tag:be.z.enum(["button","a","input"])}).nullable()}),uk=be.z.strictObject({scope:ze.extend({environmentId:be.z.uuid()}),release:Ha,validatedAt:be.z.iso.datetime({offset:!0}),validUntil:be.z.iso.datetime({offset:!0}),entries:be.z.array(be.z.strictObject({id:be.z.uuid(),funnelId:be.z.uuid(),versionId:be.z.uuid(),event:be.z.enum(["screen_enter","button_click"]),target:T0})).max(4e3)}),lk=be.z.strictObject({operation:be.z.literal("entry_start"),funnelId:be.z.uuid(),versionId:be.z.uuid(),entryId:be.z.uuid(),release:Ha,requestId:be.z.uuid(),locale:be.z.string().min(1).max(35).default("en")}),dk=be.z.strictObject({scope:ze,suppressed:be.z.literal(!0),reason:be.z.enum(["frequency","in_progress"]),retryAt:be.z.iso.datetime({offset:!0}).nullable()}),pk=be.z.strictObject({experimentId:be.z.uuid(),splitNodeId:be.z.string().min(1).max(128)}),N0=be.z.strictObject({experimentId:be.z.uuid(),experimentKey:be.z.string().min(1).max(128),variationKey:be.z.string().min(1).max(128),inExperiment:be.z.boolean(),generation:be.z.string().min(1).max(256)}),Eg=be.z.strictObject({operation:be.z.literal("page_experiments"),release:Ha,usedReceiptIds:be.z.array(be.z.uuid()).max(20).default([]),customerToken:be.z.string().regex(Vt).optional()}),Rg=be.z.strictObject({scope:ze,runId:be.z.uuid(),assignments:be.z.array(N0.extend({receiptId:be.z.uuid()})).max(20),payload:_g});var y=class extends Error{constructor(n,r,i,a,o){super(r);Le(this,"code",n);Le(this,"status",i);Le(this,"requestId",a);Le(this,"retryable");Le(this,"recovery");Le(this,"retryAfterSeconds");Le(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=_o(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var go=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new y("INVALID_STATE","Installation sequence exhausted");return e+1},D0=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function Ln(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new y("INVALID_STATE","Installation journal is invalid");return t({...n})})}function kg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||ze.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new y("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new y("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=A=>{if(A!==i)throw new y("IDENTITY_CHANGED","Identity changed during Push operation")};async function d(A){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new y("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let v=P.sha256?await P.sha256(Uint8Array.from(A,k=>k.charCodeAt(0))):await D0(A);if(!/^[a-f0-9]{64}$/.test(v))throw new y("INVALID_STATE","Push credential digest is invalid");return v}function m(A){let P=br.parse(A);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new y("INVALID_RESPONSE","Push response belongs to another installation");return P}async function w(A,P){let v=c(),k={installationId:v.installationId,publicKey:v.publicKey,issuedAt:new Date().toISOString(),...P},N=await v.sign(el(A,v.scope,k));return{...k,signature:N}}let I=(A,P,v)=>t.requestWithCredential?t.requestWithCredential(A,P,v):t.request(A,P);async function p(){let A=c(),P=i,v=r?await(t.session?.access()??r):null,k=Ln(A,ve=>ve),N;if(k.detachSeq!==null){let ve=k.detachSeq,Me=Wu.parse(await w("detach",{sequence:ve,platform:A.platform}));try{let ke=await t.request("push/installations/detach",{...A.scope,...Me},"POST",{installationDetach:!0});if(!ke||typeof ke!="object"||!("installation"in ke))throw new y("INVALID_RESPONSE","Push detach acknowledgement is invalid");let zt=m(ke.installation);if(zt.bound||zt.identitySeq!==ve)throw new y("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(ke){if(ke instanceof y&&ke.status===404)N=ke;else if(!(ke instanceof y)||ke.status!==412)throw ke}N||Ln(A,ke=>({...ke,detachSeq:ke.detachSeq===ve?null:ke.detachSeq}))}if(u(P),!v){if(N)throw N;return null}let B=O.bindPushInstallation,fe=B.request.parse(await w("bind",{sequence:o,platform:A.platform,credentialDigest:await d(v)}));u(P);let Ie=B.response.parse(await I(B.path,fe,v));u(P);let Ce=m(Ie.installation);if(!Ce.bound||Ce.identitySeq!==o)throw new y("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return N&&k.detachSeq!==null&&o>k.detachSeq&&Ln(A,ve=>({...ve,detachSeq:ve.detachSeq===k.detachSeq?null:ve.detachSeq})),Ce}async function g(){c();let A=i,P=r?await(t.session?.access()??r):null;if(!P)throw new y("NOT_IDENTIFIED","Identify before reading this installation");let v=O.readPushInstallation,k=v.request.parse(await w("read",{credentialDigest:await d(P)}));u(A);let N=v.response.parse(await I(v.path,k,P));return u(A),m(N.installation)}function f(A=p){let P=s.catch(()=>{}).then(A);return s=P,P.catch(v=>{try{e?.onError?.(v instanceof Error?v:new Error("Push synchronization failed"))}catch{}}),P}async function S(A,P,v){let k=c(),N=P.identity,B=P.observation,fe=r?await(t.session?.access()??r):null;if(u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");if(!fe)throw new y("NOT_IDENTIFIED","Identify before recovering a Push address");if(!A.connectionId||!A.kind||!A.token||!["granted","provisional"].includes(A.permission))throw new y("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await f(async()=>{if(u(N),await p(),u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let Ie=Ln(k,zt=>v?zt:{...zt,addressSeq:go(zt.addressSeq)}),ve=await w(v?"recovery_confirm":"recovery_request",{...A,sequence:Ie.addressSeq,credentialDigest:await d(fe),...v?{challenge:v}:{}}),Me=v?Xu.parse(ve):Yu.parse(ve);if(u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let ke=await I(`push/installations/recovery/${v?"confirm":"request"}`,Me,fe);if(u(N),B!==a||Ln(k,zt=>zt).addressSeq!==Ie.addressSeq)throw new y("INVALID_STATE","Push observation changed during recovery");if(v){let zt=O.updatePushAddress.response.parse(ke),Xe=m(zt.installation);if(!Xe.bound||Xe.identitySeq!==o||Xe.addressSeq!==Ie.addressSeq||Xe.connectionId!==A.connectionId||Xe.addressStatus!=="active")throw new y("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Xe}if(!ke||typeof ke!="object"||!("recovery"in ke))throw new y("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return ls.parse(ke.recovery)})}return{recoveryObserver(){c();let A={identity:i,observation:++a};return{async request(P){return ls.parse(await S(P,A))},async confirm(P,v){return br.parse(await S(v,A,P))}}},identify(A){if(!e)return;o=Ln(e,v=>({...v,identitySeq:go(v.identitySeq)})).identitySeq,r=A,i++,a++},reset(){if(e)try{Ln(e,A=>{let P=go(A.identitySeq);return{...A,identitySeq:P,detachSeq:P}})}finally{r=null,i++,a++}},start(){e&&f()},async sync(){return await f()},read:g,async recover(){let A=c(),P=i,v=o;return a++,await f(async()=>{u(P);let k=await g();return u(P),o=Ln(A,B=>{if(B.identitySeq!==v)throw new y("IDENTITY_CHANGED","A newer installation intent exists");return{...B,identitySeq:go(Math.max(B.identitySeq,k.identitySeq)),addressSeq:Math.max(B.addressSeq,k.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let A=++a,P=i;return async v=>{if(A!==a||P!==i)return null;let k=c(),N=r?await(t.session?.access()??r):null;if(!N)throw new y("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),A!==a)return null;let B=Ln(k,ve=>({...ve,addressSeq:go(ve.addressSeq)})),fe=O.updatePushAddress,Ie=fe.request.parse(await w("address",{...v,sequence:B.addressSeq,credentialDigest:await d(N)}));if(u(P),A!==a)return null;let Ce=fe.response.parse(await I(fe.path,Ie,N));return u(P),m(Ce.installation)}}}}function jg(e,t){return{messaging:{async preference(n){let r=O.readMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse(n))).preference}},push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){let n=O.readMessagingPreference;return n.response.parse(await e(n.path,{channel:"push"})).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}var Tg={name:"@tinkerlandai/indiana-sdk",version:"0.10.1",description:"Framework-independent Indiana SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function Ge(e){return typeof e=="string"?e:String(e)}var M0=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function q0(e){return e.replace(M0,"$1\uFFFD")}function Ou(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 Lg(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 Ng(e){let t;if(Array.isArray(e)){let n=e.map(Ge);if(n.length===2)return n}else if((t=Lg(e))!=null){let n=Ou(t.next()),r=Ou(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 Dg="0123456789ABCDEF",V0=/(?:%[0-9A-Fa-f]{2})+/g;function Rn(e){return`%${Dg[e>>4&15]}${Dg[15&e]}`}function zg(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Rn(e):String.fromCharCode(e):e<=2047?Rn(192|e>>6)+Rn(128|63&e):e<=65535?Rn(224|e>>12)+Rn(128|e>>6&63)+Rn(128|63&e):Rn(240|e>>18)+Rn(128|e>>12&63)+Rn(128|e>>6&63)+Rn(128|63&e)}function _u(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Cu(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(V0,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function yo(e){return e<=31||e>126}function B0(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return yo(e)}}function Nu(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return yo(e)}}function U0(e){return Nu(e)||e===39}function Pu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Nu(e)}}function Ya(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 Pu(e)}}function Fg(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 Ya(n)}})(e)}}function $g(e,t){return zg(e=e||0,t)}function kn(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),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=zg(o,t,n)}return i}function Du(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([Cu(i.slice(0,a),!0),Cu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Eu(e){let t="";for(let n=0;n<e.length;n++){let r=kn(e[n][0],Fg,!0),i=kn(e[n][1],Fg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var L0=[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],z0=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],$0=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],G0=[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 K0(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[H0,Q0,J0,Mg]=[[[],"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 Z0(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 Gg(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function ho(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function W0(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&&Gg(G0,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&ho(Mg,t[i]);)i--;let a=n+1;for(;a<t.length&&ho(Mg,t[a]);)a++;if(!(i>=0&&a<t.length&&ho(Q0,t[i])&&ho(J0,t[a])))return!1}return!0}var Y0=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,X0=/\p{Script=Latin}/u;function eI(e){return!Y0.test(e)||!X0.test(e)}var ur=36,Ja=1,Ru=26,tI=38,nI=700,rI=72,iI=128,oI=2147483647;function qg(e){return String.fromCharCode(e+22+75*+(e<26))}function aI(e,t,n){let r=0;for(e=n?Math.floor(e/nI):e>>1,e+=Math.floor(e/t);e>(ur-Ja)*Ru>>1;r+=ur)e=Math.floor(e/(ur-Ja));return Math.floor(r+(ur-Ja+1)*e/(e+tI))}function sI(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=iI,o=0,s=rI;for(;r<t.length;){let c=oI;for(let u=0;u<t.length;u++){let d=t[u];d>=a&&d<c&&(c=d)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let d=t[u];if(d<a&&o++,d===a){let m=o;for(let w=ur;;w+=ur){let I=w<=s?Ja:w>=s+Ru?Ru:w-s;if(m<I)break;n+=qg(I+(m-I)%(ur-I)),m=Math.floor((m-I)/(ur-I))}n+=qg(m),s=aI(o,r+1,r===i),o=0,r++}}o++,a++}return n}function Iu(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=_u(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Vg(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function Kg(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Hg(e){return e.length===2&&Kg(e.codePointAt(0),e.codePointAt(1))}function Bg(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function lt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Qg(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function ku(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,d=0,m=0;for(;m<4&&(u=_u(c[s]))>=0;)d=(d<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let w=0;for(;c[s]!==void 0;){let I=0;if(w>0)if(c[s]===46&&w<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(I=10*I+_u(c[s]),I>255)return null;s++}i[o]=256*i[o]+I,w++,w%2==0&&o++}if(w!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=d,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let d=i[a+u-1];i[a+u-1]=i[o],i[o]=d,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Bg(r)?null:kn(r,yo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let d of u){let m=d.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(d)&&!Gg(L0,m)||ho(H0,m))return!0}return!1})(i))return null;let s=(i=(function(u){let d="";for(let m of u){let w=m.codePointAt(0);if(w!==8204&&w!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let I=Z0(m,w);if(I){d+=I;continue}let p=z0.indexOf(w);d+=p<0?m:$0[p]}return d})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let d=/[^\0-\x7f]/.test(u);if(K0(u)||d&&(/^\p{Mark}/u.test(u)||!W0(u)||!eI(u)||u.startsWith("xn--")))return null;d&&(s[c]=`xn--${sI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Cu(e));return n===null||Bg(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(Iu(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let d=Iu(a[u]);if(d<0||d>255)return null;s+=d*(1<<8*(3-u))}let c=Iu(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function ju(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(s){let c=-1,u=-1,d=1,m=0;for(let w=0;w<s.length;++w)s[w]!==0?(m>d&&(c=u,d=m),u=-1,m=0):(u===-1&&(u=w),++m);return m>d?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Jg(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 Zg(e){return e.username!==""||e.password!==""}function vu(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,q="",xe="",Be=null,V,Za=!1,Wa=!1,zr=!1,dt;function un(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),C=0,q=e,xe="",Be=n||null,V=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Za=!1,Wa=!1,zr=!1,dt=r||0;let i=cI;switch(r){case 3:case 4:i=Xa;break;case 5:i=Mu;break;case 6:i=$r;break;case 7:i=lr;break;case 8:i=jn}return i(G(e,C))!==1?V:null}function X(e,t){return C+=C===e?vn(t):1,C<=q.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function vn(e){return e!=null&&e>65535?2:1}function Wg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var cI=e=>{let t=C;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=C+1;for(e=q.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=q.charCodeAt(n);return xe=q.slice(C,n).toLowerCase(),C=n,uI(n<q.length?e:void 0)}else return dt?1:(--C,X(t,e)?Yg(G(q,C)):0)},uI=e=>{let t=C;if(e===58){if(dt){if(lt(V.scheme)!==lt(xe))return 0;if((Zg(V)||V.port!==null)&&xe==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=xe,dt?(V.port===Qg(V.scheme)&&(V.port=null),0):(xe="",V.scheme==="file"?X(t,e)?qu(G(q,C)):0:lt(V.scheme)&&Be!==null&&Be.scheme===V.scheme?X(t,e)?lI(G(q,C)):0:lt(V.scheme)?X(t,e)?pI(G(q,C)):0:G(q,C+1)===47?(C++,X(t,e)?dI(G(q,C)):0):(V.path=[""],V.opaquePath=!0,X(t,e)?eh(G(q,C)):0))}else return dt?1:(xe="",C=-1,X(t,e)?Yg(G(q,C)):0)},Yg=e=>{let t=C;return Be===null||Be.opaquePath&&e!==35?1:Be.opaquePath&&e===35?(V.scheme=Be.scheme,V.path=Be.path.slice(),V.opaquePath=Be.opaquePath,V.query=Be.query,V.fragment="",X(t,e)?jn(G(q,C)):0):Be.scheme==="file"?(C--,X(t,e)?qu(G(q,C)):0):(C--,X(t,e)?Fu(G(q,C)):0)},lI=e=>{let t=C;return e===47&&G(q,C+1)===47?(++C,X(t,e)?ts(G(q,C)):0):(C--,X(t,e)?Fu(G(q,C)):0)},dI=e=>{let t=C;return e===47?X(t,e)?xi(G(q,C)):0:(C--,X(t,e)?wn(G(q,C)):0)},Fu=e=>{let t=C;return V.scheme=Be.scheme,e===47||lt(V.scheme)&&e===92?X(t,e)?Ug(G(q,C)):0:(V.username=Be.username,V.password=Be.password,V.host=Be.host,V.port=Be.port,V.path=Be.path.slice(),V.query=Be.query,e===63?(V.query="",X(t,e)?lr(G(q,C)):0):e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):e!=null?(V.query=null,V.path.pop(),C--,X(t,e)?wn(G(q,C)):0):X(t,e)?Fu(G(q,C)):0)},Ug=e=>{let t=C;return lt(V.scheme)&&(e===47||e===92)?X(t,e)?ts(G(q,C)):0:e===47?X(t,e)?xi(G(q,C)):0:(V.username=Be.username,V.password=Be.password,V.host=Be.host,V.port=Be.port,C--,X(t,e)?wn(G(q,C)):0)},pI=e=>{let t=C;return e===47&&G(q,C+1)===47?C++:C--,X(t,e)?ts(G(q,C)):0},ts=e=>{let t=C;return e!==47&&e!==92?(C--,X(t,e)?xi(G(q,C)):0):X(t,e)?ts(G(q,C)):0},xi=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!lt(V.scheme))){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&lt(V.scheme))break;n+=vn(r)}return xe+=q.slice(C,n),C=n-1,X(t,e)?xi(G(q,C)):0}if(e===64){Za&&(xe=`%40${xe}`),Za=!0;for(let n=0;n<xe.length;n++){let r=xe.codePointAt(n);if(r===58&&!Wa){Wa=!0;continue}let i=$g(r,Ya);Wa?V.password+=i:V.username+=i,r!=null&&r>65535&&n++}return xe="",X(t,e)?xi(G(q,C)):0}else return e==null||e===35||e===47||e===63||e===92&&lt(V.scheme)?Za&&xe===""?1:(C-=xe.length+1,xe="",X(t,e)?Xa(G(q,C)):0):(xe+=Wg(e),X(t,e)?xi(G(q,C)):0)},Xa=e=>{let t=C;if(dt&&V.scheme==="file")return C--,X(t,e)?Vu(G(q,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!lt(V.scheme))){let n=C+vn(e);for(e===91?zr=!0:e===93&&(zr=!1);n<q.length;){let r=G(q,n);if(r==null||!zr&&r===58||r===35||r===47||r===63||r===92&&lt(V.scheme))break;r===91?zr=!0:r===93&&(zr=!1),n+=vn(r)}return xe+=q.slice(C,n),C=n-1,X(t,e)?Xa(G(q,C)):0}else if(e===58&&!zr){if(xe===""||dt===4)return 1;let n=ku(xe,!lt(V.scheme));return n===null?1:(V.host=ju(n),xe="",X(t,e)?Mu(G(q,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&lt(V.scheme)){if(C--,lt(V.scheme)&&xe==="")return 1;if(dt&&xe===""&&(Zg(V)||V.port!==null))return 1;let n=ku(xe,!lt(V.scheme));return n===null?1:(V.host=ju(n),xe="",dt?0:X(t,e)?$r(G(q,C)):0)}else return xe+=Wg(e),X(t,e)?Xa(G(q,C)):0},Mu=e=>{let t=C;if(e!=null&&e>=48&&e<=57){let n=C+1;for(;n<q.length;){let r=q.charCodeAt(n);if(r<48||r>57)break;n++}return xe+=q.slice(C,n),C=n-1,X(t,e)?Mu(G(q,C)):0}else if(dt||e==null||e===35||e===47||e===63||e===92&&lt(V.scheme)){if(xe!==""){let n=parseInt(xe,10);if(n>65535)return 1;if(V.port=n===Qg(V.scheme)?null:n,xe="",dt)return 0}return dt?1:(C--,X(t,e)?$r(G(q,C)):0)}else return 1};function Xg(e,t){let n=e.length-t;if(n<2)return!1;if(Kg(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var qu=e=>{let t=C;return V.scheme="file",V.host="",e===47||e===92?X(t,e)?mI(G(q,C)):0:Be?.scheme==="file"?(V.host=Be.host,V.path=Be.path.slice(),V.opaquePath=Be.opaquePath,V.query=Be.query,e===63?(V.query="",X(t,e)?lr(G(q,C)):0):e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):e!=null?(V.query=null,Xg(q,C)?V.path=[]:Jg(V),C--,X(t,e)?wn(G(q,C)):0):X(t,e)?qu(G(q,C)):0):(C--,X(t,e)?wn(G(q,C)):0)},mI=e=>{let t=C;return e===47||e===92?X(t,e)?Vu(G(q,C)):0:(Be!==null&&Be.scheme==="file"&&(!Xg(q,C)&&(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})(Be.path[0])&&V.path.push(Be.path[0]),V.host=Be.host),C--,X(t,e)?wn(G(q,C)):0)},Vu=e=>{let t=C;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=vn(r)}return xe+=q.slice(C,n),C=n-1,X(t,e)?Vu(G(q,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!dt&&Hg(xe))return X(t,e)?wn(G(q,C)):0;if(xe==="")return V.host="",dt?0:X(t,e)?$r(G(q,C)):0;{let n=ku(xe,!lt(V.scheme));return n===null?1:(n==="localhost"&&(n=""),V.host=ju(n),xe="",dt?0:X(t,e)?$r(G(q,C)):0)}}return 1},$r=e=>{let t=C;return lt(V.scheme)?(e!==92&&e!==47&&C--,X(t,e)?wn(G(q,C)):0):!dt&&e===63?(V.query="",X(t,e)?lr(G(q,C)):0):!dt&&e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):e!=null?(e!==47&&C--,X(t,e)?wn(G(q,C)):0):(dt&&V.host===null&&V.path.push(""),X(t,e)?$r(G(q,C)):0)},wn=e=>{let t=C;if(e!=null&&e!==47&&(!lt(V.scheme)||e!==92)&&(dt||e!==63&&e!==35)){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===47||lt(V.scheme)&&r===92||!dt&&(r===63||r===35))break;n+=vn(r)}xe+=kn(q.slice(C,n),Pu),C=n,e=G(q,n)}if(e==null||e===47||lt(V.scheme)&&e===92||!dt&&(e===63||e===35)){let n=lt(V.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}})(xe)?(Jg(V),e!==47&&!n&&V.path.push("")):Vg(xe)&&e!==47&&!n?V.path.push(""):Vg(xe)||(V.scheme==="file"&&V.path.length===0&&Hg(xe)&&(xe=`${xe[0]}:`),V.path.push(xe)),xe="",e===63?(V.query="",X(t,e)?lr(G(q,C)):0):e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):X(t,e)?wn(G(q,C)):0}else return xe+=$g(e,Pu),X(t,e)?wn(G(q,C)):0},eh=e=>{let t=C;if(e===63)return V.query="",X(t,e)?lr(G(q,C)):0;if(e===35)return V.fragment="",X(t,e)?jn(G(q,C)):0;if(e!=null){let n=C+vn(e);for(;n<q.length;){let i=G(q,n);if(i===63||i===35)break;n+=vn(i)}let r=q.slice(C,n);if(n<q.length&&r.charCodeAt(r.length-1)===32?V.path[0]+=kn(r.slice(0,-1),yo)+"%20":V.path[0]+=kn(r,yo),C=n,(e=G(q,n))===63)return V.query="",X(t,e)?lr(G(q,C)):0;if(e===35)return V.fragment="",X(t,e)?jn(G(q,C)):0}return X(t,e)?eh(G(q,C)):0},lr=e=>{let t=C,n=C;if(e!=null){if(dt)n=q.length;else{let i=q.indexOf("#",C);n=i===-1?q.length:i}let r=lt(V.scheme)?U0:Nu;V.query+=kn(q.slice(C,n),r)}return C=n,G(q,n)===35&&!dt?(V.fragment="",X(t,e)?jn(G(q,C)):0):X(t,e)?lr(G(q,C)):0},jn=e=>{let t=C;return e!=null&&(V.fragment+=kn(q.slice(C),B0),C=q.length),X(t,e)?jn(G(q,C)):0};function Tu(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function th(e){switch(e.scheme){case"blob":{let t=un(Tu(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":th(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 $e=Symbol("URLImpl"),gn=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=un(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=un(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[$e]={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=un(n,null,null,0),r==null)?!1:un(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+=Tu(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[$e].url)}set href(t){let n=un(t=Ge(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[$e].url=n,this[$e].query&&wu(this[$e].query,n.query)}get origin(){return th(this[$e].url)}get protocol(){return`${this[$e].url.scheme}:`}set protocol(t){un(`${t=Ge(t)}:`,this[$e].url,null,2)}get username(){return this[$e].url.username}set username(t){t=Ge(t),vu(this[$e].url)||(function(r,i){r.username=kn(i,Ya)})(this[$e].url,t)}get password(){return this[$e].url.password}set password(t){t=Ge(t),vu(this[$e].url)||(function(r,i){r.password=kn(i,Ya)})(this[$e].url,t)}get host(){let{url:t}=this[$e];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Ge(t),this[$e].url.opaquePath||un(t,this[$e].url,null,3)}get hostname(){let{url:t}=this[$e];return t.host!=null?t.host:""}set hostname(t){t=Ge(t),this[$e].url.opaquePath||un(t,this[$e].url,null,4)}get port(){let{url:t}=this[$e];return t.port!=null?`${t.port}`:""}set port(t){t=Ge(t);let{url:n}=this[$e];vu(n)||(t?un(t,n,null,5):n.port=null)}get pathname(){return Tu(this[$e].url)}set pathname(t){t=Ge(t);let{url:n}=this[$e];n.opaquePath||(n.path=[],un(t,n,null,6))}get search(){let{url:t}=this[$e];return t.query?`?${t.query}`:""}set search(t){t=Ge(t);let{url:n,query:r}=this[$e];if(!t)n.query=null,r&&wu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",un(i,n,null,7),r&&wu(r,n.query)}}get searchParams(){let t=this[$e],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new es;return o[rt].url=i,o[rt].serialized=a==null,a&&(o[rt].list=Du(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[$e];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Ge(t);let{url:n}=this[$e];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",un(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(gn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var rt=Symbol("URLSearchParamsImpl"),fI=Symbol.dispose||Symbol.for("dispose");function wu(e,t){t?e[rt].list=Du(t):e[rt].list.length=0,e[rt].serialized=t==null}function Qa(e){if(e.url){let t=Eu(e.list);(function(r,i){r[$e].url.query=i})(e.url,t||null),e.serialized=!0}}var gI=typeof Iterator<"u"?Iterator:Object,Ao=class extends gI{constructor(t,n){super(),this[rt]={ptr:t,map:n,index:0}}next(){let t=this[rt];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}[fI](){}},es=class{constructor(t){let n=this[rt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Ng(t[i]));else if((r=Lg(t))!=null){let i;for(;!(i=Ou(r.next())).done;)n.list.push(Ng(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 o=i[a],s=q0(o),c=Ge(t[o]),u=n.list.find(d=>d[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Ge(t);i=i[0]==="?"?i.substring(1):i,n.list=Du(i)}}get size(){return this[rt].list.length}append(t,n){t=Ge(t),n=Ge(n),this[rt].list.push([t,n]);let r=this[rt];r.url&&r.serialized?(function(a,o){let s=a[$e].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Eu([[t,n]])):Qa(r)}delete(t,n){t=Ge(t),n=n!=null?Ge(n):void 0;let{list:r}=this[rt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;Qa(this[rt])}get(t){t=Ge(t);let{list:n}=this[rt];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[rt];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[rt];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[rt],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&Qa(this[rt])}sort(){this[rt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),Qa(this[rt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[rt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Ao(this[rt],t=>t)}keys(){return new Ao(this[rt],t=>t[0])}values(){return new Ao(this[rt],t=>t[1])}toString(){return Eu(this[rt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(es.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var dr="https://api.tinker.cash";function nh(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,w){let I=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}I===r&&(t=m,n=w,o())}let c=()=>s();function u(m,w=!1){let I=Kn.safeParse(m);if(!I.success||w&&Date.parse(I.data.expiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<Date.parse(I.data.expiresAt))throw new y("INVALID_RESPONSE","Invalid customer session credentials");return I.data}async function d(){if(i)return i;let m=t,w=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new y("UNAUTHENTICATED","Customer authentication is required",401);let I=(async()=>{try{let p=await e(m.refreshToken);if(w!==r)throw new y("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new y("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw w!==r?new y("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof y&&p.status===401&&c(),p)}})();i=I;try{return await I}finally{i===I&&(i=void 0)}}return{identify(m){let w=typeof m=="string"?void 0:u(m),I=typeof m=="string"?m:w.accessToken;if(!I.trim()||/\s/.test(I)||I.length>4096)throw new y("INVALID_TOKEN","A server-issued token is required");s(w,I)},reset:c,subscribeIdentity(m,w){return a.set(m,w),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return d().then(()=>{if(!n)throw new y("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new y("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:d}}var rh=Symbol("IndianaNoContent");function pr(e,t,n=gn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?ze.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??dr);if(o.username||o.password||o.search||o.hash)throw new y("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new y("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new y("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,d=0,m=null,w=new Set,I=e.session??nh(async A=>{let P=await S("customer-sessions/refresh",{},"POST",{},A);if(!P||typeof P!="object")throw new y("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:k,...N}=P;return N});function p(){d+=1,u=null,m=null;for(let A of w)A.abort();w.clear()}let g=I.subscribeIdentity(p);function f(){I.reset()}async function S(A,P={},v="POST",k={},N){let B=k.installationDetach===!0;if(B&&(A!=="push/installations/detach"||v!=="POST"))throw new y("INVALID_REQUEST","Installation authority only detaches this installation");if(!N&&!u&&!B)throw new y("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let fe=d,Ie=new AbortController;B||w.add(Ie);let Ce=()=>!B&&fe!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new y("TIMEOUT","Indiana request timed out"),ve,Me=new Promise((Xe,Tt)=>{ve=()=>Tt(Ce()),Ie.signal.addEventListener("abort",ve,{once:!0})}),ke=setTimeout(()=>Ie.abort(),c),zt=async()=>{let Xe=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{"Content-Type":"application/json",...B?{}:{Authorization:`Bearer ${N??u}`},[gs]:hs.current,[ol]:Tg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(P):void 0,signal:Ie.signal,credentials:"omit",cache:"no-store",redirect:"error",...k.keepalive?{keepalive:!0}:{}});if(Ie.signal.aborted)throw Ce();let Tt;try{Tt=Xe.status===204?rh:await Xe.json()}catch{throw Ie.signal.aborted?Ce():new y(Xe.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Xe.status,Xe.headers.get("X-Request-Id")??void 0)}if(Ie.signal.aborted)throw Ce();if(!B&&fe!==d)throw new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Xe.ok){let st=fs.safeParse(Tt),$t=st.success&&(!Nn.safeParse(st.data.error.code).success||rl(st.data.error.code,Xe.status)),gr=$t?st.data.error.code:"HTTP_ERROR",hr=_o(gr,Xe.status,{retryAfter:Xe.headers.get("Retry-After"),recovery:$t?st.data.error.recovery:void 0,reason:$t?st.data.error.reason:void 0});throw new y(gr,$t?st.data.error.message:"Indiana request failed",Xe.status,Xe.headers.get("X-Request-Id")??(st.success?st.data.requestId:void 0),{...hr,...st.success&&st.data.error.retryable===!1?{retryable:!1}:{},...hr.retryAfterSeconds===void 0&&st.success&&st.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:st.data.error.retryAfterSeconds}:{}})}if(Xe.headers.get(gs)!==hs.current)throw new y("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&Tt!==rh){let st=Tt&&typeof Tt=="object"&&"scope"in Tt?Tt:Tt&&typeof Tt=="object"&&"configuration"in Tt?Tt.configuration:null;if(!st||typeof st!="object"||!("scope"in st))throw new y("INVALID_RESPONSE","Response is missing its App/environment scope");let $t=ze.safeParse(st.scope);if(!$t.success||$t.data.projectId!==a.projectId||$t.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Gr=Xe.headers.get("X-Indiana-Telemetry-Subject");if(Gr){if(!/^[a-f0-9]{64}$/.test(Gr))throw new y("INVALID_RESPONSE","Invalid telemetry identity");m!==Gr&&(m=Gr,t?.(m))}return Tt};try{return await Promise.race([zt(),Me])}catch(Xe){throw!B&&fe!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Xe instanceof y?Xe:new y(Ie.signal.aborted?"TIMEOUT":"NETWORK_ERROR",Ie.signal.aborted?"Indiana request timed out":"Unable to read the Indiana response")}finally{clearTimeout(ke),Ie.signal.removeEventListener("abort",ve),w.delete(Ie)}}return{session:I,requestWithCredential(A,P,v){return S(A,P,"POST",{},v)},subjectKey:()=>m,identify(A){if(a&&typeof A=="object"&&"scope"in A){let P=ze.safeParse(A.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Customer session belongs to another App/environment")}I.identify(A),u=I.peek()??null},reset:f,dispose(){g(),p()},request(A,P={},v="POST",k={}){if(k.installationDetach)return S(A,P,v,k);let N=d;try{let B=I.access(),fe=Ie=>{if(N!==d)throw new y("IDENTITY_CHANGED","Customer identity changed before dispatch");return S(A,P,v,k,Ie)};return typeof B=="string"?fe(B):B.then(fe)}catch(B){return Promise.reject(B)}}}}function ih(e,t,n={}){let r=!!e.session.peek(),i=new Set,a=o=>{for(let s of i)try{s(o)}catch{}};return e.session.subscribeIdentity(()=>{r=!!e.session.peek(),a(r),n.afterChange?.()},()=>{r=!1,t()}),{isIdentified:()=>r,methods:{subscribeIdentity(o){return i.add(o),()=>{i.delete(o)}},identify(o){let s=typeof o=="string"?o:o.accessToken;if(!Vt.test(s))throw new y("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}var ah=require("zod");function oh(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof ah.ZodError?new y(n,r):i}}async function me(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=oh(t.request,n,"INVALID_REQUEST",a.request),s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):oh(t.response,s,"INVALID_RESPONSE",a.response)}function Ue(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new y("INVALID_REQUEST","Customer requests use the verified session identity")}function sh(e){return{async checkEntitlement(t){Ue(t);let n=O.checkEntitlement;return me(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return me(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function ch(e){return{async readLedger(t){let n=O.readLedger;return me(e,n,{query:t})},async readCreditStatement(t){Ue(t);let n=O.readCreditStatement;return me(e,n,t)},async quoteBalance(t){Ue(t);let n=O.quoteBalance;return me(e,n,{command:t})}}}function uh(e){return{async setupPayment(t){Ue(t);let n=O.setupPayment;return me(e,n,t)},async readPaymentSetup(t){Ue(t);let n=O.readPaymentSetup;return me(e,n,t)},async readBillingInvoice(t){Ue(t);let n=O.readBillingInvoice;return me(e,n,t)},async readBillingControls(t={}){Ue(t);let n=O.readBillingControls;return me(e,n,t)},async prepareBillingAuthorization(t){Ue(t);let n=O.prepareBillingAuthorization;return me(e,n,t)},async confirmBillingAuthorization(t){Ue(t);let n=O.confirmBillingAuthorization;return me(e,n,t)},async setBillingCoupons(t){Ue(t);let n=O.setBillingCoupons;return me(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ue(t);let n=O.revokeBillingAuthorization;return me(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ue(t);let n=O.listBillingInvoices;return me(e,n,t)},async confirmBillingAdjustment(t){Ue(t);let n=O.confirmBillingAdjustment;return me(e,n,t)}}}function lh(e){return{async previewUpdate(t){Ue(t);let n=O.previewUpdate;return me(e,n,t)},async update(t){Ue(t);let n=O.update;return me(e,n,t)},async readSubscriptionUpdate(t){Ue(t);let n=O.readSubscriptionUpdate;return me(e,n,t)},async restoreNativePurchase(t){Ue(t);let n=O.restoreNativePurchase;return me(e,n,t)},async previewAttach(t){Ue(t);let n=O.previewAttach;return me(e,n,t)},async attach(t){Ue(t);let n=O.attach;return me(e,n,t)},async readSubscriptionOperation(t){Ue(t);let n=O.readSubscriptionOperation;return me(e,n,t)}}}function dh(e){return{async redeemReward(t){return Ue(t),(await me(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Ue(t),(await me(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ue(t),(await me(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await me(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await me(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await me(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function ph(e){return{...sh(e),...ch(e),...uh(e),...lh(e),...dh(e)}}function mh(e){return{async resolveContent(t){Ue(t);let n=O.resolveContent;return me(e,n,t)},async resolvePaywall(t){Ue(t);let n=O.resolvePaywall;return me(e,n,t)},async resolveOffering(t){Ue(t);let n=O.resolveOffering;return me(e,n,t)}}}var fh=e=>new TextEncoder().encode(JSON.stringify(e)).length,gh=16384;function hh(e,t){let n=0,r,i=p=>{r={config:structuredClone(p),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function d(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!Em(r.config,p))return;I();let S=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(fh({events:[S]})>gh)throw new y("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new y("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(S)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let S={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&g===n;){let P=[];for(let N of a.slice(0,Math.min(A,100))){if(P.length&&fh({events:[...P,N]})>gh)break;P.push(N)}let v=O.trackEvents,k=await me(e,v,{events:P},void 0,{keepalive:p});if(g!==n)throw new y("IDENTITY_CHANGED","Event identity changed during delivery");if(k.inserted+k.duplicates+k.rejected+k.skipped!==P.length)throw new y("INVALID_RESPONSE","Incomplete event acknowledgement");i(k.analyticsConfig),a.splice(0,P.length),A-=P.length,S.inserted+=k.inserted,S.duplicates+=k.duplicates,S.rejected+=k.rejected,S.skipped+=k.skipped}return S})();o=f;try{return await f}finally{o===f&&(o=null)}}let w;function I(){if(w||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),w=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return I(),d(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){w?.(),w=void 0}}}function ns(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,d=()=>{for(let A of u)try{A()}catch{}},m={attributes:xt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(A,P)=>{!o.has(A)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(A,structuredClone(P),structuredClone(m.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(A,P)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(A),structuredClone(P),structuredClone(m.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?A=>e.saveStickyBucketAssignmentDoc(structuredClone(A)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function I(A,P=new Set){return o.has(A)?!s||!s.features[A]||["unknownFeature","cyclicPrerequisite"].includes(s.features[A].source):P.has(A)?!1:(P.add(A),(t?.features[A]?.rules??[]).some(v=>[...v.parentConditions??[],...(v.tracks??[]).flatMap(k=>k.experiment.parentConditions??[])].some(k=>I(k.id,P))))}let p=A=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return s?.expiresAt&&Date.parse(s.expiresAt)<=Date.now()&&(s=null,m.features=t.features),o.has(A)?!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?w():structuredClone(s.features[A]??w()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||I(A)?w():structuredClone(Fn(A,m))};async function g(){if(!t||!o.size&&!m.attributes?.merchandise&&!m.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(o.size)throw new Error("Remote Feature evaluation requires a server loader");return}let A=i;if(c?.revision===A)return c.loading;let P=r,v=t,k=[...o],N=(async()=>{let B=Ia.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:k}));if(!(P!==r||A!==i||v!==t)){if(e.assertUsable?.(v.generation),B.generation!==v.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(k.some(fe=>!Object.hasOwn(B.features,fe))||Object.keys(B.features).some(fe=>!o.has(fe)))throw new Error("Invalid remote Feature results");if(m.attributes?.merchandise||m.attributes?.merchandiseId){if(!B.merchandiseContext)throw new Error("Server did not resolve merchandise context");m.attributes=xt.parse({...m.attributes,...B.merchandiseContext}),a=!0}s=structuredClone(B),m.features={...v.features,...Object.fromEntries(Object.entries(s.features).map(([fe,Ie])=>[fe,{defaultValue:Ie.value}]))},d()}})();c={revision:A,loading:N};try{await N}finally{c?.loading===N&&(c=null)}}function f(){g().catch(A=>{try{e.onError?.(A)}catch{}})}async function S(){if(n)return n;let A=r,P=(async()=>{let v=await e.load(),k="remoteFeatures"in v?io.parse(v):null,N=k??pn.parse(v);if(N.scope.projectId!==e.scope.projectId||N.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(A!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===N.generation){let{evaluatedAt:fe,expiresAt:Ie,...Ce}=t,{evaluatedAt:ve,expiresAt:Me,...ke}=N;if(It(Ce)!==It(ke))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=N.evaluatedAt,t.expiresAt=N.expiresAt,d(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let B=new Set(k?.remoteFeatures??[]);if([...B].some(fe=>Object.hasOwn(N.features,fe)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in N&&!t.analyticsConfig.experimentViewsEnabled&&k?.analyticsConfig.experimentViewsEnabled&&m.trackedExperiments?.clear(),t=structuredClone(N),o=B,s=null,c=null,i++,m.features=t.features,m.savedGroups=Zr(t.savedGroups),m.trackedFeatureUsage={},d(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:S,refresh:S,refreshRemote:g,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(A){return u.add(A),()=>{u.delete(A)}},setAttributes(A){let P=xt.parse(A);(m.attributes?.merchandise||m.attributes?.merchandiseId||A.merchandise||A.merchandiseId)&&m.trackedExperiments?.clear(),m.attributes=P,i++,a=!1,s=null,c=null,m.features=t?.features??{},m.trackedFeatureUsage={},d(),f()},evalFeature:p,isOn(A){return p(A).on},isOff(A){return p(A).off},getFeatureValue(A,P){let v=p(A).value;return structuredClone(v===null?P:v)},reset(){r++,i++,n=null,c=null,t=null,s=null,o.clear(),m.features={},m.savedGroups={},m.stickyBucketAssignmentDocs={},m.attributes={},m.trackedFeatureUsage={},m.trackedExperiments?.clear(),d()}}}function Ah(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function hI(e){let t=Ah(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function yh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let d=a,m=!1,w=async()=>{if(m||d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Ce=O.getFeatures,ve=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await me(e,Ce,{});if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");if(r&&(ve.scope.projectId!==r.projectId||ve.scope.environment!==r.environment))throw new y("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ve.payload.analyticsConfig),ve},I=await w(),p=!0,g,f=Ce=>{try{u.onError?.(Ce)}catch{}},S=(Ce,ve,Me)=>{try{let ke=Ah(Me);n.track(Ce,ve,ke?{merchandise:ke}:{})}catch(ke){f(ke)}},A=ns({assertUsable:i?.assertFeatures,scope:I.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,I.payload):(await w()).payload,evaluateRemote:async Ce=>{if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let ve=O.evaluateFeatures,Me=await me(e,ve,{...Ce,attributes:hI(Ce.attributes)});if(Me.scope.projectId!==I.scope.projectId||Me.scope.environment!==I.scope.environment)throw new y("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Me.generation,evaluatedAt:Me.evaluatedAt,expiresAt:Me.expiresAt,features:Me.features,...Me.merchandiseContext?{merchandiseContext:Me.merchandiseContext}:{}}},onExperimentViewed:(Ce,ve,Me)=>S("Experiment Viewed",{experimentId:Ce.key,variationId:ve.key},Me),onFeatureUsage:(Ce,ve,Me)=>S("Feature Evaluated",{feature:Ce,value:ve.value,source:ve.source,ruleId:ve.ruleId,...ve.experimentResult?{variationId:ve.experimentResult.key}:{}},Me)}),P=A.refresh;function v(){clearTimeout(g),!i&&(m||d!==a||!A.expiresAt||(g=setTimeout(()=>{k().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function k(){try{return await P()}finally{v()}}let N=()=>{m||k().catch(f)},B=A.subscribe(v),fe=i?.subscribe(()=>{!m&&i.fresh&&k().catch(f)});function Ie(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",N),B(),fe?.(),A.reset(),o.delete(Ie))}o.add(Ie);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(Ce){throw Ie(),Ce}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",N),Object.assign(A,{refresh:k,destroy:Ie})}return{features:c,reset(u){a++,u();for(let d of o)d()}}}var bh=require("zod");function Sh(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=bh.z.object({funnelId:Ga.shape.id,funnelVersionId:Ga.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new y("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new y("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new y("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await me(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return me(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return me(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return me(e,s,a(o))}}}function xh(e){let t=pr(e),n=t.request,r=kg(e.push,t,e.scope??e.configuration?.scope),i=ih(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=hh(n,i.isIdentified),o=yh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...jg(n,r),...ph(n),...mh(n),forFunnel(s){return Sh(n,s)},async features(s={}){return o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ii(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ii(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ii(a,Reflect.get(t,i)))}async function rs(e,t){let n=bg.safeParse(t);if(!n.success)throw new y("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Funnel scope changed");return r}var vi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function is(e){let t=Vt.test(e.apiKey);if(typeof window<"u"&&!t)throw new y("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!vi.test(e.apiKey))throw new y("INVALID_TOKEN","A customer credential or server API key is required");let n=pr({...e,timeoutMs:e.timeoutMs??35e3});return e.session||n.identify(e.apiKey),{async start(r){let i=Un.safeParse({...r,operation:"start"});if(!i.success||i.data.operation!=="start"||(t?i.data.customer!==void 0:i.data.customer===void 0))throw new y("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=fo.safeParse(await rs(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new y("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!Ii(s.run.parameters,a.parameters??{})||(a.customer?!s.customerId||a.customer.type==="id"&&s.customerId!==a.customer.value:s.customerId!==void 0))throw new y("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function Bu(e,t,n){if(Number(e.headers.get("content-length"))>t)throw n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0;try{for(;;){n.signal?.throwIfAborted();let c=await r.read();if(c.done)break;if(a+=c.value.length,a>t)throw n.error("limit");i.push(c.value)}}finally{await r.cancel().catch(()=>{})}n.signal?.throwIfAborted();let o=new Uint8Array(a),s=0;for(let c of i)o.set(c,s),s+=c.length;return o}async function Ih(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Bu(e,t,n))}function os(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&ru(n)===t.sha256}async function as(e,t){let n=Vr.parse(t),{artifact:r,environmentId:i}=n.content,a=new gn(e.baseUrl??dr).origin,o=new gn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new y("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c=setTimeout(()=>s.abort(),Zt.initializationMs);try{let u=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>r.byteLength)throw new y("INVALID_RESPONSE","Public Paywall is unavailable");let d=await Bu(u,r.byteLength,{signal:s.signal,error:m=>new y("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!os(d,r))throw new y("INVALID_RESPONSE","Public Paywall digest or size changed");return wf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))}finally{clearTimeout(c)}}var vh=(e,t)=>new y(e,t);async function Uu(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new y("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new y("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=AI(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function AI(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=hu({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:pn.parse(o)}),c=yI(s,n.document,{...t,...r}),u=c.steps.at(-1),d=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return d?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:d.nodeId,visit:d.visit,terminal:!c.boundary}:null}function yI(e,t,n){return Pg(e,t,n,vh)}var On=require("zod");var wh=Un.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Oh=On.z.strictObject({schemaVersion:On.z.literal(1),scope:ze,runId:On.z.uuid(),funnelId:On.z.uuid(),versionId:On.z.uuid(),command:wh.optional(),closeCommand:wh.refine(e=>e.operation==="close").optional(),purchase:On.z.strictObject({receiptId:On.z.uuid(),operationId:On.z.uuid(),generation:On.z.number().int().nonnegative()}).optional(),closed:On.z.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Yt=()=>new y("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ss=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function _h(e){let t=0,n=null,r=c=>JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]),i=Promise.resolve();async function a(){let c=await e.read();if(!Number.isSafeInteger(c.revision)||c.revision<0)throw new y("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:Oh.parse(c.entry)}}function o(c){let u=i.then(c);return i=u.catch(()=>{}),u}async function s(c){for(let u=0;u<4;u++){let d=await a();if(d.entry&&n!==null&&r(d.entry)!==n)throw Yt();let m=c(d.entry,d.revision);if(ss(d.entry,m)){t=d.revision;return}let w=await e.write(d.revision,m);if(w!==null){if(!Number.isSafeInteger(w)||w<=d.revision)throw Yt();t=w;return}}throw Yt()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw Yt();n=u},async load(){let c=await a();return t=c.revision,n=c.entry?r(c.entry):null,c.entry},retain(c){let u=Oh.parse(c),d=u.command;return!d||n!==null&&r(u)!==n?Promise.reject(Yt()):(n??(n=r(u)),o(()=>s((m,w)=>{if(m&&!ss(r(m),r(u)))throw Yt();if(!m){if(w!==t&&d.operation!=="close")throw Yt();return u}if(!m.command)return{...m,command:d,...d.operation==="close"?{closed:!0}:{}};if(d.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===d.requestId||m.closeCommand&&!ss(m.closeCommand,d))throw Yt();return{...m,closeCommand:d,closed:!0}}if(!ss(m.command,d))throw Yt();return m})))},observePurchase(c,u,d){return o(()=>s((m,w)=>{if(!m&&w!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw Yt();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw Yt();return d?!m?.purchase||m.purchase.operationId!==u.operationId?m:m.command?{...m,purchase:void 0}:null:{schemaVersion:1,...c,...m,purchase:u}}))},settle(c){return o(()=>s(u=>u?u.command&&"requestId"in u.command&&u.command.requestId===c?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand&&"requestId"in u.closeCommand&&u.closeCommand.requestId===c?{...u,closeCommand:void 0}:u:null))}}}function Ch(e){let t,n,r=()=>new y("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??dr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof y?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function Ph(e){let t=null,n=0,r=!1,i,a=0,o=new Set;return{get view(){return t},get generation(){return n},get disposed(){return r},get customerToken(){return i},get readSequence(){return a},nextRead(){return++a},assertCurrent(s,c="Run identity changed during the request"){if(s!==n||r)throw new y("IDENTITY_CHANGED",c)},assertRun(s){if(t&&(s.id!==t.id||s.source.type!==t.source.type||s.source.id!==t.source.id||s.source.versionId!==t.source.versionId||s.locale!==t.locale||!Ii(s.parameters,t.parameters)))throw new y("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new y("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,d,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&d!==void 0&&d<a)&&(s.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&t&&c.run.nodeId===t.nodeId&&c.run.visit===t.visit&&c.run.revision===t.revision&&(c.run.screen=t.screen,(t.paywall?.quote?.operationId===c.review?.activeOperationId||!t.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=t.paywall)),!(t?.paywall&&c.run.paywall&&t.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||c.run.revision>=t.revision)t=c.run;else if(!m)return;if(t)for(let w of o)try{w(structuredClone(t))}catch{}}},identify(s){if(!Vt.test(s))throw new y("INVALID_TOKEN","Customer credential required");n++,i=s},subscribe(s){return o.add(s),()=>o.delete(s)},reset(){r=!0,n++,i=void 0,t=null,o.clear()}}}function mr(e){let{customerToken:t,...n}=e;return n}var bI=e=>!(e instanceof y)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Eh({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,d=null,m=t?t.load().then(f=>{if(n.disposed)throw new y("IDENTITY_CHANGED","Controller was reset during command restoration");if(d=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let S=Un.parse(f.command);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");i=S,f.closeCommand&&(a=f.closeCommand,o=!0),S.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function w(f=i){if(t&&await m,!f)throw new y("INVALID_REQUEST","No command is pending");let S=f,A=n.generation;if(t){if(!n.view||!e.scope)throw new y("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await t.retain({schemaVersion:1,scope:e.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:mr(S)})}if(A!==n.generation||i!==S&&a!==S)throw new y("IDENTITY_CHANGED","Run changed before command dispatch");let P={...S,...n.customerToken?{customerToken:n.customerToken}:{}},v=c;c=!0;try{return await r(P,k=>{if(!k.settlement)throw new y("INVALID_RESPONSE","Exact command settlement is missing");if(k.settlement.requestId!==S.requestId)throw new y("INVALID_RESPONSE","Command settlement identity changed");if(A===n.generation&&(i===S||a===S)&&k.run.pendingRequest?.requestId!==S.requestId&&k.settlement.state==="settled"&&(!o||S.operation==="close"||k.settlement?.state==="settled"&&!["running","waiting"].includes(k.run.status))){let N=()=>A!==n.generation||i!==S&&a!==S?!1:(i===S&&(i=null),a===S&&(a=null),c=i!==null,d=null,!0);return t?t.settle(S.requestId).then(N):N()}return!1})}catch(k){throw A===n.generation&&i===S&&!v&&!bI(k)&&(t&&await t.settle(S.requestId),A===n.generation&&i===S&&(i=null,c=!1,d=null)),k}}function I(f){let S=Un.parse(f);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("INVALID_REQUEST","Mutation required");if(o&&S.operation!=="close"){if(i?.requestId===S.requestId)return g(S.requestId);throw new y("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(S.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(mr(a))!==JSON.stringify(mr(S)))throw new y("COMMAND_PENDING","Retry the original Close");return a??(a=S),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(mr(i))!==JSON.stringify(mr(S)))throw new y("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=S,c=!1;return p(i,"command")}function p(f,S){let A=w(f);s[S]=A;let P=()=>{s[S]===A&&(s[S]=null)};return A.then(P,P),A}async function g(f){let S=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(S.settlement?.requestId!==f)throw new y("INVALID_RESPONSE","Exact command settlement is missing");return S.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),S}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(f){if(d&&(f.run.id!==d.runId||f.run.source.id!==d.funnelId||f.run.source.versionId!==d.versionId))throw new y("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,S,A,P){t?.bind({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId}),t&&!e.scope&&(e.scope=S.scope);let v=S.run.paywall,k=v??S.purchase,N=k?.operation,B=S.settlement&&(!v||v.purchaseRequestId===S.settlement.requestId)&&(!u||u.operationId===S.settlement.operationId)?S.settlement:void 0,fe=N?.operationId??k?.quote?.operationId??B?.operationId,Ie=k?.receiptId??B?.receiptId,Ce=v?.selectionGeneration??u?.generation??0;if(t&&fe&&Ie&&f.operation!=="review"&&(!n.view||S.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Ce>=u.generation)){let ve={receiptId:Ie,operationId:fe,generation:Ce},Me=N?.status==="complete"||k?.canReselect===!0;return t.observePurchase({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId},ve,Me).then(()=>{n.assertCurrent(A),Me?u?.operationId===ve.operationId&&(u=void 0):u=ve})}},stop(){o=!0},submit:I,executePending:w,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function wi(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new y("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!vi.test(e.serverKey)))throw new y("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new y("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=pr({...e,session:void 0,...e.serverKey?{fetch:(f,S)=>{let A=new Headers(S?.headers),P=typeof S?.body=="string"?JSON.parse(S.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||A.set(Sg,e.serverKey),(e.fetch??globalThis.fetch)(f,{...S,headers:A})}}:{},...e.session?{fetch:async(f,S)=>{let A=await e.session.access(),P=typeof S?.body=="string"?JSON.parse(S.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new y("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...S,body:JSON.stringify({...P,customerToken:A})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Ph(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Ch(e):void 0),o=a&&_h(a),s=Eh({options:e,journal:o,state:n,call:c});async function c(f,S,A){let P=n.generation,v=()=>n.assertCurrent(P);o&&await s.ready,v();let k=n.view,N=fo.parse(await rs(e,await t.request("funnels",Un.parse(f))));if(f.operation==="review"&&!N.review)throw new y("INVALID_RESPONSE","Historical projection is missing");if(v(),N.runToken&&N.runToken!==e.runToken)throw new y("INVALID_RESPONSE","Run credential changed");let B=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(B&&N.settlement?.requestId!==B)throw new y("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(N),n.assertRun(N.run);let fe=s.observePurchase(f,N,P,A);if(fe&&await fe,!N.run.stopped&&["running","waiting"].includes(N.run.status)&&f.operation==="get"&&f.settlementRequestId)return N;let Ie=S?.(N),Ce=typeof Ie=="boolean"?Ie:Ie?await Ie:!1;return v(),["running","waiting"].includes(N.run.status)||s.stop(),n.publish(f,N,k,A,Ce),N}let u=s.submit,d=null,m=new WeakMap;function w(f){let S=m.get(f);if(S)return S;let A=p(f);return m.set(f,A),A}let I=!1;async function p(f){let S=await f;if(S.run.instruction?.type!=="evaluate_segment")return S;if(d)return d;I=!0;let A=n.generation,P=(async()=>{for(let v=0;v<32&&S.run.instruction?.type==="evaluate_segment";v++){if(s.pending||s.closeRequested)return S;let k=S.run;if(S.run.instruction?.type==="evaluate_segment"){let{advance:B}=await Uu(e.configuration,k,{predict:!1});if(A!==n.generation)throw new y("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return S;if(n.view&&(n.view.revision!==k.revision||n.view.visit!==k.visit||n.view.nodeId!==k.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let fe=!0;Uu(e.configuration,k).then(({prediction:Ie})=>{fe&&A===n.generation&&!s.closeRequested&&n.view?.id===k.id&&!n.view.stopped&&n.view.nodeId===k.nodeId&&n.view.visit===k.visit&&n.view.revision===k.revision&&(i=Ie)}).catch(()=>{});try{S=await u({operation:"commit_segment",requestId:yg(k.id,k.visit,`segment:${k.revision}`),nodeId:k.nodeId,visit:k.visit,revision:k.revision,...B})}finally{fe=!1,i=null}}}return S})();d=P;try{return await P}finally{d===P&&(d=null)}}let g={get configuration(){return I?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let f=s.closing??s.pending;return f?structuredClone(mr(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(mr(f)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let f=n.view;return i&&f&&!f.stopped&&["running","waiting"].includes(f.status)&&f.id===i.runId&&f.nodeId===i.from.nodeId&&f.visit===i.from.visit&&f.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(f){return as(e,f)},async pageExperiments(f,S=[]){let A=n.generation;n.assertCurrent(A);let P=n.view?.id;if(!P)throw new y("INVALID_REQUEST","Read the Run before its page experiments");let v=Rg.parse(await t.request("funnels",Eg.parse({operation:"page_experiments",release:f,usedReceiptIds:S,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(A),v.runId!==P||v.scope.projectId!==e.scope?.projectId||v.scope.environment!==e.scope?.environment)throw new y("SCOPE_MISMATCH","Page experiment Run changed");return v},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,S){o&&await s.ready,S??(S=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let A=n.nextRead();return w(c({operation:"get",...f?{data:f}:{},...S?{purchase:S}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,A))},resume(f=n.view?.pendingRequest?.requestId){return f?s.closeRequested?g.settle(f):s.pending?.requestId===f?w(u(s.pending)):w(u({operation:"resume",requestId:f})):Promise.reject(new y("INVALID_REQUEST","No interrupted command is available"))},submit(f){return w(u(f))},retry(){return s.closeFlight?s.closeFlight:s.closing?s.executePending(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?w(s.inFlight):s.pending?w(u(s.pending)):Promise.reject(new y("INVALID_REQUEST","No command is pending"))},identify(f){n.identify(f),i=null,t.identify(e.runToken)},subscribe:n.subscribe,reset(){r?.(),n.reset(),s.reset(),i=null,t.reset()}};return g}function Rh(e){if(!Vt.test(e.customerToken))throw new y("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new y("INVALID_REQUEST","An explicit App and environment scope is required");let t=is({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=wi({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function kh(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function jh(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new y("INVALID_RESPONSE",n)}function Th(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new y("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new y("INVALID_RESPONSE",n)}function Nh(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}async function Dh(e,t){if(!Vt.test(t.customerToken))throw new y("INVALID_TOKEN","A verified Customer credential is required");let n=pr(e);if(!e.session)n.identify(t.customerToken);else if(e.session.peek()!==t.customerToken)throw new y("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),i=null,a=!1,o=null,s=null,c=null,u=null,d=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await me(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await as(e,g.paywall)};if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new y("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!kh(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new y("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function w(p){if(!o)throw new y("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await me(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return jh(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=Nh(s,f.operation),structuredClone(s)}let I={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:m,async preview(p){if(!i)throw new y("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new y("INVALID_REQUEST","Choose an authored purchase action");let f=_m(g.product,p.selection,i.capabilities);if(!f)throw new y("PRODUCT_UNAVAILABLE","Choose an available Product");let S=gf(i.document.screen,f,p.selection,i.capabilities),A=O.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:f,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),P=JSON.stringify(A);if(c&&c!==P&&(!s||s.status==="pending"))throw new y("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===P){if(u)return u;if(o)return structuredClone(o)}c=P;let v=(async()=>{let k=O.previewAttach,N=await me(n.request,k,A);return Th(N.quote,{productVersionId:f,featureQuantities:S,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=N.quote,s=null,structuredClone(o)})();u=v;try{return await v}finally{u===v&&(u=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){d?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),I}function Fh(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new y("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new y("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new y("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let I=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,I)).catch(()=>{})}),d=e.nativeEvents?.(I=>{!n||!e.nativeModule||typeof I?.requestId!="string"||(async()=>{let p=await n;if(I.instanceId!==p)return;if(I.kind==="credential"){let S=r,A=null;try{if(!o&&I.revision===S){let P=await t.access();!o&&r===S&&(A=P)}}finally{await e.nativeModule.provideCredential(p,I.requestId,A)}return}let g=!1,f=r;try{if(o||I.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(I.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,I.requestId,g)}})().catch(()=>{})});async function m(I,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new y("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,S=await t.access();if(o||r!==f)throw c();if(!n){let v=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.tinker.cash",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let k=(async()=>{if(await g.identify(A,JSON.stringify({revision:f,credentials:S})),o||r!==f)throw await g.reset(A,f),c();i=f})();a={epoch:f,task:k}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let P=await g.invoke(A,I,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new y("INVALID_RESPONSE","Native host returned invalid JSON")}}async function w(I,p){let g=await m(I,p);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new y("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(I){return w("showFunnel",{runToken:I})},showPaywall(I){return w("showPaywall",I)},showContent(I){return w("showContent",I)},purchaseSubscription(I,p){return m("purchaseSubscription",{operationId:I,accepted:p})},switchSubscription(I,p){return m("switchSubscription",{operationId:I,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(I){return m("manageSubscriptions",I?{productId:I}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),d?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var SI=O.trackUsage.request.shape.command,xI=O.trackUsage.response;function II(e){let t=ze.parse(e.scope),n=xh({...e,scope:t}),r={...e,scope:t,session:n.session},i=0;n.subscribeIdentity(()=>{i++});let a=()=>{let o=n.session.peek();if(!o)throw new y("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:Fh(e,n.session),funnel(){return Rh({...r,customerToken:a()})},resumeFunnel(o){return a(),wi({...r,runToken:o})},paywall(o){return Dh(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new y("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new y("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=SI.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new y("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new y("IDENTITY_CHANGED","Customer identity changed during usage reporting");let d=xI.parse(u);if(d.scope.projectId!==t.projectId||d.scope.environment!==t.environment)throw new y("INVALID_RESPONSE","Usage response scope differs");return d}}}var Bh=require("zod");var Oi=require("zod");var vI=Oi.z.record(Oi.z.string().regex(/^[a-f0-9]{64}$/),Oi.z.strictObject({at:Oi.z.number(),text:Oi.z.string()})),Mh=2*1048576,wI=100;function OI(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function qh(e,t){let n=t===void 0?OI():t,r=Promise.resolve();async function i(o){if(!n)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>n.getItem(o)),new Promise(c=>{s=setTimeout(()=>c(null),wI)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=Mh)return vI.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return i(e)},writeManifest(o){Promise.resolve().then(()=>n?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await a())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=Zt.retentionMs?s.text:void 0},writeArtifact(o,s){n&&(r=r.catch(()=>{}).then(async()=>{let c=await a(),u=Date.now();c[o]={at:u,text:s};let d={},m=2,w=0;for(let[I,p]of Object.entries(c).sort(([,g],[,f])=>f.at-g.at)){if(p.at>u||u-p.at>Zt.retentionMs)continue;let g=new TextEncoder().encode(JSON.stringify({[I]:p})).byteLength;m+g>Mh||w>=128||(d[I]=p,m+=g,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(d))}).catch(()=>{}))}}}var _e=(e,t)=>new y(e,t),fr=()=>performance.now(),Vh=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Uh(e){let t=eu.parse(e.scope),n=new gn(e.origin??dr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw _e("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(ee=>{let H=new gn(ee);if(H.protocol!=="https:"||H.username||H.password||H.search||H.hash||H.pathname!=="/")throw _e("INVALID_URL","Invalid configuration asset origin");return H.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${It(t)}`,s=qh(o,e.storage),c,u=0,d=0,m=!1,w=!1,I=0,p=0,g,f,S,A,P=0,v=new Set,k=new Set,N=new Map,B=new Map,fe=0,Ie=!1;function Ce(){for(let ee of v)try{ee()}catch{}}function ve(ee){try{e.onError?.(ee)}catch{}}let Me=()=>!w&&!m&&!!c&&fr()<u&&Date.now()<d;function ke(){if(!Me())throw _e("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function zt(ee,H){let ce=new TextEncoder().encode(H).byteLength;if(!N.has(ee)){for(;N.size&&(N.size>=128||fe+ce>Zt.maxCacheBytes);){let ue=N.entries().next().value;fe-=new TextEncoder().encode(ue[1]).byteLength,N.delete(ue[0])}N.set(ee,H),fe+=ce}}function Xe(ee,H,ce){return Ih(ee,H,{signal:ce,error:ue=>_e("INVALID_RESPONSE",ue==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Tt(ee){let H=new gn(ee,n);if(!r.has(H.origin)||H.username||H.password||H.hash||H.search)throw _e("INVALID_URL","Configuration artifact origin is not trusted");return H.href}async function bo(ee,H,ce=!1){let ue=await i(Tt(ee),{method:"GET",credentials:"omit",redirect:"error",cache:ce?"default":"no-cache",signal:H,headers:{}});if(ue.status===429){let Ne=ue.headers.get("retry-after")??"";P=/^\d+$/.test(Ne)?Number(Ne)*1e3:Math.max(0,Date.parse(Ne)-Date.now())||15e3}if(!ue.ok&&ue.status!==304)throw _e(`CONFIGURATION_HTTP_${ue.status}`,"Configuration synchronization failed");return ue}function Gr(ee,H,ce){let ue=Date.parse(ee.headers.get("x-indiana-config-validated-at")??""),Ne=Date.parse(ee.headers.get("x-indiana-config-valid-until")??""),Ct=Date.parse(ee.headers.get("date")??""),Ke=ee.headers.get("age"),Xt=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![ue,Ne,Ct,Xt].every(Number.isFinite)||Ne<=ue||Ne-ue>Zt.maxControlAgeMs||ue>Ct+1e3)throw _e("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Pt=Math.min(Ne-ue,ce.maxControlAgeSeconds*1e3,Zt.maxControlAgeMs)-Math.max(Xt,Ct-ue,0)-(fr()-H);if(Pt<=0)throw _e("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return fr()+Pt}function st(){if(clearTimeout(S),clearTimeout(A),w||!v.size)return;Me()&&(A=setTimeout(()=>{Me()?st():Ce()},Math.max(1,u-fr())),Vh(A));let ee=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);S=setTimeout(()=>{$t().catch(ve)},Math.max(P,ee*(.8+Math.random()*.2))),Vh(S)}async function $t(){if(w)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let ee=I,H=new AbortController;f=H;let ce=(async()=>{if(!Ie){Ie=!0;try{let xo=await s.readManifest();if(xo&&!c){let Tn=nu.parse(JSON.parse(xo));It(Tn.scope)===It(t)&&(c=Tn)}}catch{}}H.signal.throwIfAborted();let Ke=c,Xt=fr(),Mt=await bo(a,H.signal);Mt.status===304&&(!Ke||!Mt.headers.has("x-indiana-config-validated-at")||!Mt.headers.has("x-indiana-config-valid-until")||!Mt.headers.has("age"))&&(Mt=await bo(a,H.signal));let Pt=Mt.status===304?Ke:nu.parse(JSON.parse(await Xe(Mt,Zt.maxManifestBytes,H.signal))),{generation:zn,...$n}=Pt,Ar=Mt.headers.get("etag");if(It(Pt.scope)!==It(t)||Sf($n)!==zn||Ar!==`"${zn}"`&&Ar!==`W/"${zn}"`)throw _e("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(Pt.revision<Ke.revision||Pt.revision===Ke.revision&&Pt.generation!==Ke.generation))throw _e("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[xo,Tn]of Object.entries(Ke?.funnels??{})){let yr=Pt.funnels[xo];if(yr&&(yr.controlRevision<Tn.controlRevision||yr.evaluationRevision<Tn.evaluationRevision||yr.controlRevision===Tn.controlRevision&&yr.state!==Tn.state||yr.evaluationRevision===Tn.evaluationRevision&&yr.evaluationMode!==Tn.evaluationMode))throw _e("INVALID_RESPONSE","Funnel control revision changed identity")}let Ku=Gr(Mt,Xt,Pt.policy);if(H.signal.throwIfAborted(),ee!==I)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Pt,u=Ku,d=Date.now()+Math.max(0,Ku-fr()),m=!1,p=0,P=0,s.writeManifest(It(Pt)),Ce(),structuredClone(Pt)})(),ue=setTimeout(()=>H.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs),Ne=new Promise((Ke,Xt)=>H.signal.addEventListener("abort",()=>Xt(H.signal.reason),{once:!0})),Ct=Promise.race([ce,Ne]).catch(Ke=>{throw p++,(Ke instanceof Bh.z.ZodError||Ke instanceof SyntaxError||Ke instanceof y&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,m=!0,Ce()),Ke}).finally(()=>{clearTimeout(ue),g===Ct&&(g=void 0),st()});return g=Ct,Ct}async function gr(ee){let H=ee.sha256,ce=zn=>os(zn,ee);Tt(ee.url);let ue=N.get(H);if(ue&&ce(ue))return N.delete(H),N.set(H,ue),ue;if(B.has(H))return B.get(H);let Ne=new AbortController;k.add(Ne);let Ct=I,Ke=(async()=>{try{let Ar=await s.readArtifact(H);if(Ar&&ce(Ar))return zt(H,Ar),Ar}catch{}Ne.signal.throwIfAborted();let zn=await bo(ee.url,Ne.signal,!0),$n=await Xe(zn,ee.byteLength,Ne.signal);if(!ce($n))throw _e("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(w||Ct!==I)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return zt(H,$n),s.writeArtifact(H,$n),$n})(),Xt=setTimeout(()=>Ne.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Zt.initializationMs),Mt=new Promise((zn,$n)=>Ne.signal.addEventListener("abort",()=>$n(Ne.signal.reason),{once:!0})),Pt=Promise.race([Ke,Mt]).finally(()=>{clearTimeout(Xt),k.delete(Ne),B.delete(H)});return B.set(H,Pt),Pt}async function hr(){return Me()||await $t(),ke(),c}async function _i(ee){let H,ce=new Promise((ue,Ne)=>{H=setTimeout(()=>Ne(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs)});try{return await Promise.race([ee(),ce])}finally{clearTimeout(H)}}function Ci(ee,H){if(ke(),c?.generation!==ee.generation)throw _e("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(H&&c.funnels[H]?.state!=="active")throw _e("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Lu(ee){let H=ee.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let ce=ee.artifacts[H];if(ce.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let ue=Cc.parse(JSON.parse(await gr(ce)));if(It(ue.scope)!==It({projectId:t.projectId,environment:t.environment})||ue.generation!==ce.generation||ue.remoteFeatures.some(Ne=>Object.hasOwn(ue.features,Ne)))throw _e("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ci(ee),{...ue,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-fr())).toISOString()}}async function zu(ee,H){let ce=await hr(),ue=ce.funnels[ee];H&&(!ue||ue.evaluationMode==="local"&&!ue.versions[H])&&(g&&await g,ce=await $t()),Ci(ce,ee);let Ne=ce.funnels[ee];if(Ne.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel executes at Indiana; public graph loading is disabled");let Ct=H??Ne.currentVersionId,Ke=Ne.versions[Ct];if(!Ke)throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(ce.artifacts[Ke.artifact].formatVersion!==3)throw _e("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Xt,Mt]=await Promise.all([gr(ce.artifacts[Ke.artifact]).then(Pt=>If(JSON.parse(Pt))),Ne.evaluationMode==="local"?Lu(ce):void 0]);if(Mt&&It(xf(Xt,Mt))!==It(Ke.dependencies))throw _e("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ci(ce,ee),{document:Xt,growth:Mt,versionId:Ct,control:structuredClone(Ne),manifest:structuredClone(ce)}}async function $u(ee,H){try{return await zu(ee,H)}catch(ce){if(!(ce instanceof y)||!(ce.code==="CONFIGURATION_CHANGED"||ce.code==="CONFIGURATION_HTTP_404"&&Me()))throw ce;let ue=c?.generation;if(g&&await g,await $t(),ce.code!=="CONFIGURATION_CHANGED"&&c?.generation===ue)throw ce;return zu(ee,H)}}function cs(){m=!0,Ce(),$t().catch(ve)}let So=()=>{(typeof document>"u"||document.visibilityState==="visible")&&cs()};function zh(ee){if(w)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(ee),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",cs),window.addEventListener("focus",So),document.addEventListener("visibilitychange",So)),st()),()=>{v.delete(ee),v.size||(clearTimeout(S),clearTimeout(A),Gu())}}function Gu(){typeof window<"u"&&(window.removeEventListener("online",cs),window.removeEventListener("focus",So),document.removeEventListener("visibilitychange",So))}return{scope:Object.freeze({...t}),refresh:$t,subscribe:zh,assertFresh:ke,assertFeatures(ee){ke();let H=c.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(ee!==void 0&&c.artifacts[H].generation!==ee)throw _e("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Me()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Me()?Math.max(0,u-fr()):0},async features(){return _i(async()=>Lu(await hr()))},pageExperiments:()=>_i(async()=>{let ee=await hr(),H=ee.gb.pageExperiments;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let ce=ee.artifacts[H];if(ce.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let ue=Og.parse(JSON.parse(await gr(ce)));if(ue.environmentId!==t.environmentId||ue.generation!==ce.generation)throw _e("INVALID_RESPONSE","Page experiment scope or generation changed");return Ci(ee),ue}),funnel:(ee,H)=>_i(()=>$u(ee,H)),paywall:(ee,H)=>_i(async()=>{let ce=await hr(),ue=ce.paywalls?.[ee];if(!ue||!H&&ue.state!=="published")throw _e("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ne=H??ue.currentVersionId,Ct=ue.versions[Ne],Ke=Ct&&ce.artifacts[Ct.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Xt=za.parse(JSON.parse(await gr(Ke)));return Ci(ce),{document:Xt,versionId:Ne,version:Ct.version,control:structuredClone(ue),manifest:structuredClone(ce)}}),async localFunnel(ee,H){let ce=await _i(()=>$u(ee,H));if(!ce.growth)throw _e("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:ue,remoteFeatures:Ne,...Ct}=ce.growth;return vg({scope:{projectId:t.projectId,environment:t.environment},funnelId:ee,versionId:ce.versionId,evaluationMode:"local",evaluationRevision:ce.control.evaluationRevision,document:ce.document,payload:Ct})},assertFunnel(ee,H,ce){ke();let ue=c.funnels[ee];if(!ue||ue.state!=="active")throw _e("FUNNEL_STOPPED","Funnel is paused or unavailable");if(ue.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel now executes at Indiana");if(H!==void 0&&ue.controlRevision!==H)throw _e("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(ce!==void 0&&!ue.versions[ce])throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!w){w=!0,I++,u=0,f?.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(S),clearTimeout(A),Gu(),Ce(),v.clear();for(let ee of k)ee.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));N.clear(),fe=0}}}}async function Lh(e){e={...e};let t=e.configuration;if(!t)throw new y("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&It(n)!==It(e.scope))throw new y("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new y("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=vi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new y("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=is({...e,scope:n,apiKey:e.credential}),o=s=>{let c=wi({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),d=await u.get();return{...c,...d,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new y("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}
17
+ */var Ae=j.z.json().superRefine((e,t)=>{let n=0;function r(i,a){if(++n>1e4||a>20){t.addIssue({code:"custom",message:"JSON exceeds its depth or node budget"});return}if(typeof i=="string"&&(i.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(i))&&t.addIssue({code:"custom",message:"JSON text must contain valid Unicode without NUL"}),Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))(o.includes("\0")||/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(o)||["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved JSON property"}),r(s,a+1)}r(e,0),new TextEncoder().encode(JSON.stringify(e)).byteLength>65536&&t.addIssue({code:"custom",message:"JSON exceeds 64 KiB"})}),xt=j.z.record(j.z.string().min(1).max(128),Ae).superRefine((e,t)=>{(!Ae.safeParse(e).success||Object.keys(e).length>128||new TextEncoder().encode(JSON.stringify(e)).byteLength>65536||["__proto__","constructor","prototype"].some(n=>Object.hasOwn(e,n)))&&t.addIssue({code:"custom",message:"Attribute document exceeds its budget or uses a reserved key"})}),XA=new Set(["$in","$ini","$inGroup","$nin","$nini","$notInGroup","$gt","$gte","$lt","$lte","$regex","$regexi","$ne","$eq","$size","$elemMatch","$all","$alli","$not","$type","$exists","$vgt","$vgte","$vlt","$vlte","$vne","$veq","$and","$or","$nor","$savedGroup"]),Ht=xt.superRefine((e,t)=>{function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r)){if(i==="$savedGroup"&&!j.z.strictObject({id:j.z.uuid(),attributeKey:j.z.string().min(1).max(128).optional()}).safeParse(a).success&&t.addIssue({code:"custom",message:"Saved groups use v2 object references"}),!i.startsWith("$")&&i.split(".").some(o=>["__proto__","prototype","constructor"].includes(o))&&t.addIssue({code:"custom",message:"Reserved attribute path"}),i.startsWith("$")&&!XA.has(i)&&t.addIssue({code:"custom",message:`Unknown GrowthBook operator: ${i}`}),["$regex","$regexi"].includes(i)&&typeof a=="string"){(/\(\?[<!=]|\\[0-9]|\\k</.test(a)||[...a.matchAll(/\{(\d+)(?:,(\d*))?\}/g)].some(o=>Number(o[1])>255||Number(o[2]||0)>255)||i==="$regexi"&&/[^\x00-\x7f]/.test(a.replace(/\\u([0-9a-f]{4})/gi,(o,s)=>String.fromCharCode(Number.parseInt(s,16)))))&&t.addIssue({code:"custom",message:"Regex is outside the shared TS/SQL subset"});try{new RegExp(a)}catch{t.addIssue({code:"custom",message:"Invalid regular expression"})}}n(a)}}typeof e.source=="string"&&["all","any","group","parameter","answer","attribute","result"].includes(e.source)&&("operator"in e||"predicates"in e||"groupId"in e)&&t.addIssue({code:"custom",message:"Obsolete condition protocol"}),n(e)}),ey=j.z.discriminatedUnion("type",[j.z.strictObject({type:j.z.literal("condition"),condition:Ht}),j.z.strictObject({type:j.z.literal("list"),attributeKey:j.z.string().min(1).max(128),values:j.z.array(j.z.union([j.z.string(),j.z.number().finite()])).max(1e5)})]).refine(e=>e.type!=="list"||new TextEncoder().encode(JSON.stringify(e.values)).byteLength<=1048576,"Saved group list exceeds 1 MiB");function Mn(e){let t=new Set;function n(r){if(Array.isArray(r))r.forEach(n);else if(r&&typeof r=="object")for(let[i,a]of Object.entries(r))i==="$savedGroup"&&a&&typeof a=="object"&&!Array.isArray(a)&&typeof a.id=="string"?t.add(a.id):["$inGroup","$notInGroup"].includes(i)&&typeof a=="string"?t.add(a):["$eq","$ne","$in","$nin","$ini","$nini"].includes(i)||n(a)}return n(e),[...t]}var ty=j.z.record(j.z.uuid(),ey).superRefine((e,t)=>{let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:"Cyclic saved group dependency"});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:"Missing saved group dependency"});return}n.add(a),o.type==="condition"&&Mn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),zs=j.z.tuple([j.z.number().min(0).max(1),j.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),pd=j.z.strictObject({attribute:j.z.string().optional(),seed:j.z.string().min(1),hashVersion:j.z.literal(2),ranges:j.z.array(zs).min(1).max(100)}),ny=j.z.strictObject({id:j.z.string().min(1).max(128),condition:Ht,gate:j.z.boolean().optional()}),Ls={id:j.z.string().max(128).optional(),condition:Ht.optional(),parentConditions:j.z.array(ny).max(50).optional(),filters:j.z.array(pd).max(20).optional()},ry=j.z.union([j.z.strictObject({...Ls}),j.z.strictObject({...Ls,force:Ae,coverage:j.z.number().min(0).max(1).optional(),range:zs.optional(),seed:j.z.string().min(1).optional(),hashAttribute:j.z.string().optional(),hashVersion:j.z.literal(2).optional()}),j.z.strictObject({...Ls,type:j.z.literal("experiment-ref"),experimentId:j.z.uuid(),values:j.z.record(j.z.string().min(1),Ae),meta:j.z.record(j.z.string().min(1),j.z.strictObject({passthrough:j.z.boolean()})).optional()})]),iy=j.z.strictObject({defaultValue:Ae,rules:j.z.array(ry).max(100)}),Xv=j.z.record(j.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),iy).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:"custom",message:"Too many Features"});let n=new Set,r=new Set;function i(a){if(n.has(a)){t.addIssue({code:"custom",message:`Cyclic Feature dependency: ${a}`});return}if(r.has(a))return;let o=e[a];if(!o){t.addIssue({code:"custom",message:`Unknown prerequisite Feature: ${a}`});return}n.add(a);for(let s of o.rules)for(let c of s.parentConditions??[])i(c.id);n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),oy=j.z.strictObject({name:j.z.string().max(80),reason:j.z.string().max(500),dateStarted:j.z.iso.datetime({offset:!0}),dateEnded:j.z.iso.datetime({offset:!0}).nullable(),coverage:j.z.number().min(0).max(1),variationWeights:j.z.array(j.z.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Ht,savedGroups:j.z.array(j.z.strictObject({match:j.z.enum(["any","all","none"]),ids:j.z.array(j.z.uuid()).min(1)})).max(50),namespace:j.z.strictObject({id:j.z.uuid(),ranges:j.z.array(zs).min(1)}).nullable(),seed:j.z.string().min(1).max(128)}),ay=j.z.strictObject({key:j.z.string().min(1).max(128),name:j.z.string().min(1).max(80),hypothesis:j.z.string().max(2e3),status:j.z.enum(["draft","running","stopped"]),hashAttribute:j.z.string().min(1).max(128),fallbackAttribute:j.z.string().max(128).nullable(),hashVersion:j.z.literal(2),disableStickyBucketing:j.z.boolean(),bucketVersion:j.z.number().int().min(0).max(1e3),minBucketVersion:j.z.number().int().min(0).max(1e3),variations:j.z.array(j.z.strictObject({id:j.z.string().min(1),key:j.z.string().min(1),name:j.z.string().max(80),description:j.z.string().max(500)})).min(2).max(20),phases:j.z.array(oy).min(1).max(100),releasedVariationId:j.z.string().nullable(),excludeFromPayload:j.z.boolean(),statusSchedule:j.z.strictObject({startAt:j.z.iso.datetime({offset:!0}).nullable(),stopAt:j.z.iso.datetime({offset:!0}).nullable(),stopAfter:j.z.strictObject({value:j.z.number().int().positive().max(36500),unit:j.z.enum(["hours","days"])}).nullable().optional()}).nullable()}).superRefine((e,t)=>{(e.minBucketVersion>e.bucketVersion||e.statusSchedule?.stopAt&&e.statusSchedule?.stopAfter||e.phases.some((n,r)=>{if(r===0)return!1;let i=e.phases[r-1];return!i?.dateEnded||Date.parse(n.dateStarted)<Date.parse(i.dateStarted)||Date.parse(i.dateEnded)>Date.parse(n.dateStarted)})||new Set(e.variations.map(n=>n.key)).size!==e.variations.length||new Set(e.variations.map(n=>n.id)).size!==e.variations.length||e.releasedVariationId!==null&&!e.variations.some(n=>n.id===e.releasedVariationId)||e.statusSchedule?.startAt&&e.statusSchedule?.stopAt&&Date.parse(e.statusSchedule.startAt)>=Date.parse(e.statusSchedule.stopAt)||e.phases.some(n=>n.dateEnded&&Date.parse(n.dateStarted)>=Date.parse(n.dateEnded)||n.namespace?.ranges.some(([r,i],a,o)=>r>=i||o.some(([s,c],u)=>u!==a&&r<c&&s<i)))||e.phases.some(n=>n.variationWeights.length!==e.variations.length))&&t.addIssue({code:"custom",message:"Invalid experiment versions, variation keys or weights"})});var sy=ay.safeExtend({filters:j.z.array(pd).optional()}),cy=j.z.strictObject({experiments:j.z.record(j.z.uuid(),sy),savedGroups:ty}),Ni=j.z.strictObject({attributeName:j.z.string(),attributeValue:j.z.string(),assignments:j.z.record(j.z.string(),j.z.string())}),ew=j.z.strictObject({snapshot:cy,attributes:xt,results:xt,stickyBucketAssignmentDocs:j.z.record(j.z.string(),Ni)}),tw=j.z.strictObject({variantKey:j.z.string().nullable(),bucketVersion:j.z.number().int().min(0),source:j.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:j.z.number().min(0).max(1).optional(),stickyBucketUsed:j.z.boolean().optional(),hashUsed:j.z.boolean().optional()});function Zn(e){let t=new Set,n=a=>a!==null&&typeof a=="object"&&!Array.isArray(a);function r(a,o){if(n(a))for(let[s,c]of Object.entries(a))s==="$elemMatch"?i(c,o):s==="$not"?r(c,o):s==="$all"&&Array.isArray(c)&&c.forEach(u=>r(u,o))}function i(a,o=""){if(n(a)){for(let[s,c]of Object.entries(a))if(["$and","$or","$nor"].includes(s)&&Array.isArray(c))c.forEach(u=>i(u,o));else if(s==="$not")i(c,o);else if(s==="$savedGroup"&&n(c))typeof c.attributeKey=="string"&&t.add(c.attributeKey);else if(!s.startsWith("$")){let u=o?`${o}.${s}`:s;t.add(u),r(c,u)}}}return i(e),[...t]}var uy=vt.z.enum(["active","inactive"]),ly=vt.z.preprocess((e,t)=>{let n=0;function r(i,a){if(!(++n>1e4||a>20)){if(Array.isArray(i))i.forEach(o=>r(o,a+1));else if(i&&typeof i=="object")for(let[o,s]of Object.entries(i))["__proto__","constructor","prototype"].includes(o)&&t.addIssue({code:"custom",message:"Reserved merchandise attribute"}),r(s,a+1)}}return r(e,0),e},xt),dy=vt.z.strictObject({id:vt.z.string().trim().min(1).max(255),name:vt.z.string().trim().min(1).max(255),status:uy,metadata:ly}),aw=dy.extend({internal_id:vt.z.uuid(),project_id:vt.z.uuid(),environment_id:vt.z.uuid(),created_at:vt.z.iso.datetime({offset:!0}),updated_at:vt.z.iso.datetime({offset:!0})}),fd=vt.z.union([vt.z.strictObject({id:vt.z.string().trim().min(1).max(255)}),vt.z.strictObject({internalId:vt.z.uuid()})]),sw=vt.z.enum(["customer","merchandise","context"]),cw=vt.z.enum(["system","stored","request"]),uw=vt.z.enum(["customer","merchandise","mixed"]),md=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function $s(e,t={},n=new Set){if(Zn(e).some(md))return!0;for(let r of Mn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&md(i.attributeKey)||i?.type==="condition"&&$s(i.condition,t,n))return!0}return!1}var gd=require("zod"),py=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,An=gd.z.string().max(16).regex(py,"\u8BED\u8A00\u4EE3\u7801\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u4F8B\u5982 zh-CN\u3001en").refine(e=>{try{return Intl.getCanonicalLocales(e)[0]===e}catch{return!1}},"\u6301\u4E45\u5316\u8BED\u8A00\u4EE3\u7801\u5FC5\u987B\u4F7F\u7528\u89C4\u8303\u5199\u6CD5");var gw=W.z.enum(["draft","active","paused","archived"]),Wn=W.z.discriminatedUnion("type",[W.z.object({type:W.z.literal("percent"),percentOff:W.z.number().min(1).max(100).multipleOf(.01)}).strict(),W.z.object({type:W.z.literal("amount"),amountOffCents:W.z.number().int().min(1).max(1e8),currency:he}).strict()]),tn=W.z.discriminatedUnion("type",[W.z.object({type:W.z.literal("once")}).strict(),W.z.object({type:W.z.literal("repeating"),months:W.z.number().int().min(1).max(36)}).strict(),W.z.object({type:W.z.literal("forever")}).strict()]),hd=[W.z.object({type:W.z.literal("all")}).strict(),W.z.object({type:W.z.literal("plans"),planIds:W.z.array(W.z.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],my=W.z.discriminatedUnion("type",[...hd,W.z.strictObject({type:W.z.literal("merchandise"),scope:W.z.discriminatedUnion("type",[W.z.strictObject({type:W.z.literal("all")}),W.z.strictObject({type:W.z.literal("selected"),merchandiseIds:W.z.array(W.z.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),W.z.strictObject({type:W.z.literal("condition"),condition:Ht})])})]),Gs=W.z.discriminatedUnion("type",[...hd,W.z.strictObject({type:W.z.literal("merchandise"),scope:W.z.strictObject({type:W.z.enum(["all","selected","condition"])})})]),fy=W.z.strictObject({firstPurchaseOnly:W.z.boolean(),condition:Ht}),hw=W.z.object({name:W.z.string().trim().min(1).max(80),description:W.z.string().max(500),discount:Wn,duration:tn,appliesTo:my,eligibility:fy,selfClaimEnabled:W.z.boolean().default(!1),startsAt:W.z.iso.datetime().nullable(),endsAt:W.z.iso.datetime().nullable(),totalLimit:W.z.number().int().min(1).max(1e6).nullable(),perCustomerLimit:W.z.number().int().min(1).max(10),grantWindowHours:W.z.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=>!$s(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"]}),Aw=W.z.object({code:W.z.string().trim().transform(e=>e.toUpperCase()).pipe(W.z.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:W.z.number().int().min(1).max(1e6).nullable(),expiresAt:W.z.iso.datetime().nullable(),firstPurchaseOnly:W.z.boolean(),minimumAmountCents:W.z.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:he.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var Di=W.z.object({id:W.z.uuid(),couponId:W.z.uuid(),status:W.z.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:W.z.iso.datetime(),expiresAt:W.z.iso.datetime(),coupon:W.z.object({name:W.z.string(),discount:Wn,duration:tn,appliesTo:Gs}).strict()}).strict(),Ad=W.z.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Id=h.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Ks=h.z.string().regex(/^(0|[1-9]\d{0,14})$/),Wr=h.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),gy=h.z.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Fi=gy,qn=ge.refine(e=>/[1-9]/.test(e)),Bt=h.z.iso.datetime({offset:!0}),Zo=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"))},hy=h.z.array(h.z.object({upTo:qn.nullable(),unitAmountMinor:Id,flatAmountMinor:h.z.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&&Zo(t.upTo)>Zo(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),Ay=h.z.discriminatedUnion("kind",[h.z.object({kind:h.z.literal("flat"),units:qn,unitAmountMinor:Id}).strict(),h.z.object({kind:h.z.enum(["graduated","volume"]),units:qn,tiers:hy}).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"),yy=h.z.strictObject({interval:h.z.enum(["month","year"]),count:h.z.number().int().min(1).max(12),anchor:h.z.enum(["membership","calendar"])}),Mi=h.z.object({currency:he,pricing:Ay,billingCycle:yy.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var yd={requestId:h.z.uuid(),productVersionId:h.z.uuid(),internal_feature_id:h.z.uuid(),currency:he},vd=h.z.strictObject({interval:h.z.enum(["hour","day","week","month"]),intervalCount:h.z.number().int().min(1).max(12),limit:h.z.number().int().min(1).max(1e6)}),wd=h.z.discriminatedUnion("kind",[h.z.object({...yd,kind:h.z.literal("auto_topup"),threshold:Mo,quantity:qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:vd.optional()}).strict(),h.z.object({...yd,kind:h.z.literal("postpaid"),maxAmountMinorPerPeriod:Fi,maxOutstandingMinor:Fi}).strict()]),bd={productVersionId:h.z.uuid(),internal_feature_id:h.z.uuid(),currency:he},Od=h.z.discriminatedUnion("kind",[h.z.object({...bd,kind:h.z.literal("auto_topup"),threshold:Mo,quantity:qn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:vd.optional(),purchaseAmountMinor:Fi,purchaseUnits:qn}).strict(),h.z.object({...bd,kind:h.z.literal("postpaid"),maxAmountMinorPerPeriod:Fi,maxOutstandingMinor:Fi,cashPrice:Mi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Wo=h.z.object({id:h.z.uuid(),terms:Od,status:h.z.enum(["prepared","active","revoked","blocked"]),createdAt:Bt,acceptedAt:Bt.nullable(),effectiveAt:Bt.nullable(),revokedAt:Bt.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"),_d=h.z.object({authorizationId:h.z.uuid(),terms:Od,setupUrl:h.z.url().nullable()}).strict(),Cd=h.z.object({authorizationId:h.z.uuid(),accepted:h.z.literal(!0)}).strict(),Pd=h.z.object({authorizationId:h.z.uuid(),requestId:h.z.uuid()}).strict(),Ed=h.z.object({internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable(),interval:h.z.enum(["day","week","month","year"]),anchor:h.z.enum(["billing_cycle","utc"]).optional(),basis:h.z.enum(["usage","credits"]),filter:St.optional(),limit:ge.nullable(),thresholds:h.z.array(h.z.number().positive().max(1)).max(8),includedThresholds:h.z.array(h.z.number().positive().max(1)).max(8).optional(),absoluteThresholds:h.z.array(qn).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&&Zo(t)>Zo(i)}),"Notification thresholds must increase"),by=Ed.safeExtend({requestId:h.z.uuid()}),Sd={control:h.z.literal("overage"),requestId:h.z.uuid(),internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable()},Sy=h.z.discriminatedUnion("action",[h.z.strictObject({...Sd,action:h.z.literal("set"),allowed:h.z.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.z.boolean()}),h.z.strictObject({...Sd,action:h.z.literal("remove")})]),Rd=h.z.union([by,Sy]),xy=h.z.strictObject({internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable(),allowed:h.z.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.z.boolean(),interval:h.z.enum(["day","week","month","year"]),startsAt:Bt,endsAt:Bt,used:h.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:h.z.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:h.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),Iy=h.z.object({internal_feature_id:h.z.uuid(),entityId:h.z.uuid().nullable(),interval:h.z.enum(["day","week","month","year"]),anchor:h.z.enum(["billing_cycle","utc"]).optional(),basis:h.z.enum(["usage","credits"]),filter:St.optional(),startsAt:Bt,endsAt:Bt,used:Kt,reserved:Kt,limit:ge.nullable(),thresholds:h.z.array(h.z.number().positive().max(1)).max(8),notifiedThresholds:h.z.array(h.z.number().positive().max(1)).max(1024),includedThresholds:h.z.array(h.z.number().positive().max(1)).max(8).optional(),includedAllowance:h.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:h.z.array(h.z.number().positive().max(1)).max(1024).optional(),absoluteThresholds:h.z.array(qn).max(8).optional(),notifiedAbsoluteThresholds:h.z.array(qn).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||ge.safeParse(e.used).success&&ge.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),vy=h.z.object({authorizationId:h.z.uuid(),status:h.z.enum(["idle","pending","blocked"]),taskId:h.z.uuid().nullable(),invoiceId:h.z.uuid().nullable(),hostedInvoiceUrl:h.z.url().nullable(),purchaseCount:h.z.number().int().nonnegative(),purchaseWindowEndsAt:Bt.nullable(),attemptCount:h.z.number().int().nonnegative(),failedAttemptCount:h.z.number().int().nonnegative(),suspendedAt:Bt.nullable(),nextAttemptAt:Bt.nullable(),failureReason:h.z.string().min(1).max(240).nullable()}).strict(),kd=h.z.object({internal_feature_id:h.z.uuid().optional(),entityId:h.z.uuid().optional()}).strict(),Hs=h.z.object({authorizations:h.z.array(Wo).max(100),limits:h.z.array(Ed).max(100),overages:h.z.array(xy).max(100).optional(),windows:h.z.array(Iy).max(200),autoTopups:h.z.array(vy).max(100),limited:h.z.boolean()}).strict(),wy=h.z.object({id:h.z.uuid(),internal_feature_id:h.z.uuid(),productVersionId:h.z.uuid(),authorizationId:h.z.uuid(),entityId:h.z.uuid().nullable(),units:ge,amountMinor:Wr,cashPrice:Mi}).strict(),qi=h.z.object({id:h.z.uuid(),sourceKind:h.z.enum(["product","usage","manual"]),providerInvoiceId:h.z.string().min(1).max(240).nullable(),status:h.z.enum(["accruing","open","pending","paid","failed","void"]),currency:he,startsAt:Bt.nullable(),endsAt:Bt.nullable(),amountMinor:h.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:h.z.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Ks,paidAmountMinor:Ks,refundedAmountMinor:Ks,createdAt:Bt,hostedInvoiceUrl:h.z.url().nullable(),adjustment:h.z.object({originalInvoiceId:h.z.uuid(),amountMinor:h.z.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:Bt.nullable(),reason:h.z.string().min(1).max(500).optional()}).strict().nullable(),lines:h.z.array(wy).max(100),linesLimited:h.z.boolean()}).strict(),jd=h.z.object({invoiceId:h.z.uuid(),accepted:h.z.literal(!0)}).strict(),Td=h.z.strictObject({requestId:h.z.uuid(),originalInvoiceId:h.z.uuid(),amountMinor:h.z.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:h.z.string().trim().min(1).max(500)}),Nd=h.z.object({after:h.z.uuid().nullable(),limit:h.z.number().int().min(1).max(100)}).strict(),Dd=h.z.object({rows:h.z.array(qi).max(100),nextCursor:h.z.uuid().nullable()}).strict(),xd=h.z.strictObject({id:h.z.string(),coupon:h.z.string(),start:h.z.number().nonnegative(),end:h.z.number().nullable()}),Oy=h.z.strictObject({subscriptionId:h.z.string(),customerId:h.z.string(),accountId:h.z.string(),sourceItems:h.z.array(h.z.strictObject({id:h.z.string(),price_id:h.z.string(),quantity:h.z.number().int(),discounts:h.z.array(xd).optional()})).max(100),items:h.z.array(h.z.strictObject({id:h.z.string(),price:h.z.string(),quantity:h.z.number().int(),discounts:h.z.array(h.z.strictObject({coupon:h.z.string().optional(),terms:h.z.strictObject({id:h.z.string(),name:h.z.string().optional(),percent_off:h.z.number().optional(),amount_off:h.z.number().optional(),currency:h.z.string().optional(),duration:h.z.enum(["once","forever","repeating"]),duration_in_months:h.z.number().optional()}).optional(),discount:h.z.string().optional(),receipt:xd.optional()})).max(20)})).max(100)}),Fd=h.z.strictObject({membershipId:h.z.uuid(),requestId:h.z.uuid(),grantIds:h.z.array(h.z.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Md=h.z.strictObject({membershipId:h.z.uuid(),operationId:h.z.uuid(),status:h.z.enum(["pending","effective"]),execution:Oy.nullable(),grants:h.z.array(h.z.strictObject({id:h.z.uuid(),couponId:h.z.uuid(),name:h.z.string(),discount:Wn,duration:tn,startedAt:Bt.nullable()})).max(20)});var Yr=require("zod");var qd=Yr.z.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Vd=Yr.z.number().int().min(1).max(1e3),Yo=Yr.z.object({cap:ge.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Yr.z.number().positive().max(1e4).nullable(),cycles:Yr.z.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");var Vn=require("zod");var Bd=Vn.z.strictObject({itemKey:Vn.z.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:Vn.z.uuid(),includedAmount:Vn.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Vn.z.number().int().min(0).max(1e4),terms:Vo,pricing:ki.optional(),unitAmountMinor:Vn.z.number().int().min(0).max(1e8),productId:Vn.z.string().min(1).max(255).nullable(),priceId:Vn.z.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{kl(e.includedAmount,e.terms.units,e.quantity),qo({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"})}});var Y=require("zod");var _r=ge.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Vi=Y.z.string().min(1).max(120),Xo=Y.z.enum(["cap","overflow"]),nn=(e,t)=>{let[n,r=""]=e.split(".");if(n===void 0||n==="")throw new Error("Invalid decimal value");return BigInt(n)*10n**BigInt(t)+BigInt(r.padEnd(t,"0"))},Bi=e=>{try{return e()}catch{return!1}},Ui=Y.z.discriminatedUnion("operation",[Y.z.object({operation:Y.z.literal("quote"),overageBehavior:Xo.optional(),internal_feature_id:Y.z.uuid(),entityId:Y.z.uuid().optional(),quantity:_r,properties:St}).strict(),Y.z.object({operation:Y.z.literal("consume"),overageBehavior:Xo.optional(),occurredAt:Y.z.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.z.uuid(),entityId:Y.z.uuid().optional(),quantity:ge,properties:St,idempotencyKey:Vi}).strict(),Y.z.object({operation:Y.z.literal("reserve"),occurredAt:Y.z.iso.datetime({offset:!0}).optional(),internal_feature_id:Y.z.uuid(),entityId:Y.z.uuid().optional(),quantity:_r,properties:St,idempotencyKey:Vi,expiresInSeconds:Y.z.number().int().min(1).max(86400)}).strict(),Y.z.object({operation:Y.z.literal("confirm"),operationId:Y.z.uuid(),quantity:_r,properties:St.optional(),idempotencyKey:Vi}).strict(),Y.z.object({operation:Y.z.literal("refund"),operationId:Y.z.uuid(),quantity:_r,idempotencyKey:Vi}).strict(),Y.z.object({operation:Y.z.literal("release"),operationId:Y.z.uuid(),idempotencyKey:Vi}).strict()]),Qs=Y.z.object({internal_credit_feature_id:Y.z.uuid().nullable(),internal_metered_feature_id:Y.z.uuid(),dimension:Y.z.string().min(1).max(64),counterKey:Y.z.string().min(1).max(240),cycleStart:Y.z.iso.datetime({offset:!0}),unitCost:ge,units:_r,amount:Kt,tier:Y.z.number().int().min(1).max(12).nullable()}).strict(),Cr=Y.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Ud(e,t){let n=e.reduce((r,i)=>r+nn(i.units,12),0n)-nn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var Ld=Y.z.discriminatedUnion("funding",[Y.z.strictObject({funding:Y.z.literal("balance"),sourceId:Y.z.uuid(),rolloverId:Y.z.uuid().nullable(),units:Cr.refine(e=>/[1-9]/.test(e)),amount:Kt}),Y.z.strictObject({funding:Y.z.literal("unbilled"),units:Cr.refine(e=>/[1-9]/.test(e))}),Y.z.object({funding:Y.z.literal("prepaid"),sourceId:Y.z.uuid(),units:_r,amount:Kt,pricing:Y.z.array(Qs).min(1).max(12)}).strict().refine(e=>Bi(()=>e.pricing.reduce((t,n)=>t+nn(n.units,6),0n)===nn(e.units,6)&&e.pricing.reduce((t,n)=>t+nn(n.amount,12),0n)===nn(e.amount,12)&&e.pricing.every(t=>nn(t.unitCost,6)*nn(t.units,6)===nn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),Y.z.object({funding:Y.z.literal("postpaid"),invoiceLineId:Y.z.uuid().nullable(),units:_r,authorizationId:Y.z.uuid()}).strict()]),ea=Y.z.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),zd=Y.z.object({allowed:Y.z.boolean(),internal_feature_id:Y.z.uuid(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Xo.optional(),reason:ea.nullable(),allocations:Y.z.array(Ld).max(500)}).strict().refine(e=>Bi(()=>e.allowed?e.reason===null&&Ud(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>Bi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&nn(e.requestedQuantity,6)>=nn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Li=Y.z.object({id:Y.z.uuid(),internal_feature_id:Y.z.uuid(),kind:Y.z.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:Y.z.uuid().nullable(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Xo.optional(),accepted:Y.z.boolean(),reason:Y.z.enum([...ea.options,"expired"]).nullable(),createdAt:Y.z.iso.datetime({offset:!0}),reservationStatus:Y.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:Y.z.iso.datetime({offset:!0}).nullable(),allocations:Y.z.array(Ld).max(500)}).strict().refine(e=>Bi(()=>e.accepted?e.reason===null&&Ud(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>Bi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&nn(e.requestedQuantity,6)>=nn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");var Ee=require("zod");var Pr=Ee.z.iso.datetime({offset:!0}),$d=ge.refine(e=>/[1-9]/.test(e)),Gd=Ee.z.strictObject({interval:qd.exclude(["lifetime"]),count:Vd}),_y=Ee.z.strictObject({action:Ee.z.literal("create"),requestId:Ee.z.uuid(),internal_feature_id:Ee.z.uuid(),entityId:Ee.z.uuid().nullable(),amount:$d.nullable(),expiresAt:Pr.nullable(),reset:Gd.nullable(),rollover:Yo.nullable(),nextResetAt:Pr.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),Kd=Ee.z.discriminatedUnion("action",[_y,Ee.z.strictObject({action:Ee.z.literal("update"),requestId:Ee.z.uuid(),grantId:Ee.z.uuid(),revision:Ee.z.number().int().nonnegative(),amount:$d.nullable(),expiresAt:Pr.nullable(),rollover:Yo.nullable(),nextResetAt:Pr.nullable()}),Ee.z.strictObject({action:Ee.z.enum(["add","subtract","set_remaining"]),requestId:Ee.z.uuid(),grantId:Ee.z.uuid(),revision:Ee.z.number().int().nonnegative(),amount:ge}),Ee.z.strictObject({action:Ee.z.literal("revoke"),requestId:Ee.z.uuid(),grantId:Ee.z.uuid(),revision:Ee.z.number().int().nonnegative()})]),Js=Ee.z.strictObject({id:Ee.z.uuid(),internal_feature_id:Ee.z.uuid(),entityId:Ee.z.uuid().nullable(),amount:ge.nullable(),reset:Gd.nullable(),rollover:Yo.nullable(),nextResetAt:Pr.nullable(),startsAt:Pr,expiresAt:Pr.nullable(),revision:Ee.z.number().int().nonnegative(),revoked:Ee.z.boolean(),available:Kt,held:Kt,spent:Kt}),Hd=Ee.z.strictObject({customerId:Ee.z.uuid(),after:Ee.z.uuid().nullable(),limit:Ee.z.number().int().min(1).max(100)}),Qd=Ee.z.strictObject({rows:Ee.z.array(Js).max(100),nextCursor:Ee.z.uuid().nullable()});var ne=require("zod");var _n=ne.z.iso.datetime({offset:!0}),Jd=ne.z.strictObject({invoiceId:ne.z.uuid(),after:ne.z.string().min(1).max(180).nullable(),limit:ne.z.number().int().min(1).max(100)}),Cy=ne.z.strictObject({kind:ne.z.literal("product"),key:ne.z.string(),productVersionId:ne.z.uuid(),productName:ne.z.string(),itemKey:ne.z.string(),entityId:ne.z.uuid().nullable(),quantity:ne.z.number().positive(),subtotalMinor:ne.z.string().regex(/^-?\d+$/),discountMinor:ne.z.string().regex(/^\d+$/),taxMinor:ne.z.string().regex(/^-?\d+$/).nullable(),totalMinor:ne.z.string().regex(/^-?\d+$/),startsAt:_n.nullable(),endsAt:_n.nullable(),providerLineId:ne.z.string().nullable(),providerItemId:ne.z.string()}),Zd=ne.z.strictObject({invoice:qi,items:ne.z.array(ne.z.discriminatedUnion("kind",[Cy,ne.z.strictObject({kind:ne.z.literal("invoice_credit"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),units:ge,reserved:ge,amountMinor:Wr,grossAmountMinor:Wr,creditsAppliedMinor:Wr,properties:St,cashPrice:Mi,providerItemId:ne.z.string().nullable(),creditProviderItemId:ne.z.string().nullable()}),ne.z.strictObject({kind:ne.z.literal("usage"),key:ne.z.string(),internal_feature_id:ne.z.uuid(),name:ne.z.string(),units:ge,reserved:ge,amountMinor:Wr,cashPrice:Mi})])).max(100),nextCursor:ne.z.string().min(1).max(180).nullable()}),Py=ne.z.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Zs=ne.z.strictObject({from:_n,to:_n,entityId:ne.z.uuid().optional(),snapshotAt:_n.nullable(),after:ne.z.strictObject({at:_n,id:ne.z.uuid(),position:ne.z.number().int().nonnegative()}).nullable(),limit:ne.z.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"),Wd=ne.z.strictObject({customerId:ne.z.uuid(),entityId:ne.z.uuid().nullable(),from:_n,to:_n,snapshotAt:_n,totals:ne.z.array(ne.z.strictObject({internal_credit_feature_id:ne.z.uuid(),name:ne.z.string(),consumed:Kt,refunded:Kt,net:Py})).max(1e3),rows:ne.z.array(ne.z.strictObject({operationId:ne.z.uuid(),position:ne.z.number().int().nonnegative(),kind:ne.z.enum(["consume","confirm","refund"]),originalId:ne.z.uuid().nullable(),occurredAt:_n,internal_feature_id:ne.z.uuid(),entitlementName:ne.z.string(),sourceId:ne.z.uuid(),internal_credit_feature_id:ne.z.uuid(),creditName:ne.z.string(),units:Cr,amount:Kt,pricing:ne.z.array(Qs).max(12),properties:St})).max(100),nextCursor:Zs.shape.after});var T=require("zod");var ln=require("zod");var Ey=ln.z.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Ry=ln.z.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),ta=ln.z.strictObject({internal_feature_id:ln.z.uuid(),entityId:ln.z.uuid().nullable()}),Yd=ta.extend({quantity:ge,expectedRevision:ln.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:ln.z.string().min(1).max(120),properties:St.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),zi=ta.extend({operationId:ln.z.uuid().nullable(),usage:ge,capacity:Ey.nullable(),remaining:Ry.nullable(),withinLimit:ln.z.boolean(),revision:ln.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ln.z.iso.datetime({offset:!0}).nullable()}).strict().superRefine((e,t)=>{let n=r=>{let i=r.startsWith("-"),[a,o=""]=(i?r.slice(1):r).split(".");if(a===void 0||a==="")throw new Error("Invalid decimal value");return(i?-1n:1n)*(BigInt(a)*10n**12n+BigInt(o.padEnd(12,"0")))};(e.capacity===null!=(e.remaining===null)||(e.capacity===null?!e.withinLimit:e.remaining===null||n(e.remaining)!==n(e.capacity)-n(e.usage)||e.withinLimit!==n(e.remaining)>=0n)||e.revision===0!=(e.operationId===null)||e.operationId===null!=(e.updatedAt===null))&&t.addIssue({code:"custom",message:"Absolute usage must conserve capacity and its immutable revision"})});var Ut=T.z.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),yn=T.z.iso.datetime({offset:!0}),ky=T.z.enum(["access","metered","credit"]),$i={internal_feature_id:T.z.uuid(),key:Ir,name:T.z.string().min(1).max(120),kind:ky},Xd=T.z.object({customerId:T.z.uuid(),snapshotAt:yn,memberships:T.z.array(T.z.object({id:T.z.uuid(),productId:T.z.string().min(1).max(255),productVersionId:T.z.uuid(),billingProductVersionId:T.z.uuid(),version:T.z.number().int().positive(),key:T.z.string().min(1).max(64),name:T.z.string().min(1).max(120),groupId:T.z.string().max(255).nullable(),membershipType:T.z.enum(["main","addon"]),status:T.z.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:T.z.boolean(),accessEnabled:T.z.boolean(),renewalChange:T.z.object({productVersionId:T.z.uuid(),name:T.z.string().min(1).max(120),version:T.z.number().int().positive(),effectiveAt:yn,benefitsAppliedAt:yn.nullable(),timing:T.z.enum(["immediate","renewal"]),changeKind:T.z.enum(["plan","seats","quantity"]),feature:T.z.strictObject({internal_feature_id:T.z.uuid(),name:T.z.string().min(1).max(80),fromQuantity:T.z.number().int().min(0).max(1e4),toQuantity:T.z.number().int().min(0).max(1e4)}).optional(),seat:T.z.object({key:T.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:T.z.number().int().min(0).max(1e4),toQuantity:T.z.number().int().min(0).max(1e4)}).strict().nullable(),status:T.z.enum(["prepared","quoted","confirmed","pending","scheduled"])}).strict().refine(e=>e.changeKind==="seats"==(e.seat!==null)&&e.changeKind==="quantity"==(e.feature!==void 0),"Quantity changes require their fixed component identities and quantities").nullable(),period:T.z.object({phase:T.z.enum(["paid","trial"]),startsAt:yn,endsAt:yn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:T.z.boolean(),balances:T.z.array(T.z.object({...$i,usageType:T.z.enum(["consumable","non_consumable"]).nullable(),accessible:T.z.boolean(),unlimited:T.z.boolean(),available:Ut,held:Ut,debt:Ut,nextExpiresAt:yn.nullable(),usage:zi.nullable()}).strict().refine(e=>e.kind==="metered"==(e.usageType!==null)&&(e.accessible||e.available==="0"&&e.held==="0")&&(e.usageType==="non_consumable"?e.usage!==null&&e.usage.internal_feature_id===e.internal_feature_id&&e.unlimited===(e.usage.capacity===null)&&e.available===(e.usage.remaining===null||e.usage.remaining.startsWith("-")?"0":e.usage.remaining)&&e.held==="0"&&e.debt==="0":e.usage===null),"Balances must expose their actual spendable or non-consumable state")).max(500),balancesLimited:T.z.boolean()}).strict(),ep=T.z.enum(["source","usage","transaction","invoice","debt","settlement"]),na=T.z.object({at:yn,id:T.z.uuid(),type:ep}).strict(),tp=T.z.object({type:ep.nullable(),resourceKey:Ir.optional(),kind:T.z.enum(["purchase","refund"]).optional(),topup:T.z.boolean().optional(),from:T.z.iso.date().nullable(),to:T.z.iso.date().nullable(),after:na.nullable(),limit:T.z.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Xr={id:T.z.uuid(),occurredAt:yn},jy=T.z.discriminatedUnion("type",[T.z.strictObject({...Xr,type:T.z.literal("invoice"),status:T.z.string().min(1).max(80),paid:Ut,refunded:Ut,currency:he,externalId:T.z.string().nullable()}),T.z.object({...Xr,...$i,type:T.z.literal("source"),reason:T.z.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Ut,unlimited:T.z.boolean(),status:T.z.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:yn,expiresAt:yn.nullable(),orderId:T.z.uuid().nullable(),parentSourceId:T.z.uuid().nullable()}).strict(),T.z.object({...Xr,type:T.z.literal("usage"),internal_feature_id:T.z.uuid(),name:T.z.string().min(1).max(120),kind:T.z.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:T.z.uuid().nullable(),quantity:ge,accepted:T.z.boolean(),reason:T.z.enum([...ea.options,"expired"]).nullable(),properties:St,reservationStatus:T.z.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:yn.nullable(),charges:T.z.array(T.z.discriminatedUnion("funding",[T.z.strictObject({funding:T.z.literal("balance"),sourceId:T.z.uuid(),rolloverId:T.z.uuid().nullable(),units:Cr,amount:Ut}),T.z.strictObject({funding:T.z.literal("unbilled"),units:Cr}),T.z.object({...$i,funding:T.z.literal("prepaid"),amount:Ut}).strict(),T.z.object({funding:T.z.literal("postpaid"),invoiceId:T.z.uuid(),invoiceLineId:T.z.uuid(),authorizationId:T.z.uuid(),units:ge,currency:he}).strict()])).max(500)}).strict().refine(e=>(e.kind==="set_usage"||e.kind==="consume"&&e.quantity==="0"?e.accepted&&e.reason===null&&e.charges.length===0&&e.reservationStatus===null:e.accepted?e.reason===null&&e.charges.length>0:e.reason!==null&&e.charges.length===0)&&e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null),"Usage facts must retain their original outcome and receipt"),T.z.object({...Xr,type:T.z.literal("transaction"),purpose:T.z.enum(["product","invoice"]),productVersionId:T.z.uuid().nullable(),productName:T.z.string().min(1).max(120).nullable(),productVersion:T.z.number().int().positive().nullable(),invoiceId:T.z.uuid().nullable(),orderId:T.z.uuid(),originalId:T.z.uuid().nullable(),kind:T.z.enum(["purchase","refund"]),amountMinor:T.z.number().int().nonnegative().max(2e8).nullable(),currency:he.nullable()}).strict().refine(e=>e.currency===null==(e.amountMinor===null)&&(e.purpose==="product"?e.productVersionId!==null&&e.productName!==null&&e.productVersion!==null&&e.invoiceId===null:e.productVersionId===null&&e.productName===null&&e.productVersion===null&&e.invoiceId!==null)&&e.kind==="refund"==(e.originalId!==null)&&(e.kind!=="refund"||e.amountMinor===null||e.amountMinor>0),"Payment fact provenance is incomplete"),T.z.object({...Xr,...$i,type:T.z.literal("debt"),sourceId:T.z.uuid(),transactionId:T.z.uuid(),amount:Ut}).strict(),T.z.object({...Xr,...$i,type:T.z.literal("settlement"),sourceId:T.z.uuid(),debtId:T.z.uuid(),kind:T.z.enum(["payment","usage_refund","payment_return"]),amount:Ut}).strict()]),np=T.z.object({customerId:T.z.uuid(),rows:T.z.array(jy).max(50),nextCursor:na.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");var le=require("zod"),ip=le.z.object({customerId:le.z.uuid()}).strict(),op=le.z.discriminatedUnion("action",[le.z.object({customerId:le.z.uuid(),requestId:le.z.uuid(),action:le.z.literal("assign"),poolId:le.z.uuid(),memberCustomerId:le.z.uuid()}).strict(),le.z.strictObject({customerId:le.z.uuid(),requestId:le.z.uuid(),action:le.z.literal("assign_entity"),poolId:le.z.uuid(),entityId:le.z.uuid()}),le.z.object({customerId:le.z.uuid(),requestId:le.z.uuid(),action:le.z.literal("release"),poolId:le.z.uuid(),slotId:le.z.uuid()}).strict()]),Gi=le.z.number().int().nonnegative(),Ws=le.z.iso.datetime({offset:!0}),Ys=le.z.strictObject({internalId:le.z.uuid(),id:le.z.string(),name:le.z.string().nullable(),version:le.z.number().int().positive()}),rp=le.z.enum(["active","past_due"]),Xs=le.z.strictObject({customerId:le.z.uuid(),licenses:le.z.array(le.z.strictObject({id:le.z.uuid(),linkId:le.z.uuid(),parent:le.z.strictObject({customerProductId:le.z.uuid(),status:rp,product:Ys}),product:Ys,planLicense:le.z.strictObject({id:le.z.uuid(),prepaidOnly:le.z.boolean(),isCustom:le.z.boolean()}).nullable(),granted:Gi,included:Gi,paidQuantity:Gi,usage:Gi,remaining:Gi,createdAt:Ws}).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:le.z.array(le.z.strictObject({id:le.z.uuid(),linkId:le.z.uuid(),status:rp,product:Ys,entity:le.z.strictObject({internalId:le.z.uuid(),id:le.z.string().nullable(),name:le.z.string().nullable()}).nullable(),beneficiary:le.z.strictObject({internalId:le.z.uuid(),id:le.z.string().nullable(),name:le.z.string().nullable()}).nullable(),startedAt:Ws.nullable(),endedAt:Ws.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:le.z.boolean()});var se=require("zod"),Ki=se.z.enum(["email","sms","voice","push"]),Kw=se.z.enum(["resend","twilio","fcm","apns"]);var Hw=se.z.string().regex(/^\+[1-9]\d{1,14}$/),Ty=se.z.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Ny=se.z.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Dy=se.z.strictObject({subject:Ny,html:se.z.string().min(1).max(131072).optional(),text:se.z.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),Fy=se.z.strictObject({body:se.z.string().min(1).max(1600).refine(e=>e.trim().length>0)}),My=se.z.strictObject({text:se.z.string().trim().min(1).max(4e3),language:se.z.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:se.z.number().int().min(1).max(900)}),qy=se.z.record(se.z.string().min(1).max(64),se.z.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"),Vy=se.z.strictObject({title:se.z.string().trim().min(1).max(200),body:se.z.string().trim().min(1).max(2e3),url:se.z.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:qy.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),ap=se.z.discriminatedUnion("channel",[se.z.strictObject({channel:se.z.literal("email"),content:Dy}),se.z.strictObject({channel:se.z.literal("sms"),content:Fy}),se.z.strictObject({channel:se.z.literal("voice"),content:My}),se.z.strictObject({channel:se.z.literal("push"),content:Vy})]),sp=se.z.strictObject({requestId:se.z.uuid(),customerId:se.z.uuid(),connectionId:se.z.uuid().optional(),message:ap,expiresAt:se.z.iso.datetime({offset:!0})}),By=se.z.array(se.z.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),Uy=se.z.discriminatedUnion("kind",[se.z.strictObject({kind:se.z.literal("all")}),se.z.strictObject({kind:se.z.literal("customers"),customerIds:By})]),Qw=se.z.strictObject({name:se.z.string().trim().min(1).max(120),connectionId:se.z.uuid().optional(),message:ap,audience:Uy,frequencyLimit:se.z.number().int().min(1).max(100)}),cp=se.z.strictObject({requestId:se.z.uuid(),channel:Ki,state:se.z.enum(["allowed","denied"]),expectedRevision:se.z.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),up=se.z.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),lp=se.z.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),Jw=se.z.strictObject({meter:Ty,estimatedUnits:se.z.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:se.z.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});var Se=require("zod");var te=require("zod");var Er=require("zod");var Hi=Er.z.strictObject({internalFeatureId:Er.z.uuid(),name:Er.z.string().min(1).max(120),includedAmount:Er.z.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Er.z.enum(["hour","day","week","month","year","lifetime"]),resetCount:Er.z.number().int().min(1).max(100),terms:Vo});var tt=require("zod");var mp=require("zod");var Rr=require("zod"),dp=Rr.z.enum(["stripe","apple","google","merchant"]),pp=Rr.z.enum(["membership","credit_pack","lifetime"]),Xw=Rr.z.enum(["active","grace","suspended","inactive","revoked"]),eO=Rr.z.strictObject({currency:Rr.z.string().regex(/^[A-Z]{3}$/),micros:Rr.z.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ei=mp.z.object({provider:dp,currency:he}).strict();var Yn=tt.z.strictObject({internal_feature_id:tt.z.uuid(),quantity:ge.refine(e=>/[1-9]/.test(e)),properties:St,entityId:tt.z.uuid().optional()}),fp=tt.z.strictObject({requirement:Yn,commerce:ei.optional(),paywallId:tt.z.uuid().optional()}),Ly=tt.z.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),ec=tt.z.strictObject({productId:tt.z.string().min(1),productVersionId:tt.z.string().min(1),name:tt.z.string().min(1).max(120),action:tt.z.enum(["purchase","upgrade","addon","topup"]),membershipId:tt.z.string().min(1).nullable(),currency:he,amountMinor:tt.z.string().regex(/^(0|[1-9]\d{0,8})$/),interval:tt.z.enum(["free","week","month","year","one_time"]),intervalCount:tt.z.number().int().min(1).max(156)}),kr=tt.z.strictObject({internal_feature_id:tt.z.string().min(1),name:tt.z.string().min(1).max(120),kind:tt.z.enum(["access","metered","credit"]),quantity:ge,allowed:tt.z.boolean(),reason:Ly.nullable(),preview:tt.z.strictObject({scenario:tt.z.enum(["feature_flag","usage_limit"]),candidates:tt.z.array(ec).max(20)}).nullable()}).superRefine((e,t)=>{(e.allowed!==(e.reason===null)||e.allowed&&e.preview!==null||new Set(e.preview?.candidates.map(n=>n.productVersionId)).size!==(e.preview?.candidates.length??0)||e.preview?.candidates.some(n=>n.action==="upgrade"!=(n.membershipId!==null)))&&t.addIssue({code:"custom",message:"Invalid access recommendation"})}),cO=tt.z.strictObject({paywallId:tt.z.uuid(),requirement:Yn});var ia=te.z.object({plan:te.z.string().min(1).max(200).optional(),coupon:te.z.uuid().optional(),promotionCode:te.z.uuid().optional(),picker:te.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ra=te.z.object({text:te.z.string().optional(),label:te.z.string().optional(),alt:te.z.string().optional(),html:te.z.string().max(32768).optional(),price:te.z.object({current:te.z.string(),original:te.z.string().nullable(),period:te.z.string()}).optional(),code:te.z.string().optional(),countdownAt:te.z.iso.datetime().optional(),planId:te.z.string().min(1).max(200).optional(),planVersionId:te.z.string().min(1).max(200).optional(),currency:he.optional(),couponId:te.z.uuid().optional(),offerId:te.z.uuid().optional(),unavailable:te.z.boolean().optional(),unavailableReason:te.z.string().optional(),missing:te.z.array(te.z.string()).optional()}).strict(),ti=te.z.object({paywall:kr.optional(),nodes:te.z.record(te.z.string(),te.z.object({base:ra,picker:te.z.string().optional(),byPlan:te.z.record(te.z.string(),ra).optional()}).strict()),plans:te.z.record(te.z.string(),te.z.object({id:te.z.string().min(1).max(200),versionId:te.z.string().min(1).max(200),available:te.z.boolean(),name:te.z.string(),price:te.z.string(),period:te.z.string(),currency:he.optional(),amountMinor:te.z.number().int().nonnegative().optional(),interval:te.z.enum(["free","week","month","year","one_time"]).optional(),intervalCount:te.z.number().int().positive().optional(),prepaid:te.z.array(Hi).max(100).optional()}).strict()),pickers:te.z.record(te.z.string(),te.z.object({options:te.z.array(te.z.string().min(1).max(200)).max(20),selected:te.z.string().min(1).max(200).nullable()}).strict()),quantities:te.z.record(te.z.string(),te.z.strictObject({minimum:te.z.number().int().nonnegative(),maximum:te.z.number().int().nonnegative(),step:te.z.number().int().positive(),value:te.z.number().int().nonnegative(),label:te.z.string(),available:te.z.boolean()})).optional(),diagnostics:te.z.array(te.z.object({nodeId:te.z.string(),message:te.z.string()}).strict())}).strict();function gp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}var b=require("zod");function zy(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function hp(e){let t={};function n(r){var i;if(zy(r)){let a=t[i=r.interaction.pickerId]??(t[i]={ids:[],defaultId:null});for(let s of r.children){let c=s.type==="stack"?s.bind?.plan:void 0;c&&!a.ids.includes(c)&&a.ids.push(c)}let o=r.children[r.interaction.defaultIndex];!a.defaultId&&o?.type==="stack"&&(a.defaultId=o.bind?.plan??null)}r.type==="stack"&&r.children.forEach(n)}return e.pages.forEach(r=>n(r.root)),t}var Cn=require("zod"),Ap=Cn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),oa=Cn.z.strictObject({tiers:Cn.z.array(Cn.z.strictObject({id:Ap,name:Cn.z.string().trim().min(1).max(80)})).min(1).max(8),assignments:Cn.z.array(Cn.z.strictObject({productVersionId:Cn.z.string().min(1).max(200),tierId:Ap,period:Cn.z.enum(["month","year"])})).max(20)}).superRefine((e,t)=>{let n=e.tiers.map(r=>r.id);(new Set(n).size!==n.length||new Set(e.assignments.map(r=>r.productVersionId)).size!==e.assignments.length||new Set(e.assignments.map(r=>`${r.tierId}:${r.period}`)).size!==e.assignments.length||e.assignments.some(r=>!n.includes(r.tierId)))&&t.addIssue({code:"custom",message:"Each product and tier/period cell must have one unambiguous assignment"})});function aa(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}var oe=require("zod");var $y=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],yp=oe.z.enum($y),bp=oe.z.object({source:yp,layout:oe.z.enum(["full","compact"]),resourceKey:Ir.optional(),pageSize:oe.z.number().int().min(1).max(50),showSources:oe.z.boolean(),allowPurchase:oe.z.boolean(),outputs:oe.z.object({billing_adjustment:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional()}).strict().optional()}).strict().superRefine((e,t)=>{(e.outputs?.billing_authorization||e.outputs?.billing_adjustment)&&e.source!=="billing_controls"&&t.addIssue({code:"custom",message:"Payment authorization routes belong to the billing controls component."}),e.resourceKey&&!["credit_balance","credit_transactions"].includes(e.source)&&t.addIssue({code:"custom",message:"\u8FD9\u4E2A\u6570\u636E\u6E90\u4E0D\u80FD\u7ED1\u5B9A\u79EF\u5206\u8D44\u6E90\u3002"}),e.showSources&&e.source!=="credit_balance"&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u4F59\u989D\u53EF\u4EE5\u5C55\u5F00\u6765\u6E90\u3002"}),e.allowPurchase&&!["credit_packs","customer_plans","membership"].includes(e.source)&&t.addIssue({code:"custom",message:"\u53EA\u6709\u79EF\u5206\u5305\u3001\u5957\u9910\u4E0E\u4F1A\u5458\u7EC4\u4EF6\u53EF\u4EE5\u542F\u7528\u4EA4\u6613\u3002"})}),wt=oe.z.string().max(2e3),Sp=oe.z.object({id:oe.z.string().max(100),label:wt,detail:oe.z.array(wt).max(12),value:wt.optional(),status:wt.optional(),facts:oe.z.array(oe.z.object({label:wt,value:wt}).strict()).max(1e3),purchaseId:oe.z.uuid().optional(),invoiceUrl:oe.z.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:oe.z.array(oe.z.strictObject({action:oe.z.literal("invoice_open"),label:wt})).max(1).optional(),membershipActions:oe.z.array(oe.z.object({value:oe.z.string().max(100),label:wt}).strict()).max(3).optional()}).strict(),Gy=oe.z.object({key:Ir,name:wt,spendable:wt,reserved:wt,available:wt,expiry:wt.nullable(),sources:oe.z.array(Sp).max(50),sourceCount:oe.z.number().int().nonnegative(),sourcePage:oe.z.number().int().positive(),hasNextSources:oe.z.boolean(),hasPreviousSources:oe.z.boolean()}).strict(),Ky=oe.z.object({source:yp,status:oe.z.enum(["idle","loading","ready","error"]),stale:oe.z.boolean(),preview:oe.z.boolean(),errorCode:oe.z.string().max(80).optional(),errorMessage:wt.optional(),resources:oe.z.array(Gy).max(500),rows:oe.z.array(Sp).max(50),hasNext:oe.z.boolean(),hasPrevious:oe.z.boolean(),page:oe.z.number().int().positive(),filter:oe.z.string().max(40),updatedAt:oe.z.iso.datetime().optional(),buyingId:oe.z.uuid().optional(),membershipBusy:oe.z.boolean().optional(),billingBusy:oe.z.boolean().optional(),membershipReview:oe.z.object({title:wt,note:wt,facts:oe.z.array(oe.z.object({label:wt,value:wt}).strict()).max(100)}).strict().optional(),membershipResult:wt.optional()}).strict(),xp=oe.z.object({nodes:oe.z.record(oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ky)}).strict(),AO=oe.z.object({nodeId:oe.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:oe.z.enum(["refresh","next","previous","filter","buy_pack","billing_portal","billing_authorization","billing_adjustment","invoice_open","membership_preview","membership_confirm","membership_dismiss","sources_next","sources_previous"]),value:oe.z.string().max(100).optional()}).strict();var Qy=4,Sn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Ji=b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Te=b.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Jy=b.z.enum(["none","xs","sm","md","lg","xl"]),Zy=b.z.enum(["none","sm","md","lg","full"]),tc=b.z.string().regex(/^#[0-9a-fA-F]{6}$/),wp=b.z.string().max(2048).refine(e=>{try{let t=new URL(e);return t.protocol==="https:"&&t.hostname.length>0}catch{return!1}},"\u53EA\u652F\u6301 https \u94FE\u63A5"),nc=b.z.union([wp,b.z.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),b.z.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),b.z.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),Ip=b.z.object({primary:tc,background:tc,text:tc,radius:Zy,font:b.z.enum(["system","serif","rounded","mono"])}).strict(),Zi=b.z.union([b.z.enum(["primary","text","muted","background","surface"]),b.z.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),je=(e,t)=>b.z.number().int().min(e).max(t),vp=b.z.union([b.z.enum(["fit","fill"]),je(1,1200)]),Wy=b.z.object({top:je(0,200),right:je(0,200),bottom:je(0,200),left:je(0,200)}).strict(),Yy=b.z.object({top:je(-100,200),right:je(-100,200),bottom:je(-100,200),left:je(-100,200)}).strict(),Op=b.z.object({x:je(0,100),y:je(0,100)}).strict(),Xy=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("color"),color:Zi}).strict(),b.z.object({type:b.z.literal("linear"),angle:je(0,360),stops:b.z.array(b.z.object({color:Zi,at:je(0,100)}).strict()).min(2).max(4)}).strict(),b.z.object({type:b.z.literal("image"),src:nc,fit:b.z.enum(["cover","contain"]),position:Op.optional()}).strict()]),eb=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("rect"),radius:b.z.union([je(0,200),b.z.object({topLeft:je(0,200),topRight:je(0,200),bottomRight:je(0,200),bottomLeft:je(0,200)}).strict()])}).strict(),b.z.object({type:b.z.literal("pill")}).strict()]),tb=b.z.object({width:je(0,12),color:Zi,style:b.z.enum(["solid","dashed"])}).strict(),nb=b.z.object({x:je(-40,40),y:je(-40,40),blur:je(0,80),spread:je(-20,40),color:Zi}).strict(),rb=b.z.object({font:b.z.enum(["system","serif","rounded","mono"]),size:je(8,96),weight:b.z.number().int().min(100).max(900).multipleOf(100),lineHeight:b.z.number().min(.8).max(3),letterSpacing:b.z.number().min(-5).max(20),color:Zi,align:b.z.enum(["start","center","end"]),italic:b.z.boolean(),decoration:b.z.enum(["none","underline","line-through"]),transform:b.z.enum(["none","uppercase"])}).strict().partial(),jr=b.z.object({width:vp,height:vp,padding:Wy,margin:Yy,gap:je(0,120),grow:b.z.union([b.z.boolean(),b.z.number().min(0).max(12)]),background:Xy,opacity:b.z.number().min(0).max(1),clipContent:b.z.boolean(),shape:eb,border:tb,shadow:nb,text:rb}).strict().partial(),Jt={id:Ji,name:b.z.string().trim().min(1).max(60).optional(),hidden:b.z.boolean().optional(),style:jr.optional(),fallback:Te.optional()},ib=b.z.object({...Jt,type:b.z.literal("text"),productField:b.z.enum(["name","price","trial","period"]).optional(),feature:b.z.object({id:b.z.uuid(),field:b.z.enum(["name","allowance"])}).strict().optional(),text:Te,variant:b.z.enum(["title","heading","body","caption"])}).strict(),ob=b.z.object({...Jt,type:b.z.literal("image"),src:nc,localizedSrc:b.z.record(An,nc).optional(),alt:Te,aspect:b.z.enum(["auto","1:1","4:3","16:9","3:1"]),fit:b.z.enum(["cover","contain"]),position:Op.optional()}).strict(),ab=b.z.object({...Jt,type:b.z.literal("button"),label:Te,variant:b.z.enum(["primary","secondary","link"]),action:Te,purpose:b.z.enum(["purchase","navigation","close"]).optional(),bind:ia.optional()}).strict(),sb=b.z.object({...Jt,type:b.z.literal("divider")}).strict(),cb=b.z.object({...Jt,type:b.z.literal("customer_data"),title:Te,data:bp}).strict(),ub=b.z.object({...Jt,type:b.z.literal("spacer"),size:Jy}).strict(),lb=b.z.object({...Jt,type:b.z.literal("custom_html"),html:b.z.record(An,b.z.string().max(Sn.customHtml)),css:b.z.string().max(Sn.customCss)}).strict(),db=b.z.object({...Jt,type:b.z.literal("price"),fallback:Te,parts:b.z.object({current:jr.optional(),original:jr.optional(),period:jr.optional()}).strict().optional()}).strict(),pb=b.z.object({...Jt,type:b.z.literal("coupon_code"),label:Te,fallback:Te}).strict(),mb=b.z.object({...Jt,type:b.z.literal("countdown"),source:b.z.enum(["offer.ends_at","offer.expires_at","fixed"]),at:b.z.iso.datetime().optional(),granularity:b.z.enum(["day","hour","minute","second"]),expired:Te,fallback:Te}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),fb=b.z.object({...Jt,type:b.z.literal("plan_picker"),label:Te,fallback:Te,planIds:b.z.array(b.z.string().min(1).max(200)).min(1).max(20).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D").optional(),defaultPlan:b.z.string().min(1).max(200).optional(),grouping:oa.safeExtend({monthLabel:Te,yearLabel:Te,unavailableLabel:Te}).optional(),states:b.z.object({selected:jr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!aa(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),gb=b.z.object({...Jt,type:b.z.literal("quantity_picker"),bind:ia.optional(),label:Te,fallback:Te,internalFeatureId:b.z.uuid(),minimumQuantity:je(0,1e4),maximumQuantity:je(0,1e4),defaultQuantity:je(0,1e4),step:je(1,1e4)}).strict().refine(e=>e.minimumQuantity<=e.defaultQuantity&&e.defaultQuantity<=e.maximumQuantity&&(e.defaultQuantity-e.minimumQuantity)%e.step===0,"Quantity controls require a Product binding and valid bounds"),hb=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("input"),label:Te,keyboard:b.z.enum(["text","email","tel","url"]),maxLength:je(1,500)}).strict(),b.z.object({type:b.z.literal("multiselect"),label:Te,min:je(0,50),max:je(1,50)}).strict(),b.z.object({type:b.z.literal("select"),label:Te,defaultIndex:je(0,49),purpose:b.z.enum(["option","product","tier"]).optional(),pickerId:Ji.optional(),selectedStyle:jr.optional()}).strict(),b.z.object({type:b.z.literal("tabs"),label:Te,defaultIndex:je(0,49),purpose:b.z.literal("tier").optional()}).strict(),b.z.object({type:b.z.literal("toggle"),label:Te,defaultEnabled:b.z.boolean()}).strict(),b.z.object({type:b.z.literal("carousel"),label:Te}).strict()]),bn={...Jt,type:b.z.literal("stack"),direction:b.z.enum(["vertical","horizontal","overlay"]),align:b.z.enum(["start","center","end","stretch"]),justify:b.z.enum(["start","center","end","between"]),productSlot:b.z.object({index:je(0,19),period:b.z.enum(["month","year"]).optional(),requireBinding:b.z.boolean().optional()}).strict().optional(),interaction:hb.optional(),states:b.z.object({selected:jr.optional()}).strict().optional(),purpose:b.z.literal("benefits").optional(),purchaseAction:Te.optional(),buttonVariant:b.z.enum(["primary","secondary","link"]).optional(),bind:ia.optional()},_p=b.z.lazy(()=>b.z.object({...Jt,type:bn.type,direction:bn.direction,align:bn.align,justify:bn.justify,children:b.z.array(Ab).max(Sn.children),productSlot:bn.productSlot,interaction:bn.interaction,states:bn.states,purpose:bn.purpose,purchaseAction:bn.purchaseAction,buttonVariant:bn.buttonVariant,bind:bn.bind}).strict()),Ab=b.z.lazy(()=>b.z.union([_p,ib,ob,ab,sb,ub,lb,db,pb,mb,fb,gb,cb])),yb=b.z.union([b.z.string().max(500),b.z.number().finite(),b.z.boolean(),b.z.null()]),Qi={id:Te,event:Te,properties:b.z.record(Te,yb).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},bb=b.z.discriminatedUnion("type",[b.z.object({...Qi,type:b.z.literal("navigate"),close:b.z.literal(!1),pageId:Ji}).strict(),b.z.object({...Qi,type:b.z.literal("event"),close:b.z.boolean()}).strict(),b.z.object({...Qi,type:b.z.literal("close"),close:b.z.literal(!0)}).strict(),b.z.object({...Qi,type:b.z.literal("open_url"),close:b.z.boolean(),url:wp}).strict(),b.z.object({...Qi,type:b.z.literal("claim_offer"),close:b.z.boolean(),couponId:b.z.uuid()}).strict()]),Sb=b.z.object({defaultLocale:An,locales:b.z.record(An,b.z.record(Te,b.z.string().max(Sn.stringLength)))}).strict(),xb=b.z.enum(["popup","paywall","onboarding","page","banner"]);var Ib=b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("modal"),size:b.z.enum(["sm","md","lg"])}).strict(),b.z.object({type:b.z.literal("sheet"),size:b.z.enum(["sm","md","lg"])}).strict(),b.z.object({type:b.z.literal("fullscreen")}).strict(),b.z.object({type:b.z.literal("inline")}).strict()]);var vb=b.z.object({kind:b.z.literal("screen"),schemaVersion:b.z.literal(Qy),name:b.z.string().trim().min(1).max(80),surface:xb,initialPageId:Ji.optional(),presentation:Ib,theme:Ip,pages:b.z.array(b.z.object({id:Ji,name:b.z.string().trim().min(1).max(60),root:_p,theme:Ip.optional(),editorPosition:b.z.object({x:b.z.number().finite().min(-1e5).max(1e5),y:b.z.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(Sn.pages),strings:Sb,actions:b.z.array(bb).max(Sn.actions)}).strict();function Lt(e,t){for(let n of e.pages)Xn(n.root,t)}var rn=vb.superRefine((e,t)=>{let n=Sn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(d=>d.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let d of e.actions)d.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===d.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=d=>t.addIssue({code:"custom",message:d}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>Sn.locales&&r(`\u6700\u591A ${Sn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let d of e.actions)a.has(d.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${d.id}`),a.add(d.id);let o=new Set;for(let d of e.pages)["next","back"].includes(d.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${d.id}`),o.has(d.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${d.id}`),o.add(d.id);let s=new Set,c=0,u=!1;Lt(e,(d,m)=>{if(c++,m>Sn.depth&&(u=!0),s.has(d.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${d.id}`),s.add(d.id),d.type==="button"&&!a.has(d.action)&&r(`\u6309\u94AE ${d.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${d.action}`),d.type==="custom_html")for(let w of Object.keys(d.html))i.includes(w)||r(`\u81EA\u5B9A\u4E49 HTML ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`);if(d.type==="image")for(let w of Object.keys(d.localizedSrc??{}))i.includes(w)||r(`\u56FE\u7247 ${d.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${w}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${Sn.depth} \u5C42`)});function Xn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Xn(i,t,n+1,e)}function sa(e){let t=[],n=new Set;return Lt(e,r=>{let i=(a,o,s)=>{n.has(a)||(n.add(a),t.push({key:a,nodeId:r.id,nodeType:r.type,field:o,required:s}))};r.type==="stack"&&r.interaction&&i(r.interaction.label,"label",!0),r.fallback&&i(r.fallback,"text",!0),r.type==="text"&&i(r.text,"text",!0),r.type==="customer_data"&&i(r.title,"title",!0),(r.type==="plan_picker"||r.type==="quantity_picker"||r.type==="coupon_code")&&i(r.label,"label",!0),r.type==="plan_picker"&&r.grouping&&(i(r.grouping.monthLabel,"label",!0),i(r.grouping.yearLabel,"label",!0),i(r.grouping.unavailableLabel,"text",!0)),r.type==="countdown"&&i(r.expired,"text",!0),r.type==="button"&&i(r.label,"label",!0),r.type==="image"&&(i(`image:${r.id}`,"src",!1),i(r.alt,"alt",!1)),r.type==="custom_html"&&i(`html:${r.id}`,"html",!0)}),t}function wb(e,t,n){if(t.field==="html"){let r;return Lt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Wi(e,t.nodeId);return r?.type==="image"?r.localizedSrc?.[n]??(n===e.strings.defaultLocale?r.src:void 0):void 0}return e.strings.locales[n]?.[t.key]}function er(e){let t=sa(e).filter(r=>r.required);return Object.keys(e.strings.locales).sort((r,i)=>r===e.strings.defaultLocale?-1:i===e.strings.defaultLocale?1:0).map(r=>{let i=t.filter(a=>!wb(e,a,r)?.trim()).map(a=>a.key);return{locale:r,total:t.length,filled:t.length-i.length,missing:i,complete:i.length===0}})}function Ob(e,t){let n=null;return Xn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Wi(e,t){for(let n of e.pages){let r=Ob(n.root,t);if(r)return r}return null}var Rt=require("zod"),ft=Rt.z.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"),rc=Rt.z.strictObject({type:Rt.z.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Rt.z.boolean(),enum:Rt.z.array(Rt.z.string().max(255)).min(1).max(100).optional()}),ni=rc.extend({type:Rt.z.enum([...rc.shape.type.options,"array"]),items:rc.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"})}),ri=ni.safeExtend({source:Rt.z.discriminatedUnion("type",[Rt.z.strictObject({type:Rt.z.literal("input")}),Rt.z.strictObject({type:Rt.z.literal("node")}),Rt.z.strictObject({type:Rt.z.enum(["parameter","attribute"]),key:ft})])}),_O=Rt.z.record(ft,ri),ic=Rt.z.record(ft,ft).refine(e=>Object.keys(e).length<=20);function dn(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=>dn(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&&Rt.z.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 oc(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&&oc(e.items,t.items)}function ca(e,t){let n={};for(let[r,i]of Object.entries(e)){let a=i.source,o=a.type==="input"?t.answers:a.type==="node"?t.results??{}:a.type==="parameter"?t.parameters:t.attributes,s=a.type==="parameter"||a.type==="attribute"?a.key:r,c=Object.hasOwn(o,s),u=o[s];if(a.type==="attribute"&&s.includes(".")&&(!c||s.startsWith("merchandise."))){u=o,c=!0;for(let d of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,d)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(d)||Number(d)>=u.length)){c=!1;break}u=u[d]}}if(!(!c||u===void 0)){if(!dn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function ii(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 Cp(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"||!dn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}var tr=require("zod");var xn=tr.z.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"),Pn=tr.z.discriminatedUnion("source",[tr.z.strictObject({source:tr.z.literal("literal"),value:Ae}),tr.z.strictObject({source:tr.z.literal("variable"),key:tr.z.string().min(1).max(255),path:xn.optional()})]);function Pp(e,t){if(!t)return e;for(let n of xn.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 ac(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ca(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Ae.parse(Pp(n[e.key],e.path)))}function sc(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&&!xn.safeParse(r).success?null:{key:n,path:r}}function cc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Lt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(gp))]}function ua(e){return cc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function on(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),d=c.replace(/^-/,""),m=d.replace(".","").length,w=(d.includes(".")?d.indexOf("."):m)+Number(u),I=w<=0?2-w+m:w>=m?w:m+1;n+=I+(c.startsWith("-")?1:0)-s.length}}return n}var nr=Se.z.enum(["page","popup","banner"]),_b=3e5,Ep=Se.z.strictObject({type:Se.z.enum(["string","number","boolean","strings","json"]),nullable:Se.z.boolean()}),Cb=Se.z.strictObject({inputs:Se.z.record(Te,Ep.extend({required:Se.z.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Se.z.record(Te,Ep).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Pb=Se.z.strictObject({kind:nr,schemaVersion:Se.z.literal(1),name:Se.z.string().trim().min(1).max(80),screen:rn,contract:Cb}),la=Pb.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"]),on(e)>_b&&n("Content document exceeds its byte budget",[])});function Eb(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 Rb=la.superRefine((e,t)=>{for(let n of ua(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&&!Eb(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}er(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),Rp=Se.z.strictObject({id:Se.z.uuid(),kind:nr,projectId:Se.z.uuid(),environmentId:Se.z.uuid(),name:Se.z.string(),revision:Se.z.number().int().nonnegative(),status:Se.z.enum(["draft","published","archived"]),publishedVersionId:Se.z.uuid().nullable(),createdAt:Se.z.iso.datetime({offset:!0}),updatedAt:Se.z.iso.datetime({offset:!0})}),VO=Rp.extend({draft:la}),BO=Se.z.strictObject({rows:Se.z.array(Rp).max(200),nextCursor:Se.z.uuid().nullable()}),uc=Se.z.strictObject({id:Se.z.uuid(),kind:nr,resourceId:Se.z.uuid(),projectId:Se.z.uuid(),environmentId:Se.z.uuid(),version:Se.z.number().int().positive(),sourceRevision:Se.z.number().int().nonnegative(),document:Rb,createdAt:Se.z.iso.datetime({offset:!0})}),UO=uc.omit({document:!0}),LO=Se.z.discriminatedUnion("action",[Se.z.strictObject({action:Se.z.literal("create"),kind:nr,id:Se.z.uuid(),document:la}),Se.z.strictObject({action:Se.z.literal("save"),kind:nr,id:Se.z.uuid(),revision:Se.z.number().int().nonnegative(),document:la}),Se.z.strictObject({action:Se.z.enum(["publish","archive"]),kind:nr,id:Se.z.uuid(),revision:Se.z.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"})});var lc=require("zod"),oi={funnelId:lc.z.uuid().optional(),funnelVersionId:lc.z.uuid().optional()};var et=require("zod");var De=require("zod");var Ze=require("zod"),GO=Ze.z.discriminatedUnion("action",[Ze.z.strictObject({action:Ze.z.literal("create"),couponId:Ze.z.uuid(),productBindingId:Ze.z.uuid(),storeOfferId:Ze.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ze.z.enum(["introductory","promotional"])}),Ze.z.strictObject({action:Ze.z.literal("set_enabled"),id:Ze.z.uuid(),revision:Ze.z.number().int().nonnegative(),enabled:Ze.z.boolean()})]),KO=Ze.z.array(Ze.z.strictObject({id:Ze.z.uuid(),couponId:Ze.z.uuid(),productBindingId:Ze.z.uuid(),storeOfferId:Ze.z.string().min(1).max(255).nullable(),storeOfferType:Ze.z.enum(["introductory","promotional"]),enabled:Ze.z.boolean(),revision:Ze.z.number().int().nonnegative()})).max(500),ai=Ze.z.strictObject({offerKind:Ze.z.enum(["none","introductory","promotional"]),offerId:Ze.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ze.z.number().int().min(0).max(1e8),trialDays:Ze.z.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"})}),HO=Ze.z.record(Ze.z.uuid(),ai).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var dc=De.z.object({type:De.z.literal("native_purchase"),receiptId:De.z.uuid(),orderId:De.z.uuid(),productVersionId:De.z.uuid(),provider:De.z.enum(["apple","google"]),productId:De.z.string().min(1).max(255),productKind:pp,replacement:De.z.strictObject({sourceOrderId:De.z.uuid(),sourceProductId:De.z.string().min(1).max(255),policy:De.z.enum(["apple_store","google_full_price"]),sourceAccountTokens:De.z.array(De.z.uuid()).max(50)}).nullable(),appAccountToken:De.z.uuid().optional(),obfuscatedAccountId:De.z.string().min(1).max(64).optional(),obfuscatedProfileId:De.z.uuid().optional(),basePlanId:De.z.string().min(1).max(255).optional(),offerId:De.z.string().min(1).max(255).optional(),offerKind:De.z.enum(["none","introductory","promotional"]),currency:he,catalogAmountMinor:De.z.number().int().nonnegative().max(1e8),discountMinor:De.z.number().int().nonnegative().max(1e8),trialDays:De.z.number().int().min(1).max(730).nullable(),seatBundle:De.z.array(De.z.strictObject({key:De.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:De.z.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:De.z.strictObject({offerId:De.z.string().min(1).max(255),keyId:De.z.string().min(1).max(255),nonce:De.z.uuid(),signature:De.z.string().min(1).max(1024),timestamp:De.z.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"})});var l=require("zod");var we=require("zod/v4"),kp=require("zod/v4"),kb=kp.z.registry(),{BillingInterval:jp}=(()=>{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:jb}=(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')."})})}))(we.z),{withSpecDefault:Tb}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(kb),{COMMON:Tp}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Nb}={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:Db}=(e=>({COMMON_SET:new Set(e)}))(Tp),{hasNoDuplicateCurrencies:Np}={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:Dp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Fb}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(we.z),{Infinite:Mb}={Infinite:"inf"},{TierBehavior:qb}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Fp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Vb}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Bb}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Ub}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Lb}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(we.z),{ApiCreditTierSchema:Mp}=(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."})})}))(we.z),{VIOLATION_MESSAGES:zb}={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:qp}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(we.z),{ModelMarkupsSchema:$b}=((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()}))(we.z,qp),{InvoiceUsageEntrySchema:Gb}=(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()}))(we.z),{AttachDiscountSchema:Vp}=(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."})}))(we.z),{CustomLineItemSchema:Kb}=(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."})})}))(we.z),{UnixMsTimestampSchema:Hb}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(we.z),{CreateInvoicePreviewLineSchema:Qb}=(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()})}))(we.z),{ReissueInvoiceParamsSchema:Bp}=(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."})})}))(we.z),{InvoiceModeParamsSchema:Tr}=(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."})}))(we.z),{InvoiceTemplateSchema:Jb}=(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."})})}))(we.z),{BasePriceSchema:Zb}=((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."})})}))(we.z,jp,jb),{CURRENCY_CODES:Wb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Tp,Nb,Db),{ApiPriceProcessorsSchema:Up}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(we.z,Fb),{AllocatedBillingFieldSchema:Yb}=((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'."})}))(we.z,Vb),{CreditDimensionNameSchema:Xb}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(we.z,Bb,Ub),{ApiCreditMatchSchema:Lp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Lb),{findCreditTierViolations:eS}=(e=>({findCreditTierViolations:n=>{let r=[],i=(o,s)=>r.push({index:o,reason:s,message:e[s]}),a=0;for(let[o,s]of n.entries()){let c=o===n.length-1;if(s==="inf"){c||i(o,"non_final_infinity");continue}(!Number.isFinite(s)||s<=a)&&i(o,"not_increasing"),a=s,c&&i(o,"final_not_infinity")}return r}}))(zb),{ApiCreditMultiplierSchema:tS}=((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."})}))(we.z,Lp),{ProviderMarkupsSchema:nS}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(we.z,qp),{InvoiceFeatureQuantitySchema:zp}=((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."})}))(we.z,Fp,Gb),{CreateInvoicePreviewSchema:pc}=((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()})}))(we.z,Qb),{SUPPORTED_SET:rS}=(e=>({SUPPORTED_SET:new Set(e)}))(Wb),{ApiCreditDimensionBaseSchema:iS}=((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."})})}))(we.z,Lp),{refineGraduatedTiers:$p}=(e=>({refineGraduatedTiers:(n,r)=>{let i=e(n.tiers.map(a=>a.to));for(let{index:a,message:o}of i)r.addIssue({code:"custom",message:o,path:["tiers",a,"to"]})}}))(eS),{ApiFeatureMarkupsOverrideSchema:oS}=((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."})})}))(we.z,nS,$b),{isValidCurrencyCode:aS}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(rS),{ApiCreditDimensionSchema:sS}=((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()])}))(we.z,iS,Mp,$p),{CurrencyCodeSchema:Gp}=((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')."})}))(we.z,aS),{AdditionalCurrencyTierSchema:cS}=((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"]})}))(we.z,Gp),{ApiCreditSchemaItemBaseSchema:Kp}=((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."})})}))(we.z,Xb,sS,tS),{ApiFlatCreditSchemaItemSchema:uS}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Kp,we.z),{AdditionalCurrencyPriceSchema:lS}=((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."})})}))(we.z,Gp),{AdditionalCurrencyTierArraySchema:dS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(we.z,cS,Np,Dp),{ApiGraduatedCreditSchemaItemSchema:pS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Kp,we.z,Mp,$p),{AdditionalCurrencyPriceArraySchema:Hp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(we.z,lS,Np,Dp),{ApiUsageTierWithCurrenciesSchema:mS}=((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()}))}))(we.z,Mb,dS),{ApiCreditSchemaItemSchema:fS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(we.z,pS,uS),{BasePriceParamsSchema:gS}=((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."})}))(Zb,Tb,we.z,Hp),{PlanItemPriceParamsSchema:hS}=((e,t,n,r,i,a,o)=>({PlanItemPriceParamsSchema:e.object({stripe_price_id:e.string().nullish().transform(c=>c??void 0).meta({description:"Stripe price id this feature price is billed under. Set by sync flows to preserve an existing Stripe price.",internal:!0}).optional(),amount:e.number().optional().meta({description:"Price per billing_units after included usage. Either 'amount' or 'tiers' is required."}),additional_currencies:t.optional().meta({description:"Amounts in additional currencies for this flat price. The base 'amount' is in the org's default currency. Only valid with 'amount', not 'tiers'."}),tiers:e.array(n).optional().meta({description:"Tiered pricing. Either 'amount' or 'tiers' is required."}),tier_behavior:e.enum(r).optional(),interval:e.enum(i).meta({description:"Billing interval. For consumable features, should match reset.interval."}),interval_count:e.number().default(1).optional().meta({description:"Number of intervals per billing cycle. Defaults to 1."}),billing_units:e.number().default(1).optional().meta({description:"Units per price increment. Usage is rounded UP when billed (e.g. billing_units=100 means 101 rounds to 200)."}),billing_method:e.enum(a).meta({description:"'prepaid' for upfront payment (seats), 'usage_based' for pay-as-you-go."}),allocated_billing:o,max_purchase:e.number().nullish().meta({description:"Max units purchasable beyond included. E.g. included=100, max_purchase=300 allows 400 total. Null for no limit."})})}))(we.z,Hp,mS,qb,jp,Fp,Yb),{ApiFeatureOverrideSchema:AS}=((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."})})}))(we.z,fS,oS),{InvoiceBasePriceParamsSchema:Qp}=((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()}))(gS,Up),{InvoiceItemPriceParamsSchema:yS}=((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()}))(hS,Up),{InvoiceLicenseQuantitySchema:bS}=((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()}))(we.z,Qp,zp),{InvoiceCustomizeItemSchema:SS}=((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()}))(we.z,yS,AS),{InvoiceCustomizeSchema:xS}=((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."})}))(we.z,Qp,SS),{InvoicePlanParamsSchema:IS}=((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()}))(we.z,xS,zp,bS,Vp),{CreateInvoiceParamsSchema:si}=((e,t,n,r,i)=>({CreateInvoiceParamsSchema:e.object({customer_id:e.string().meta({description:"The customer to invoice."}),plans:e.array(t).optional(),custom_line_items:e.array(n).optional().meta({description:"Charges that are not tied to any plan or feature."}),discounts:e.array(r).optional().meta({description:"Discounts applied to the whole invoice."}),invoice_template_id:e.string().optional().meta({description:"ID of an invoice template whose footer, memo and default payment terms are applied."}),net_terms_days:e.number().int().positive().optional().meta({description:"Days until the invoice is due. Defaults to the template's terms, then the org default."}),tax_rate_id:e.string().optional().meta({description:"Stripe tax rate ID (txr_...) applied to every line."}),period_start:i.optional().meta({description:"Start of the period being invoiced, in milliseconds. Prorated lines are charged for period_start \u2192 period_end against one price interval starting at period_start."}),period_end:i.optional().meta({description:"End of the period being invoiced, in milliseconds."}),preview:e.boolean().optional().meta({description:"If true, returns the calculated lines and totals without creating an invoice."})}).strict().refine(o=>o.period_start===void 0==(o.period_end===void 0),{message:"period_start and period_end must be provided together."}).refine(o=>o.period_start===void 0||o.period_end===void 0||o.period_end>o.period_start,{message:"period_end must be after period_start."})}))(we.z,IS,Kb,Vp,Hb);var Wp=l.z.strictObject({requestId:l.z.uuid(),predecessorOperationId:l.z.uuid().optional(),invoiceMode:Tr.optional(),entityId:l.z.uuid().optional(),billingSubscriptionId:l.z.uuid().optional(),newBillingSubscription:l.z.literal(!0).optional(),offerId:l.z.uuid().optional(),nativeOffer:ai.optional(),plans:l.z.array(l.z.strictObject({productVersionId:l.z.uuid(),seatQuantities:l.z.record(To,l.z.number().int().min(0).max(1e4)).optional(),featureQuantities:l.z.record(l.z.uuid(),l.z.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:l.z.enum(["stripe","apple","google","merchant"]),currency:he}).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"),Dr=l.z.strictObject({operationId:l.z.uuid()}),kt=l.z.number().int().min(0).max(1e8),vS=l.z.strictObject({lineId:l.z.uuid(),productVersionId:l.z.uuid(),productName:l.z.string().min(1).max(80),interval:l.z.enum(["free","week","month","year","one_time"]),intervalCount:l.z.number().int().min(1).max(156).optional(),baseAmountMinor:kt,seats:l.z.array(l.z.strictObject({key:To,quantity:l.z.number().int().min(0).max(1e4),includedQuantity:l.z.number().int().min(0).max(1e4),maximumQuantity:l.z.number().int().min(0).max(1e4),unitAmountMinor:kt})).max(20),prepaid:l.z.array(Bd).max(100).optional(),catalogAmountMinor:kt,trial:l.z.strictObject({days:l.z.number().int().min(1).max(730),cardRequired:l.z.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+qo({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"),Yp=l.z.string().regex(/^[A-Za-z0-9_-]{1,200}$/),wS=l.z.strictObject({id:Yp,name:l.z.string().min(1).max(40),percent_off:l.z.number().gt(0).max(100).optional(),amount_off:l.z.number().int().positive().optional(),currency:l.z.string().regex(/^[a-z]{3}$/).optional(),duration:l.z.enum(["once","repeating","forever"]),duration_in_months:l.z.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"),OS=l.z.strictObject({subscriptionId:l.z.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:l.z.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:l.z.array(l.z.strictObject({id:l.z.string(),price_id:l.z.string(),quantity:l.z.number().int().nonnegative(),discounts:l.z.array(l.z.strictObject({id:l.z.string(),coupon:l.z.string(),start:l.z.number(),end:l.z.number().nullable()})).optional()})).min(1).max(100),prorationDate:l.z.number().int().nonnegative(),amountMinor:l.z.number().int().positive(),periodStartMs:l.z.number(),periodEndMs:l.z.number()}),Xp=l.z.strictObject({invoiceMode:Tr.optional(),append:OS.optional(),provider:l.z.literal("stripe"),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:l.z.enum(["payment","subscription"]),lineItems:l.z.array(l.z.strictObject({price:l.z.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:l.z.number().int().min(1).max(1e4),priceId:l.z.uuid(),productName:l.z.string().min(1).max(80),amountMinor:l.z.number().int().min(0).max(1e8),currency:l.z.string().regex(/^[a-z]{3}$/),interval:l.z.enum(["week","month","year","one_off"]),intervalCount:l.z.number().int().min(1).max(52),slot:l.z.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:l.z.strictObject({mode:l.z.enum(["graduated","volume"]),tiers:l.z.array(l.z.strictObject({upTo:l.z.number().int().min(1).max(1e6).nullable(),unitAmountMinor:l.z.number().int().min(0).max(1e8),flatAmountMinor:l.z.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:l.z.array(l.z.strictObject({coupon:Yp,terms:wS})).max(1),trialPeriodDays:l.z.number().int().min(1).max(730).nullable(),metadata:l.z.strictObject({grooveCheckoutId:l.z.uuid(),grooveCustomerId:l.z.uuid()}),expiresAt:l.z.iso.datetime({offset:!0})}),ci=l.z.strictObject({operationId:l.z.uuid(),entityId:l.z.uuid().nullable(),billingSubscriptionId:l.z.uuid().nullable(),discount:l.z.strictObject({offerId:l.z.uuid(),couponId:l.z.uuid(),discount:Wn,duration:tn,amountMinor:kt,allocations:l.z.array(l.z.strictObject({productVersionId:l.z.uuid(),amountMinor:kt})).min(1).max(20),expiresAt:l.z.iso.datetime({offset:!0})}).nullable(),charge:l.z.strictObject({effectiveAt:l.z.iso.datetime({offset:!0}),periodEndsAt:l.z.iso.datetime({offset:!0}),debitMinor:kt,discountMinor:kt,taxMinor:kt,totalMinor:kt}).nullable(),expiresAt:l.z.iso.datetime({offset:!0}),provider:l.z.enum(["stripe","apple","google","merchant"]),nativeOffer:ai.optional(),currency:he,lines:l.z.array(vS).min(1).max(20),catalogAmountMinor:kt,automaticTax:l.z.boolean(),execution:l.z.union([Xp,Po]).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"),ui=l.z.strictObject({operationId:l.z.uuid(),orderId:l.z.uuid(),append:l.z.boolean().optional(),invoiceMode:l.z.boolean().optional(),status:l.z.enum(["pending","complete","cancelled","failed"]),executor:l.z.enum(["indiana","merchant"]),checkoutUrl:l.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:l.z.union([Xp,Po]).nullable(),currency:he,catalogAmountMinor:kt,taxMinor:kt,totalMinor:l.z.number().int().min(0).max(2e8).nullable(),quoteFinalized:l.z.boolean(),nativePurchase:dc.nullable(),confirmedAt:l.z.iso.datetime({offset:!0}).nullable().optional(),quote:ci.optional(),merchantExecution:Sr.nullable().optional(),problem:Ei.nullable().optional(),authority:jo.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"),pa=l.z.strictObject({enabled:l.z.literal(!0),featureIds:l.z.array(l.z.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),em=l.z.strictObject({requestId:l.z.uuid(),invoiceMode:Tr.optional(),membershipId:l.z.uuid(),carryOverBalances:pa.optional(),carryOverUsages:pa.optional(),membershipIds:l.z.array(l.z.uuid()).min(1).max(20).optional(),prorationBehavior:l.z.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:l.z.enum(["immediate","renewal","store"]),change:l.z.discriminatedUnion("type",[l.z.strictObject({type:l.z.literal("plan"),productVersionId:l.z.uuid()}),l.z.strictObject({type:l.z.literal("seats"),licenseKey:To,quantity:l.z.number().int().min(0).max(1e4)}),l.z.strictObject({type:l.z.literal("quantity"),internal_feature_id:l.z.uuid(),quantity:l.z.number().int().min(0).max(1e4)}),l.z.strictObject({type:l.z.literal("cancel")}),l.z.strictObject({type:l.z.literal("uncancel")}),l.z.strictObject({type:l.z.literal("billing_cycle"),billingCycleAnchor:l.z.union([l.z.literal("now"),l.z.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"),da=l.z.string().regex(/^price_[A-Za-z0-9]+$/),Jp=l.z.strictObject({grooveUpdateId:l.z.uuid(),grooveCustomerId:l.z.uuid()}),Zp=l.z.strictObject({price:da.nullable(),priceId:l.z.uuid().optional(),quantity:l.z.number().int().min(0).max(1e4)}),tm=l.z.strictObject({provider:l.z.literal("stripe"),invoiceMode:Tr.optional(),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:l.z.string().regex(/^sub_[A-Za-z0-9]+$/),action:l.z.enum(["update","cancel","schedule","release"]),update:l.z.strictObject({items:l.z.array(Zp).max(20),remove:l.z.array(da).max(20),restoreItems:l.z.array(l.z.strictObject({price:da,quantity:l.z.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:l.z.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:l.z.number().int().positive().optional(),paymentBehavior:l.z.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:l.z.boolean().optional(),clearCancelAt:l.z.literal(!0).optional(),billingCycleAnchorNow:l.z.literal(!0).optional(),metadata:Jp}).nullable(),cancel:l.z.strictObject({prorate:l.z.literal(!1),invoiceNow:l.z.literal(!1)}).nullable(),schedule:l.z.strictObject({currentItems:l.z.array(l.z.strictObject({price:da,quantity:l.z.number().int().min(0).max(1e4)})).max(20),nextItems:l.z.array(Zp).min(1).max(20),switchAt:l.z.number().int().positive(),interval:l.z.enum(["week","month","year"]),intervalCount:l.z.number().int().min(1).max(52),resetBillingCycleAnchor:l.z.literal(!0).optional(),metadata:Jp}).nullable(),release:l.z.strictObject({schedule:l.z.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:l.z.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"),ma=l.z.strictObject({carryOverBalances:pa.optional(),carryOverUsages:pa.optional(),operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),timing:l.z.enum(["immediate","renewal"]),effectiveAt:l.z.iso.datetime({offset:!0}),expiresAt:l.z.iso.datetime({offset:!0}),currency:he,creditMinor:kt,debitMinor:kt,discountMinor:kt,taxMinor:kt,totalMinor:kt,retainedProductVersionIds:l.z.array(l.z.uuid()).max(19),execution:l.z.union([tm,Eo])}),_S=l.z.strictObject({operationId:l.z.uuid(),invoiceMode:l.z.boolean().optional(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),status:l.z.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:l.z.enum(["immediate","renewal"]),effectiveAt:l.z.iso.datetime({offset:!0}),checkoutUrl:l.z.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:l.z.enum(["indiana","merchant"]),execution:l.z.union([tm,Eo]).nullable(),confirmedAt:l.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Sr.nullable().optional(),problem:Ei.nullable().optional(),quote:ma.optional(),authority:jo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),CS=l.z.strictObject({operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),timing:l.z.literal("store"),effectiveAt:l.z.null(),expiresAt:l.z.iso.datetime({offset:!0}),currency:he,creditMinor:l.z.null(),debitMinor:l.z.null(),discountMinor:l.z.null(),taxMinor:l.z.null(),totalMinor:l.z.null(),retainedProductVersionIds:l.z.array(l.z.uuid()).max(19),store:l.z.strictObject({provider:l.z.enum(["apple","google"]),productId:l.z.string().min(1).max(255),catalogAmountMinor:kt,policy:l.z.enum(["apple_store","google_full_price"])})}),PS=l.z.strictObject({operationId:l.z.uuid(),membershipId:l.z.uuid(),productVersionId:l.z.uuid(),status:l.z.enum(["prepared","pending","effective","cancelled","failed"]),timing:l.z.literal("store"),effectiveAt:l.z.iso.datetime({offset:!0}).nullable(),checkoutUrl:l.z.null(),nativePurchase:dc.nullable()}),nm=l.z.union([ma,CS]),mc=l.z.union([_S,PS]),Yi=l.z.number().int().positive().max(2e8),Nr=l.z.number().int().min(0).max(2e8),rm=l.z.strictObject({requestId:l.z.uuid(),invoiceId:l.z.uuid(),mode:l.z.enum(["full","partial"]),amountMinor:Yi.optional(),entitlementAction:l.z.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),im=l.z.strictObject({provider:l.z.literal("stripe"),executor:l.z.enum(["indiana","merchant"]),accountId:l.z.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:l.z.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Yi,currency:l.z.string().regex(/^[a-z]{3}$/),metadata:l.z.strictObject({indianaRefundId:l.z.uuid()}),idempotencyKey:l.z.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:l.z.array(l.z.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),fc=l.z.strictObject({operationId:l.z.uuid(),invoiceId:l.z.uuid(),providerInvoiceId:l.z.string().min(1).max(200),currency:he,paidMinor:Nr,refundedMinor:Nr,pendingMinor:Nr,amountMinor:Yi,mode:l.z.enum(["full","partial"]),entitlementAction:l.z.enum(["retain","revoke"]),revokes:l.z.strictObject({customerProductIds:l.z.array(l.z.uuid()).max(100),subscriptionIds:l.z.array(l.z.string().min(1).max(200)).max(20)}),execution:l.z.union([im,Ro]),expiresAt:l.z.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"),fa=l.z.strictObject({operationId:l.z.uuid(),invoiceId:l.z.uuid(),providerInvoiceId:l.z.string().min(1).max(200),status:l.z.enum(["quoted","pending","succeeded","failed","expired"]),executor:l.z.enum(["indiana","merchant"]),currency:he,amountMinor:Yi,mode:l.z.enum(["full","partial"]),entitlementAction:l.z.enum(["retain","revoke"]),refundId:l.z.string().min(1).max(200).nullable(),quote:fc.optional(),execution:l.z.union([im,Ro]).nullable(),confirmedAt:l.z.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:Sr.nullable().optional(),problem:Ei.nullable().optional(),authority:jo.optional(),failureReason:l.z.string().min(1).max(200).nullable(),createdAt:l.z.iso.datetime({offset:!0}),completedAt:l.z.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"),u_=l.z.strictObject({invoiceId:l.z.uuid(),currency:he,paidMinor:Nr,refundedMinor:Nr,pendingMinor:Nr,refundableMinor:Nr,executor:l.z.enum(["indiana","merchant"]).nullable(),canRefund:l.z.boolean(),operations:l.z.array(fa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),l_=l.z.strictObject({requestId:l.z.uuid(),mode:l.z.enum(["full","partial"]),amountMinor:Yi.optional(),entitlementAction:l.z.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 om=et.z.strictObject({requestId:et.z.uuid(),targets:et.z.array(et.z.strictObject({membershipId:et.z.uuid(),action:et.z.enum(["cancel","uncancel"]),timing:et.z.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"),ga=et.z.strictObject({batchId:et.z.uuid()}),ES=et.z.strictObject({operationId:et.z.uuid(),membershipIds:et.z.array(et.z.uuid()).min(1).max(20),provider:et.z.enum(["stripe","apple","google"]),action:et.z.enum(["cancel","uncancel"]),timing:et.z.enum(["immediate","renewal"]),status:et.z.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ma.nullable(),managementUrl:et.z.url().nullable(),failureCode:et.z.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Xi=et.z.strictObject({batchId:et.z.uuid(),ready:et.z.boolean(),status:et.z.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:et.z.iso.datetime({offset:!0}),acceptedAt:et.z.iso.datetime({offset:!0}).nullable(),groups:et.z.array(ES).min(1).max(100)});var Pe=require("zod"),RS=Pe.z.string().trim().min(1).max(240),gc={requestId:Pe.z.uuid(),reason:RS},ha=Pe.z.discriminatedUnion("action",[Pe.z.strictObject({...gc,action:Pe.z.literal("start"),productVersionId:Pe.z.uuid(),entityId:Pe.z.uuid().optional(),days:Pe.z.number().int().min(1).max(730).optional()}),Pe.z.strictObject({...gc,action:Pe.z.literal("extend"),membershipId:Pe.z.uuid(),days:Pe.z.number().int().min(1).max(730)}),Pe.z.strictObject({...gc,action:Pe.z.literal("end"),membershipId:Pe.z.uuid()})]),am=Pe.z.strictObject({operationId:Pe.z.uuid()}),sm=Pe.z.iso.datetime({offset:!0}),kS=Pe.z.strictObject({provider:Pe.z.literal("stripe"),executor:Pe.z.enum(["indiana","merchant"]),accountId:Pe.z.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Pe.z.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Pe.z.union([Pe.z.literal("now"),sm]),prorationBehavior:Pe.z.literal("none")}),hc=Pe.z.strictObject({operationId:Pe.z.uuid(),action:Pe.z.enum(["start","extend","end"]),status:Pe.z.enum(["pending","effective"]),managedBy:Pe.z.enum(["indiana","stripe"]),membershipIds:Pe.z.array(Pe.z.uuid()).min(1).max(20),endsAt:sm.nullable(),execution:kS.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"),f_=Pe.z.strictObject({groupId:Pe.z.uuid(),productVersionId:Pe.z.uuid(),enabled:Pe.z.boolean()});var He=require("zod");var cm=He.z.strictObject({requestId:He.z.uuid(),currency:he,makeDefault:He.z.boolean()}),um=He.z.strictObject({setupId:He.z.uuid()}),jS=He.z.strictObject({provider:He.z.literal("stripe"),executor:He.z.literal("merchant"),accountId:He.z.string().regex(/^acct_[A-Za-z0-9]+$/),mode:He.z.literal("setup"),currency:He.z.string().regex(/^[a-z]{3}$/),customer:He.z.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:He.z.uuid(),metadata:He.z.strictObject({grooveProjectId:He.z.uuid(),grooveEnvironmentId:He.z.uuid(),grooveCustomerId:He.z.uuid(),groovePaymentSetupId:He.z.uuid()}),setDefaultPaymentMethod:He.z.boolean(),expiresAt:He.z.iso.datetime({offset:!0})}),Ac=He.z.strictObject({id:He.z.uuid(),provider:He.z.literal("stripe"),status:He.z.enum(["prepared","complete","expired"]),currency:he,makeDefault:He.z.boolean(),url:He.z.url().nullable(),createdAt:He.z.iso.datetime({offset:!0}),expiresAt:He.z.iso.datetime({offset:!0}),completedAt:He.z.iso.datetime({offset:!0}).nullable(),execution:jS.nullable()});var Ot=require("zod"),lm=Ot.z.union([Ot.z.string(),Ot.z.number(),Ot.z.boolean(),Ot.z.null()]),dm=Ot.z.strictObject({customerId:Ot.z.uuid()}),pm=Ot.z.strictObject({customerId:Ot.z.uuid(),provider:Ot.z.literal("stripe"),checkedAt:Ot.z.iso.datetime({offset:!0}),status:Ot.z.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Ot.z.number().int().nonnegative(),differences:Ot.z.array(Ot.z.strictObject({subscriptionId:Ot.z.string().startsWith("sub_"),itemId:Ot.z.string().nullable(),field:Ot.z.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:lm,actual:lm})).max(1e4)});var ye=require("zod");var Aa=ye.z.iso.datetime({offset:!0}),ya=ye.z.strictObject({createdAt:Aa,id:ye.z.uuid()}),ba=ye.z.strictObject({customerId:ye.z.uuid().optional(),entityId:ye.z.uuid().optional(),productId:ye.z.string().min(1).max(256).optional(),provider:ye.z.enum(["stripe","apple","google","merchant","free"]).optional(),status:ye.z.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:ya.optional(),limit:ye.z.number().int().min(1).max(100).optional()}),yc={id:ye.z.uuid(),customerId:ye.z.uuid(),entityId:ye.z.uuid().nullable(),productId:ye.z.string().min(1).max(256),productVersionId:ye.z.uuid(),name:ye.z.string().min(1).max(120),provider:ye.z.enum(["stripe","apple","google","merchant","free"]),createdAt:Aa},TS=ye.z.strictObject({...yc,status:ye.z.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ye.z.boolean(),billingSubscriptionId:ye.z.uuid().nullable()}),NS=ye.z.strictObject({...yc,status:ye.z.enum(["active","ended","refunded"]),orderId:ye.z.uuid().nullable(),transactionId:ye.z.uuid().nullable(),currency:he.nullable(),amountMinor:ye.z.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),DS=ye.z.strictObject({...yc,status:ye.z.enum(["blocked","resolved"]),conflict:ye.z.strictObject({detectedAt:Aa,blockingMembershipIds:ye.z.array(ye.z.uuid()).min(1).max(100),transactionId:ye.z.uuid()}),resolvedAt:Aa.nullable()}),mm=ba.extend({status:ye.z.enum(["blocked","resolved"]).optional()}),fm=ye.z.strictObject({customerId:ye.z.uuid(),orderId:ye.z.uuid()}),gm=ye.z.strictObject({orderId:ye.z.uuid(),status:ye.z.enum(["blocked","resolved"])}),hm=ye.z.strictObject({items:ye.z.array(TS).max(100),nextCursor:ya.nullable()}),Am=ye.z.strictObject({items:ye.z.array(NS).max(100),nextCursor:ya.nullable()}),ym=ye.z.strictObject({items:ye.z.array(DS).max(100),nextCursor:ya.nullable()});var We=require("zod");var bm=We.z.union([We.z.strictObject({intent:We.z.literal("read"),requestId:We.z.uuid(),purchaseIntentId:We.z.uuid()}),We.z.strictObject({requestId:We.z.uuid(),provider:We.z.literal("apple"),purchaseIntentId:We.z.uuid(),productId:We.z.string().min(1).max(255).optional(),signedTransaction:We.z.string().min(1).max(131072)}),We.z.strictObject({requestId:We.z.uuid(),provider:We.z.literal("google"),purchaseIntentId:We.z.uuid(),productId:We.z.string().min(1).max(255).optional(),purchaseToken:We.z.string().min(1).max(16384)})]),Sm=We.z.strictObject({requestId:We.z.uuid(),orderId:We.z.uuid(),purchaseIntentId:We.z.uuid(),status:We.z.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:he,refunded:We.z.boolean(),completion:We.z.strictObject({transactionIds:We.z.array(We.z.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:We.z.boolean()}).nullable()});var U=require("zod"),Sc=U.z.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),FS=U.z.record(U.z.string(),U.z.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),MS=3,eo=20,qS=MS*eo,bc=U.z.strictObject({type:U.z.literal("product"),productId:Sc}),xm={type:U.z.literal("group"),key:U.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:U.z.string().trim().min(1).max(80)},VS=U.z.discriminatedUnion("type",[bc,U.z.strictObject({...xm,items:U.z.array(bc).max(eo)})]),BS=U.z.discriminatedUnion("type",[bc,U.z.strictObject({...xm,items:U.z.array(VS).max(eo)})]),US=U.z.array(BS).max(eo).superRefine((e,t)=>{let n=new Set,r=new Set,i=0;function a(o){for(let s of o){i++;let c=s.type==="product"?n:r,u=s.type==="product"?s.productId:s.key;c.has(u)&&t.addIssue({code:"custom",message:s.type==="product"?"Duplicate Offering Product reference":"Duplicate Offering group key"}),c.add(u),s.type==="group"&&a(s.items)}}a(e),(n.size>eo||i>qS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function xc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:xc(t))}var li=U.z.strictObject({lookupKey:U.z.string().trim().min(1).max(200),displayName:U.z.string().trim().min(1).max(1500),items:US,metadata:FS}),LS=U.z.strictObject({product:U.z.record(U.z.string(),U.z.json()),prices:U.z.array(U.z.record(U.z.string(),U.z.json())),entitlements:U.z.array(U.z.record(U.z.string(),U.z.json())),freeTrials:U.z.array(U.z.record(U.z.string(),U.z.json())),licenses:U.z.array(U.z.record(U.z.string(),U.z.json()))}),Im=li.extend({id:U.z.uuid(),projectId:U.z.uuid(),environmentId:U.z.uuid(),state:U.z.enum(["active","archived"]),isCurrent:U.z.boolean(),revision:U.z.number().int().nonnegative(),publishedVersionId:U.z.uuid().nullable(),createdAt:U.z.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"})}),vm=U.z.strictObject({id:U.z.uuid(),offeringId:U.z.uuid(),projectId:U.z.uuid(),environmentId:U.z.uuid(),version:U.z.number().int().positive(),document:li,productEvidence:U.z.record(Sc,LS),createdAt:U.z.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=xc(e.document);(!n.length||GS(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"})}),zS=U.z.strictObject({rows:U.z.array(Im).max(200),versions:U.z.array(vm).max(500)}),v_=U.z.discriminatedUnion("action",[U.z.strictObject({action:U.z.literal("create"),document:li}),U.z.strictObject({action:U.z.literal("save"),id:U.z.uuid(),revision:U.z.number().int().nonnegative(),document:li}),U.z.strictObject({action:U.z.enum(["publish","set_current","archive","restore"]),id:U.z.uuid(),revision:U.z.number().int().nonnegative()})]),w_=U.z.strictObject({record:Im,version:vm.nullable()}),wm=U.z.discriminatedUnion("type",[U.z.strictObject({type:U.z.literal("current")}),U.z.strictObject({type:U.z.literal("id"),id:U.z.uuid()}),U.z.strictObject({type:U.z.literal("lookup_key"),lookupKey:U.z.string().min(1).max(200)}),U.z.strictObject({type:U.z.literal("version"),versionId:U.z.uuid()})]),$S=U.z.strictObject({internalId:Sc,id:U.z.string(),name:U.z.string().nullable(),version:U.z.number().int().positive(),archived:U.z.boolean()}),O_=zS.extend({products:U.z.array($S).max(500),pagination:U.z.strictObject({rows:U.z.string().nullable(),versions:U.z.string().nullable(),products:U.z.string().nullable()}).optional()});function GS(e){let t=[];xc(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}var to=require("zod");var Om=to.z.strictObject({id:to.z.uuid(),offeringId:to.z.uuid(),version:to.z.number().int().positive(),document:li});var ht=require("zod");var de=require("zod");var Fr=require("zod");var Sa=Fr.z.strictObject({items:Fr.z.array(Fr.z.strictObject({productVersionId:Fr.z.string().min(1).max(200),label:Fr.z.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:Fr.z.string().min(1).max(200).nullable(),grouping:oa.optional()});function _m(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}var gt=require("zod"),KS=gt.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),xa=gt.z.discriminatedUnion("type",[gt.z.object({type:gt.z.literal("fixed"),productVersionId:gt.z.string().min(1).max(200)}).strict(),gt.z.object({type:gt.z.literal("picker"),pickerId:KS,allowedProductVersionIds:gt.z.array(gt.z.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")]),Bn=gt.z.discriminatedUnion("type",[gt.z.object({type:gt.z.literal("modal"),size:gt.z.enum(["sm","md","lg"])}).strict(),gt.z.object({type:gt.z.literal("sheet"),size:gt.z.enum(["sm","md","lg"])}).strict(),gt.z.object({type:gt.z.literal("fullscreen")}).strict(),gt.z.object({type:gt.z.literal("inline")}).strict()]);var Ic=de.z.discriminatedUnion("type",[de.z.strictObject({type:de.z.literal("event"),event:de.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),de.z.strictObject({type:de.z.literal("open_url"),url:de.z.url().refine(e=>new URL(e).protocol==="https:")})]),HS=rn,QS=de.z.discriminatedUnion("type",[de.z.object({type:de.z.literal("checkout"),product:xa}).strict(),de.z.object({type:de.z.literal("close")}).strict(),de.z.object({type:de.z.literal("action"),action:Ic}).strict()]),di=de.z.object({schemaVersion:de.z.literal(3),kind:de.z.literal("paywall"),name:de.z.string().trim().min(1).max(80),presentation:Bn,requirement:Yn.optional(),products:Sa,offeringVersionId:de.z.uuid().nullable(),offeringId:de.z.uuid(),screen:HS,buttons:de.z.record(de.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),QS)}).strict(),q_=di.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 ZS(e))t.addIssue({code:"custom",message:r});for(let r of JS(e))t.addIssue({code:"custom",message:r});er(e.screen).some(r=>!r.complete)&&t.addIssue({code:"custom",message:"Paywall needs complete local content"}),(Object.keys(e.buttons).length!==e.screen.actions.filter(r=>r.type!=="navigate").length||e.screen.actions.some(r=>r.type!=="navigate"&&!Object.hasOwn(e.buttons,r.id)))&&t.addIssue({code:"custom",message:"Paywall buttons require matching node policies"}),Object.values(e.buttons).some(r=>r.type==="checkout")||t.addIssue({code:"custom",message:"A paywall requires a purchase or membership change button"})});function JS(e){let t=e.products.items.map(a=>a.productVersionId),n=hp(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&&(!aa(e.products.grouping,t)||e.products.grouping.tiers.some(a=>!e.products.grouping.assignments.some(o=>o.tierId===a.id)))&&i.push("grouping");for(let a of Object.values(e.buttons))if(a.type==="checkout"){let o=a.product;if(o.type==="fixed")r.add(o.productVersionId);else{o.allowedProductVersionIds.forEach(u=>r.add(u));let s=!1,c=n[o.pickerId];c&&(s=!0,(o.allowedProductVersionIds.some(u=>!c.ids.includes(u))||c.ids.some(u=>!o.allowedProductVersionIds.includes(u)))&&i.push("picker")),Lt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let d=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(d)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Lt(e.screen,a=>{a.type==="stack"&&a.productSlot&&!a.bind?.plan&&i.push(`productBinding:${a.id}`),(a.type==="stack"||a.type==="button")&&a.bind?.plan&&!t.includes(a.bind.plan)&&i.push("binding"),a.type==="plan_picker"&&(!a.planIds?.length||a.planIds.some(o=>!t.includes(o)))&&i.push("binding")}),[...new Set(i)]}function ZS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Xn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let d=e.screen.actions.find(w=>w.id===u);d?.type==="navigate"&&r.get(s.id).push(d.pageId);let m=e.buttons[u];s.id!==n.id&&m&&m.type!=="close"&&t.push(`purchaseScreen:${c.id}`)}s.id!==n.id&&(c.type==="plan_picker"||c.type==="stack"&&c.productSlot)&&t.push(`packageScreen:${c.id}`)});let i=new Set;function a(s){if(!i.has(s)){i.add(s);for(let c of r.get(s)??[])a(c)}}let o=e.screen.initialPageId??e.screen.pages[0]?.id;o?a(o):t.push("initialPage");for(let s of e.screen.pages)i.has(s.id)||t.push(`unreachableScreen:${s.id}`);return[...new Set(t)]}var Cm=de.z.object({id:de.z.uuid(),projectId:de.z.uuid(),environmentId:de.z.uuid(),revision:de.z.number().int().nonnegative(),state:de.z.enum(["active","archived"]),publishedVersionId:de.z.uuid().nullable(),updatedAt:de.z.iso.datetime({offset:!0}),draft:di}).strict(),V_=de.z.object({rows:de.z.array(Cm).max(200),nextCursor:de.z.uuid().nullable()}).strict(),B_=Cm.omit({draft:!0}).extend({name:de.z.string(),productCount:de.z.number().int().nonnegative()}).strict(),U_=de.z.discriminatedUnion("action",[de.z.object({action:de.z.literal("save"),id:de.z.uuid().nullable(),revision:de.z.number().int().nonnegative(),document:di}).strict(),de.z.object({action:de.z.enum(["publish","archive"]),id:de.z.uuid(),revision:de.z.number().int().nonnegative()}).strict()]),L_=de.z.object({paywalls:de.z.array(de.z.object({id:de.z.uuid(),paywallId:de.z.uuid(),version:de.z.number().int().positive(),name:de.z.string().min(1).max(80),presentation:Bn,buttons:di.shape.buttons}).strict()).max(500),limited:de.z.boolean()}).strict();var Oe=require("zod");var Nt=require("zod");var pi=Nt.z.string().regex(/^[a-f0-9]{64}$/),WS=ra.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),Pm=Nt.z.strictObject({couponDigests:Nt.z.record(Nt.z.uuid(),pi),variables:Nt.z.record(An,Nt.z.record(Nt.z.uuid(),Nt.z.partialRecord(Nt.z.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Nt.z.string()))),locales:Nt.z.record(An,ti.extend({nodes:Nt.z.record(Nt.z.string(),Nt.z.strictObject({base:WS})),plans:Nt.z.object({}).strict(),pickers:Nt.z.object({}).strict()}).omit({paywall:!0}))});var Fe=require("zod");var no=require("zod"),vc=no.z.strictObject({eventsEnabled:no.z.boolean(),experimentViewsEnabled:no.z.boolean(),featureUsageEnabled:no.z.boolean()}),H_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Em(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}var $=require("zod");var wc=$.z.tuple([$.z.number().min(0).max(1),$.z.number().min(0).max(1)]).refine(([e,t])=>e<=t),YS=$.z.strictObject({attribute:$.z.string().optional(),seed:$.z.string(),hashVersion:$.z.literal(2),ranges:$.z.array(wc).max(100)}),XS=$.z.strictObject({id:$.z.string().min(1).max(255),condition:Ht,gate:$.z.boolean().optional()}),ex=$.z.strictObject({key:$.z.string().optional(),name:$.z.string().optional(),passthrough:$.z.boolean().optional()}),Rm={condition:Ht.optional(),parentConditions:$.z.array(XS).max(100).optional(),weights:$.z.array($.z.number().min(0).max(1)).max(20).optional(),coverage:$.z.number().min(0).max(1).optional(),hashAttribute:$.z.string().optional(),fallbackAttribute:$.z.string().optional(),hashVersion:$.z.literal(2).optional(),disableStickyBucketing:$.z.boolean().optional(),bucketVersion:$.z.number().int().nonnegative().optional(),minBucketVersion:$.z.number().int().nonnegative().optional(),filters:$.z.array(YS).max(100).optional(),ranges:$.z.array(wc).max(20).optional(),meta:$.z.array(ex).max(20).optional(),seed:$.z.string().optional(),name:$.z.string().optional(),phase:$.z.string().optional()},mi=$.z.strictObject({...Rm,key:$.z.string().min(1).max(255),variations:$.z.tuple([Ae,Ae]).rest(Ae).refine(e=>e.length<=20),urlPatterns:$.z.array($.z.strictObject({include:$.z.boolean(),type:$.z.enum(["regex","simple"]),pattern:$.z.string()})).max(100).optional(),force:$.z.number().int().nonnegative().optional(),active:$.z.boolean().optional(),persistQueryString:$.z.boolean().optional()}),Oc=$.z.strictObject({value:Ae,variationId:$.z.number().int(),key:$.z.string(),name:$.z.string().optional(),bucket:$.z.number().optional(),passthrough:$.z.boolean().optional(),inExperiment:$.z.boolean(),hashUsed:$.z.boolean().optional(),hashAttribute:$.z.string(),hashValue:$.z.string(),featureId:$.z.string().nullable(),stickyBucketUsed:$.z.boolean().optional()}),tx=$.z.strictObject({...Rm,id:$.z.string().max(255).optional(),force:Ae.optional(),variations:$.z.array(Ae).min(2).max(20).optional(),key:$.z.string().optional(),range:wc.optional(),tracks:$.z.array($.z.strictObject({experiment:mi,result:Oc})).max(100).optional()}),nx=$.z.strictObject({defaultValue:Ae.optional(),rules:$.z.array(tx).max(500).optional()}),ro=$.z.record($.z.string(),$.z.union([$.z.strictObject({type:$.z.literal("hashed"),attributeKey:$.z.string(),values:$.z.array($.z.string().regex(/^[a-f0-9]{64}$/))}),$.z.strictObject({type:$.z.literal("list"),attributeKey:$.z.string(),values:$.z.array($.z.union([$.z.string(),$.z.number()]))}),$.z.strictObject({type:$.z.literal("condition"),condition:Ht})])),pn=$.z.strictObject({scope:ze,generation:$.z.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.z.iso.datetime({offset:!0}),expiresAt:$.z.iso.datetime({offset:!0}).nullable(),features:$.z.record($.z.string(),nx),savedGroups:ro,experiments:$.z.record($.z.uuid(),mi)});var io=pn.extend({analyticsConfig:vc,remoteFeatures:Fe.z.array(Fe.z.string().min(1).max(255)).max(500)}),_c=io.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"})}),km=Fe.z.strictObject({attributes:xt,features:Fe.z.array(Fe.z.string().min(1).max(255)).max(500).optional(),customerId:Fe.z.uuid().optional()}),rx=Fe.z.strictObject({value:Ae,source:Fe.z.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Fe.z.boolean(),off:Fe.z.boolean(),ruleId:Fe.z.string(),experimentResult:Oc.optional()}),Ia=Fe.z.strictObject({generation:pn.shape.generation,evaluatedAt:pn.shape.evaluatedAt,expiresAt:pn.shape.expiresAt,features:Fe.z.record(Fe.z.string(),rx),merchandiseContext:Fe.z.strictObject({merchandiseId:Fe.z.uuid(),merchandise:xt}).optional()}),jm=Fe.z.strictObject({customerId:Fe.z.uuid().optional(),events:Fe.z.array(Fe.z.strictObject({eventUuid:Fe.z.uuid(),timestamp:Fe.z.iso.datetime({offset:!0}),name:Fe.z.string().min(1).max(255),merchandise:fd.optional(),properties:Fe.z.record(Fe.z.string(),Ae).default({}),deviceId:Fe.z.string().min(1).max(255).optional(),sessionId:Fe.z.string().min(1).max(255).optional()})).min(1).max(100)}),Tm=Fe.z.strictObject({inserted:Fe.z.number().int().nonnegative(),duplicates:Fe.z.number().int().nonnegative(),rejected:Fe.z.number().int().nonnegative(),skipped:Fe.z.number().int().nonnegative(),analyticsConfig:vc});var L=require("zod");function Cc(e,t=[]){let n=[];Lt(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(sa(e).map(i=>i.key));for(let[i,a]of Object.entries(e.strings.locales))for(let o of Object.keys(a))r.has(o)||n.push(`Unused string ${o} must not be delivered (${i})`);return n}function Nm(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Nm(t)??[])}}function ix(e){let t=e.pages.map(i=>{let a=Nm(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(sa({pages:t}).map(i=>i.key)),r=Object.fromEntries(Object.entries(e.strings.locales).map(([i,a])=>[i,Object.fromEntries(Object.entries(a).filter(([o])=>n.has(o)))]));return{...e,pages:t,strings:{...e.strings,locales:r}}}function Dm(e,t=[]){let n=rn.parse(structuredClone(ix(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=Cc(n,t);if(i.length)throw new Error(i.join("; "));return n}var Q=require("zod");var F=require("zod");var at=require("zod"),va=at.z.strictObject({schemaVersion:at.z.literal(1),renderKey:at.z.string().min(1).max(256),routeTemplate:at.z.string().startsWith("/").max(2048),selectors:at.z.array(at.z.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:at.z.array(at.z.number().int().min(0)).min(1),absent:at.z.array(at.z.number().int().min(0))}).superRefine((e,t)=>{let n=[...e.present,...e.absent];(new Set(e.selectors).size!==e.selectors.length||new Set(n).size!==n.length||n.length!==e.selectors.length||n.some(r=>r>=e.selectors.length))&&t.addIssue({code:"custom",message:"Incomplete or ambiguous render signature"})}),Fm=at.z.strictObject({renderKey:at.z.string().min(1).max(256),routeKey:at.z.string().min(1).max(256),stateKey:at.z.string().min(1).max(256),documentKey:at.z.string().min(1).max(256),documentHash:at.z.string().regex(/^[a-f0-9]{64}$/),compositionKey:at.z.string().min(1).max(256),entryMode:at.z.enum(["hard","soft"]),match:at.z.strictObject({present:at.z.array(at.z.number().int().min(0)),absent:at.z.array(at.z.number().int().min(0))})});var rr=require("zod"),ox=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Pc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ax=rr.z.string().regex(new RegExp(`^${Pc}/${Pc}/${Pc}/manifest\\.json$`)),Mm=rr.z.strictObject({kind:rr.z.literal("gcs-resumable"),url:rr.z.url(),bucket:rr.z.enum(ox),objectKey:ax,byteLength:rr.z.number().int().positive(),expiresAt:rr.z.iso.datetime()}).superRefine((e,t)=>{let n=new URL(e.url),r=n.searchParams,i=["uploadType","upload_id","name","upload_protocol","ifGenerationMatch"];(n.origin!=="https://storage.googleapis.com"||n.username||n.password||n.hash||n.pathname!==`/upload/storage/v1/b/${e.bucket}/o`||[...r.keys()].some(a=>!i.includes(a)||r.getAll(a).length!==1)||r.get("uploadType")!=="resumable"||!/^[A-Za-z0-9_-]{1,4096}$/.test(r.get("upload_id")??"")||r.has("name")&&r.get("name")!==`app-manifests/${e.objectKey}`||r.has("upload_protocol")&&r.get("upload_protocol")!=="resumable"||r.has("ifGenerationMatch")&&r.get("ifGenerationMatch")!=="0")&&t.addIssue({code:"custom",message:"Invalid IAM upload capability"})});var pt=F.z.string().min(1).max(256),an=F.z.string().regex(/^[a-f0-9]{64}$/),wa=F.z.strictObject({versionId:F.z.uuid(),manifestDigest:an,sourceGraphDigest:an,pageKey:pt,stateKey:pt,documentKey:pt,documentHash:an,elementKey:pt.optional(),nodeId:pt.optional(),contentHash:an.optional(),renderKey:pt.optional()}),qm=F.z.strictObject({pageKey:pt,documentKey:pt,expectedDocumentHash:an,renderKey:pt.optional(),nodeId:pt,elementKey:pt,expectedContentHash:an,property:F.z.enum(["text","fontSize","color"]),value:F.z.union([F.z.string().max(4e3),F.z.number().finite()])}),Vm=F.z.strictObject({versionId:F.z.uuid(),manifestDigest:an,sourceGraphDigest:an,pageKey:pt,stateKey:pt,documentKey:pt,documentHash:an,renderKey:pt.optional(),patches:F.z.array(qm.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),sx=/^[a-z][a-z0-9-]{0,39}$/,oo=F.z.string().regex(sx),Rc=F.z.enum(["web","ios","android"]),u1=F.z.discriminatedUnion("action",[F.z.strictObject({action:F.z.literal("register"),requestId:F.z.uuid(),client:oo,platform:Rc,label:F.z.string().trim().min(1).max(100),sha256:an,bytes:F.z.number().int().min(1),transferBytes:F.z.number().int().min(1)}),F.z.strictObject({action:F.z.literal("complete"),versionId:F.z.uuid()}),F.z.strictObject({action:F.z.literal("current"),versionId:F.z.uuid(),expectedCurrent:F.z.uuid().nullable()}),F.z.strictObject({action:F.z.literal("delivery"),enabled:F.z.boolean()}),F.z.strictObject({action:F.z.literal("changes"),versionId:F.z.uuid(),experimentId:F.z.uuid(),variationId:pt,changesetId:F.z.uuid().nullable(),expectedRevision:an.nullable(),editorUrl:F.z.string().url().max(2048),patches:F.z.array(qm).max(200)})]),kc=F.z.strictObject({id:F.z.uuid(),projectId:F.z.uuid(),environmentId:F.z.uuid(),clientKey:oo,platform:Rc,label:F.z.string(),sha256:an,bytes:F.z.number().int().positive(),objectKey:F.z.string(),state:F.z.enum(["uploading","ready","rejected"]),isCurrent:F.z.boolean(),revision:F.z.number().int().nonnegative(),createdAt:F.z.string(),expiresAt:F.z.string(),readyAt:F.z.string().nullable(),summary:F.z.record(F.z.string(),F.z.json()),routeTree:F.z.json().nullable(),validation:F.z.record(F.z.string(),F.z.json())}),cx=F.z.strictObject({key:oo,platform:Rc,currentId:F.z.uuid().nullable()}),l1=F.z.strictObject({rows:F.z.array(kc).max(100),nextCursor:F.z.uuid().nullable(),clients:F.z.array(cx).max(20)}),Ec=F.z.strictObject({storedBytes:F.z.number().int().nonnegative(),reservedBytes:F.z.number().int().nonnegative(),chargedBytes:F.z.number().int().nonnegative(),versions:F.z.number().int().nonnegative(),objects:F.z.number().int().nonnegative(),orphanObjects:F.z.number().int().nonnegative(),missingReadyObjects:F.z.number().int().nonnegative(),unknownObjectSizes:F.z.number().int().nonnegative(),byteLimit:F.z.number().int().positive(),versionLimit:F.z.number().int().positive(),remainingBytes:F.z.number().int().nonnegative()}),d1=F.z.strictObject({asOf:F.z.iso.datetime({offset:!0}),reclamation:F.z.literal("manual-review-required"),buckets:F.z.strictObject({source:Ec,runtime:Ec,previews:Ec})}),p1=F.z.strictObject({version:kc,actorId:F.z.uuid(),claims:F.z.record(F.z.string(),F.z.json())}),m1=F.z.strictObject({version:kc,upload:Mm.nullable()}),f1=F.z.object({format:F.z.literal("indiana-route-state-index"),schemaVersion:F.z.literal(3),routes:F.z.array(F.z.object({routeKey:pt,path:F.z.string(),documentKey:pt,documentHash:an,initialStateKey:pt,initialRenderKey:pt})),renders:F.z.array(Fm)}).loose().superRefine((e,t)=>{(!e.renders||e.routes.some(n=>!e.renders?.some(r=>r.renderKey===n.initialRenderKey&&r.routeKey===n.routeKey&&r.documentKey===n.documentKey&&r.stateKey===n.initialStateKey&&r.documentHash===n.documentHash&&r.entryMode==="hard")))&&t.addIssue({code:"custom",message:"Incomplete render catalog"})}),g1=F.z.strictObject({rows:F.z.array(F.z.object({id:F.z.uuid(),name:F.z.string(),status:F.z.string(),variations:F.z.array(F.z.object({id:pt,key:pt,name:F.z.string().optional()}).loose())}).loose()),limited:F.z.boolean()}),h1=F.z.strictObject({enabled:F.z.boolean(),allowedOrigins:F.z.array(F.z.string())});var Mr=require("zod");var Bm=Mr.z.strictObject({id:Mr.z.uuid(),name:Mr.z.string().trim().min(1).max(80),client:oo,source:wa,event:Mr.z.enum(["screen_enter","button_click"]),cooldownSeconds:Mr.z.number().int().min(0).max(2592e3),behavior:Mr.z.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"})});var Ve=require("zod");var jc=Ae,ux=["parameters","answers","results","variables"];function Tc(e){return ux.some(t=>e===t||e.startsWith(t+"."))}function Nc(e){let t={};for(let[r,i]of Object.entries(ca(e.declarations,e))){let a=r.split(".");if(a.some(c=>["__proto__","constructor","prototype"].includes(c)))throw new Error("Reserved result path");let o=t;for(let c of a.slice(0,-1)){Object.hasOwn(o,c)||(o[c]={});let u=o[c];if(!u||typeof u!="object"||Array.isArray(u))throw new Error("Ambiguous result path");o=u}let s=a.at(-1);if(s===void 0)throw new Error("Empty result path");o[s]=i}return{...Object.fromEntries(Object.entries(e.attributes).filter(([r])=>!Tc(r))),variables:t}}var ct=require("zod");var Oa=ct.z.discriminatedUnion("kind",[ct.z.object({kind:ct.z.literal("ledger"),cursor:na}).strict(),ct.z.object({kind:ct.z.literal("billing"),cursor:ct.z.uuid()}).strict()]),lx=ct.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ir=ct.z.record(ct.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ct.z.union([ct.z.string().max(500),ct.z.boolean(),ct.z.array(ct.z.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),dx=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Dc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Dc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||dx.test(n)||Dc(r,t+1)))}var px=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,or=ct.z.record(lx,Ae).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Dc(e)&&!px.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var Um=ct.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),_a=ct.z.array(ct.z.object({variable:Um,componentId:Um,required:ct.z.boolean()}).strict()).max(40).refine(e=>new Set(e.map(t=>t.variable)).size===e.length&&new Set(e.map(t=>t.componentId)).size===e.length,"Input bindings must be unique"),_1=ct.z.object({bindings:_a,answers:ir,values:ct.z.record(ct.z.string(),Ae).optional()}).strict();var Lm=require("zod"),Ca=Lm.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Fc=Ve.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),zm=Ve.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),$m=or.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Mc=Ve.z.record(Fc,Ve.z.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),mx=Pn,Gm=Ve.z.strictObject({type:Ve.z.literal("external_task"),endpointId:Ve.z.uuid(),taskKey:Fc,inputs:Ve.z.record(Fc,mx).refine(e=>Object.keys(e).length<=20),outputs:Mc}),Km=Ve.z.strictObject({maxAttempts:Ve.z.number().int().min(1).max(5),retryDelaySeconds:Ve.z.number().int().min(1).max(30),backoff:Ve.z.enum(["fixed","exponential"]),requestTimeoutSeconds:Ve.z.number().int().min(1).max(10),timeoutSeconds:Ve.z.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var N1=Ve.z.strictObject({outcome:Ve.z.enum(["success","failure"]),data:$m});var D1=Ve.z.discriminatedUnion("operation",[Ve.z.strictObject({operation:Ve.z.literal("signal"),runId:Ve.z.uuid(),nodeId:zm,eventName:Ca,eventId:Ve.z.uuid(),data:$m}),Ve.z.strictObject({operation:Ve.z.literal("read_results"),runId:Ve.z.uuid()})]),F1=Ve.z.strictObject({scope:ze,runId:Ve.z.uuid(),eventId:Ve.z.uuid(),accepted:Ve.z.boolean()}),fx=Ve.z.record(zm,jc),M1=Ve.z.strictObject({scope:ze,runId:Ve.z.uuid(),results:fx});var In={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Hm="00000000-0000-0000-0000-000000000000";var J=require("zod");var Qe=require("zod");var L1=Qe.z.enum(["local","remote"]),qc=Qe.z.strictObject({port:Qe.z.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Ae.optional(),sticky:Qe.z.array(Qe.z.strictObject({expected:Ni.nullable(),next:Ni})).max(100),exposures:Qe.z.array(Ae).max(100),features:Qe.z.array(Ae).max(100)}),Qm=Qe.z.strictObject({type:Qe.z.literal("evaluate"),receiptId:Qe.z.uuid(),environmentId:Qe.z.uuid(),policyRevision:Qe.z.number().int().nonnegative(),attributes:xt,sticky:Qe.z.record(Qe.z.string(),Ni)}),Jm=Qm.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative()}),Vc=Qm.omit({type:!0,receiptId:!0}).extend({type:Qe.z.literal("evaluate_segment")}),Zm=Qe.z.strictObject({nodeId:Qe.z.string().min(1).max(64),result:qc}),Wm=Vc.extend({runId:Qe.z.uuid(),versionId:Qe.z.uuid(),nodeId:Qe.z.string().min(1).max(64),visit:Qe.z.number().int().nonnegative(),revision:Qe.z.number().int().nonnegative(),parameters:or,answers:ir,variables:Qe.z.record(Qe.z.string(),Ae)});var ae=require("zod");var Bc=ae.z.array(ae.z.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"),Pa=ae.z.intersection(xt,ae.z.looseObject({tags:Bc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ea=ae.z.string().trim().max(80),Ra=ae.z.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),ka=ae.z.union([ae.z.email().max(254),ae.z.literal("")]),ja=ae.z.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Ym=ae.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Xm=ae.z.object({externalUserId:Ym.optional(),name:Ea.default(""),email:ka.default(""),phone:Ra.optional(),attributes:Pa.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),Ta=ae.z.discriminatedUnion("type",[ae.z.strictObject({type:ae.z.literal("id"),value:ae.z.uuid()}),ae.z.strictObject({type:ae.z.literal("externalUserId"),value:Ym})]),Na=ae.z.strictObject({name:Ea.optional(),email:ka.optional(),phone:Ra.optional(),attributes:Pa.optional(),fingerprint:ja.optional()}),Da=e=>!e.customerData||e.customer?.type==="externalUserId",Fa="customerData requires an externalUserId customer",fi=ae.z.object({id:ae.z.uuid(),externalUserId:ae.z.string().min(1).max(255).nullable(),name:Ea,email:ka,phone:Ra.optional(),attributes:Pa,createdAt:ae.z.iso.datetime()}).strict(),ef=ae.z.object({customer:fi,changed:ae.z.boolean(),replayed:ae.z.boolean()}).strict(),gx=ae.z.discriminatedUnion("type",[ae.z.object({type:ae.z.literal("id"),value:ae.z.uuid()}).strict(),ae.z.object({type:ae.z.literal("externalUserId"),value:ae.z.string().trim().min(1).max(255)}).strict()]),hx=ae.z.object({name:Ea.optional(),email:ka.optional(),phone:Ra.optional(),attributes:Pa.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ae.z.array(ae.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ae.z.strictObject({add:Bc,remove:Bc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Uc=ae.z.object({lookup:gx}).strict(),tf=Uc.extend({requestId:ae.z.uuid(),patch:hx}).strict(),nf=ae.z.object({search:ae.z.string().trim().max(200).default(""),tag:ae.z.string().trim().max(40).default(""),planId:ae.z.string().max(200).default(""),versionId:ae.z.string().max(200).default(""),holdingStatus:ae.z.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ae.z.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ae.z.union([ae.z.iso.datetime(),ae.z.literal("")]).default(""),createdUntil:ae.z.union([ae.z.iso.datetime(),ae.z.literal("")]).default(""),offset:ae.z.coerce.number().int().min(0).max(1e5).default(0),limit:ae.z.coerce.number().int().min(1).max(100).default(50)}).strict(),rf=ae.z.object({customers:fi.array(),hasMore:ae.z.boolean(),total:ae.z.number().int().nonnegative().nullable(),evaluatedAt:ae.z.iso.datetime()}).strict();var ao=J.z.discriminatedUnion("type",[J.z.strictObject({type:J.z.literal("literal"),value:Ae}),J.z.strictObject({type:J.z.literal("variable"),key:ft,path:xn.optional()}),J.z.strictObject({type:J.z.literal("feature"),featureKey:J.z.string().min(1).max(128)})]),Ax=J.z.strictObject({requestId:J.z.uuid(),decisionId:J.z.uuid(),customerId:J.z.uuid(),externalUserId:J.z.string().min(1).max(255).nullable(),versionId:J.z.uuid(),receiptId:J.z.uuid(),value:Ae}),yx={funnelId:J.z.uuid(),requestId:J.z.uuid(),customer:Ta,customerData:Na.optional(),attributes:xt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},Y1=J.z.discriminatedUnion("operation",[J.z.strictObject({operation:J.z.literal("decide"),...yx}).refine(Da,Fa),J.z.strictObject({operation:J.z.literal("read_decision"),decisionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("evaluate_decision"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),receiptId:J.z.uuid(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),result:qc}),J.z.strictObject({operation:J.z.literal("feature_config"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("commit_decision_segment"),decisionId:J.z.uuid(),requestId:J.z.uuid(),nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative(),revision:J.z.number().int().nonnegative(),policyRevision:J.z.number().int().nonnegative(),generation:J.z.string().min(1).max(256),steps:J.z.array(Zm).max(32),boundary:J.z.strictObject({nodeId:J.z.string().min(1).max(64),visit:J.z.number().int().nonnegative()}).optional()}),J.z.strictObject({operation:J.z.literal("segment_configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("configuration"),funnelId:J.z.uuid(),versionId:J.z.uuid().optional()}),J.z.strictObject({operation:J.z.literal("local_configuration"),funnelId:J.z.uuid()}),J.z.strictObject({operation:J.z.literal("report_used"),decisionId:J.z.uuid(),eventId:J.z.uuid(),occurredAt:J.z.iso.datetime({offset:!0}),reference:J.z.string().min(1).max(128).optional()})]),X1=J.z.strictObject({scope:ze,decisionId:J.z.uuid(),requestId:J.z.uuid(),status:J.z.enum(["pending","completed","failed"]),decision:Ax.nullable(),evaluation:J.z.discriminatedUnion("type",[Jm,Wm]).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"),eC=J.z.strictObject({scope:ze,decisionId:J.z.uuid(),eventId:J.z.uuid(),source:J.z.literal("caller_reported")});var _t=require("zod");var of=_t.z.strictObject({type:_t.z.literal("bundle"),paywall:Pn.optional(),offering:Pn.optional(),coupons:Pn,data:Pn}),bx=e=>_t.z.strictObject({type:_t.z.literal(e),id:_t.z.uuid()}),oC=_t.z.strictObject({type:_t.z.literal("bundle"),paywallVersionId:_t.z.uuid().optional(),offeringVersionId:_t.z.uuid().optional(),couponIds:_t.z.array(_t.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Ae});var aC=_t.z.strictObject({type:_t.z.literal("bundle"),offering:bx("offering_version").nullable(),paywall:_t.z.strictObject({versionId:_t.z.uuid(),paywallId:_t.z.uuid(),offeringVersionId:_t.z.uuid()}).nullable(),coupons:_t.z.array(Di).max(20),data:Ae});var mn=require("zod");var sn=require("zod");var af=sn.z.union([sn.z.string(),sn.z.number().finite(),sn.z.boolean(),sn.z.null()]),Sx=sn.z.union([af,sn.z.array(af).min(1).max(20)]),xx=sn.z.record(xn,Sx).refine(e=>Object.keys(e).length<=10),sf=sn.z.strictObject({path:xn,type:sn.z.enum(["string","number","boolean","strings"]),nullable:sn.z.boolean().optional(),aggregation:sn.z.enum(["count","exists"]).optional(),where:xx.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 Ix=["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"],cf=mn.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),vx=Pn,uf=mn.z.discriminatedUnion("type",[Gm,mn.z.strictObject({type:mn.z.literal("claim_offer"),coupon:Pn}),mn.z.strictObject({type:mn.z.literal("event"),event:cf}),mn.z.strictObject({type:mn.z.literal("api"),operation:mn.z.enum(Ix),inputs:mn.z.record(xn,vx).refine(e=>Object.keys(e).length<=40),outputs:mn.z.record(cf,sf).refine(e=>Object.keys(e).length<=20)})]);var ot=Ca,wx=Q.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),cn={id:ot,name:Q.z.string().trim().min(1).max(80),position:Q.z.strictObject({x:Q.z.number().finite(),y:Q.z.number().finite()}).optional()},Ox={success:ot,cancel:ot,unavailable:ot,failure:ot},Lc=Q.z.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),zc=Q.z.enum(["same_window","new_window"]),_x=Q.z.discriminatedUnion("type",[Q.z.strictObject({...cn,type:Q.z.literal("entry"),next:ot,triggers:Q.z.array(Bm).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.z.strictObject({...cn,type:Q.z.literal("screen"),screenId:ot,presentation:Bn,outputs:Q.z.record(ot,ot),offering:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("variable"),key:ft}),Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()})]).optional()}),Q.z.strictObject({...cn,type:Q.z.literal("offering"),configuration:Q.z.discriminatedUnion("source",[Q.z.strictObject({source:Q.z.literal("fixed"),versionId:Q.z.uuid()}),Q.z.strictObject({source:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128)})]),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("coupon"),couponId:Q.z.uuid(),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("coupons"),couponIds:Q.z.array(Q.z.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("output"),value:Q.z.discriminatedUnion("type",[...ao.options,of,Q.z.strictObject({type:Q.z.literal("selection"),screenId:ot,offeringKey:ft})])}),Q.z.strictObject({...cn,type:Q.z.literal("condition"),cases:Q.z.array(Q.z.strictObject({condition:Ht,target:ot})).min(1).max(50),default:ot}),Q.z.strictObject({...cn,type:Q.z.literal("feature"),featureKey:Q.z.string().min(1).max(128),writes:Q.z.strictObject({value:ft}),next:ot}),Q.z.strictObject({...cn,type:Q.z.literal("split"),experimentId:Q.z.uuid(),applyPageExperiment:Q.z.literal(!0).optional(),routes:Q.z.record(wx,ot).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:ot}),Q.z.strictObject({...cn,type:Q.z.literal("action"),...Ox,execution:Km,action:uf,writes:ic.optional()}),Q.z.strictObject({...cn,type:Q.z.literal("external_page"),appManifest:wa.optional(),url:Lc,openIn:zc,opened:ot,failed:ot}),Q.z.strictObject({...cn,type:Q.z.literal("end"),outcome:Q.z.enum(["completed","closed","ineligible","failed"]),output:ao.optional()}),Q.z.strictObject({...cn,type:Q.z.literal("wait"),writes:ic.optional(),wait:Q.z.discriminatedUnion("type",[Q.z.strictObject({type:Q.z.literal("duration"),delaySeconds:Q.z.number().int().min(1).max(2592e3),elapsed:ot}),Q.z.strictObject({type:Q.z.literal("event"),eventName:ot,outputs:Mc,timeoutSeconds:Q.z.number().int().min(1).max(2592e3),received:ot,timeout:ot})])})]),$c=Q.z.strictObject({version:Q.z.literal(5),entry:ot,nodes:Q.z.array(_x).min(1).max(In.flowNodes)}),Gc=$c.superRefine((e,t)=>{Cx(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Ma(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 Cx(e,t){let n=[],r=new Map(e.nodes.map(d=>[d.id,d])),i=(d,m,w)=>{n.push(d),t?.({message:d,reason:m,path:w?["nodes",e.nodes.indexOf(w)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(d=>d.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(d=>d.type==="screen").length>In.pages||e.nodes.filter(d=>!["screen","entry","end","output"].includes(d.type)).length>In.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let d of e.nodes){for(let m of Ma(d))m===e.entry&&i("An entry cannot be a transition target","entryTarget",d),r.has(m)||i(`Missing target ${m}`,"missingTarget",d);d.type==="screen"&&(a.has(d.screenId)&&i("Every screen has exactly one node owner","screenOwner",d),a.add(d.screenId))}let o=new Set,s=new Set,c=new Set;function u(d){if(o.has(d)){i("Flow edges must not form a cycle","cycle",r.get(d));return}if(!(s.has(d)||!r.has(d))){o.add(d),c.add(d);for(let m of Ma(r.get(d)))u(m);o.delete(d),s.add(d)}}u(e.entry);for(let d of e.nodes)c.has(d.id)||i("Every node must be reachable from Entry","unreachable",d);return[...new Set(n)]}var Kc={maxTransitions:1e4,runTimeoutSeconds:2592e3};function lf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(d=>s===d||c&&s.startsWith(d+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Zn(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}var M=require("zod");var gi=M.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),qa=e=>M.z.record(M.z.string(),Ae).refine(t=>on(t)<=e,"Funnel evidence exceeds its byte budget"),TC=M.z.enum(["local_segment","evaluation","presentation","timer","event","operation"]),Qc=M.z.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Jc=M.z.discriminatedUnion("type",[M.z.strictObject({type:M.z.literal("flag"),key:M.z.string().min(1).max(128)}),M.z.strictObject({type:M.z.literal("experiment"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("saved_group"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("config"),key:M.z.string().min(1).max(128)}),M.z.strictObject({type:M.z.literal("constant"),key:M.z.string().min(1).max(128)}),M.z.strictObject({type:M.z.literal("paywall_version"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("offering_version"),id:M.z.uuid()}),M.z.strictObject({type:M.z.literal("reward"),id:M.z.uuid()})]),so=M.z.strictObject({schemaVersion:M.z.literal(1),kind:Qc,selector:Jc.nullable(),context:qa(131072),contract:M.z.strictObject({version:M.z.number().int().positive(),evaluator:M.z.string().min(1).max(128),policyRevision:M.z.number().int().nonnegative()})}).refine(e=>on(e)<=131072,"Node input exceeds its byte budget"),df=M.z.strictObject({schemaVersion:M.z.literal(1),kind:Qc,outcome:M.z.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:qa(131072),route:M.z.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:qa(131072)}).refine(e=>on(e)<=131072,"Node result exceeds its byte budget"),NC=M.z.strictObject({schemaVersion:M.z.literal(1),operations:M.z.record(gi,M.z.strictObject({attempts:M.z.number().int().nonnegative(),maxAttempts:M.z.number().int().min(1).max(5),deadlineAt:M.z.iso.datetime({offset:!0}),retryAt:M.z.iso.datetime({offset:!0}).nullable(),error:M.z.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:M.z.strictObject({type:gi,id:M.z.uuid()}).nullable()}))}).refine(e=>on(e)<=65536,"Execution state exceeds its byte budget"),qr={receiptId:M.z.uuid()},Hc=M.z.iso.datetime({offset:!0}),DC=M.z.discriminatedUnion("type",[M.z.strictObject({type:M.z.literal("node_entered"),details:M.z.strictObject({kind:Qc})}),M.z.strictObject({type:M.z.literal("presentation_shown"),details:M.z.strictObject({...qr,source:M.z.literal("client"),occurredAt:Hc.optional()})}),M.z.strictObject({type:M.z.literal("decision_accepted"),details:M.z.strictObject(qr)}),M.z.strictObject({type:M.z.literal("signal_received"),details:M.z.strictObject({signalId:M.z.uuid(),nodeId:gi,eventName:gi,data:qa(8192),source:M.z.literal("server"),occurredAt:Hc})}),M.z.strictObject({type:M.z.literal("signal_consumed"),details:M.z.strictObject({...qr,signalId:M.z.uuid()})}),M.z.strictObject({type:M.z.literal("wait_elapsed"),details:M.z.strictObject(qr)}),M.z.strictObject({type:M.z.literal("wait_timeout"),details:M.z.strictObject(qr)}),M.z.strictObject({type:M.z.literal("operation_completed"),details:M.z.strictObject({...qr,operation:gi,reference:M.z.strictObject({type:gi,id:M.z.uuid()}).nullable()})}),M.z.strictObject({type:M.z.literal("execution_recovered"),details:M.z.strictObject({generation:M.z.number().int().positive(),reason:M.z.enum(["interrupted","expired_lease","delivery_failed"])})}),M.z.strictObject({type:M.z.literal("execution_failed"),details:M.z.strictObject({generation:M.z.number().int().positive(),code:M.z.string().regex(/^[a-z_]{1,64}$/)})}),M.z.strictObject({type:M.z.literal("run_completed"),details:M.z.strictObject({outcome:M.z.enum(["completed","ineligible","failed"])})}),M.z.strictObject({type:M.z.literal("run_closed"),details:M.z.strictObject({source:M.z.enum(["client","server","expiry"])})}),M.z.strictObject({type:M.z.literal("treatment_used"),details:M.z.strictObject({...qr,source:M.z.enum(["client","server"]),occurredAt:Hc,reference:M.z.string().min(1).max(128).optional()})})]);var fn=L.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Px=L.z.discriminatedUnion("type",[L.z.strictObject({id:fn,type:L.z.literal("owned"),publicData:Pm.optional(),document:rn.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")}),L.z.strictObject({id:fn,type:L.z.literal("paywall"),paywallVersionId:L.z.uuid()})]),Zc={kind:L.z.literal("funnel"),schemaVersion:L.z.literal(4),screens:L.z.array(Px).max(In.pages),references:L.z.record(fn,Jc).refine(e=>Object.keys(e).length<=500),inputs:L.z.array(L.z.strictObject({variable:fn,screenId:fn,componentId:fn,required:L.z.boolean()})).max(In.questions),variables:L.z.record(ft,ri).refine(e=>Object.keys(e).length<=In.logicNodes),outputSchema:ni,execution:L.z.strictObject({runTimeoutSeconds:L.z.number().int().min(1).max(Kc.runTimeoutSeconds),maxTransitions:L.z.number().int().min(1).max(Kc.maxTransitions)})},XC=L.z.strictObject({...Zc,graph:$c});function Ex(e,t){let n=!1,r=(i,a)=>{let o=i.type==="stack"||i.type==="button"?i.bind?.coupon??a:a;i.type==="text"&&Object.values(e.strings.locales).some(s=>s[i.text]?.includes("{{offer."))&&!(o&&t(o))&&(n=!0),i.type==="stack"&&i.children.forEach(s=>r(s,o))};for(let i of e.pages)r(i.root);return n}function Ba(e){return Array.isArray(e)?e.some(Ba):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Hm:Ba(n))}function Rx(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=Dm(i.document)}catch(o){t.push({message:o instanceof Error?o.message:"Screen cannot be delivered",reason:"screen",path:["screens",r,"document"]});continue}for(let[o,s]of e.inputs.entries())s.screenId===i.id&&!Wi(a,s.componentId)&&t.push({message:`Local Funnel input ${s.variable} targets hidden component ${s.componentId} on screen ${s.screenId}`,reason:"inputBinding",path:["inputs",o]})}for(let[r,i]of e.graph.nodes.entries()){let a=["graph","nodes",r],o=i.type==="screen"?e.screens.find(s=>s.id===i.screenId):void 0;o?.type==="owned"&&(o.document.actions.some(s=>typeof s.properties.templateKey=="string"&&s.properties.templateKey.startsWith("popup-coupon-"))&&t.push({message:"Funnel screens claim Coupons through a Claim Coupon step",reason:"coupon",path:a}),Ex(o.document,s=>n.has(s))&&t.push({message:"Offer copy shows the Coupon of a Claim Coupon step",reason:"coupon",path:a})),(i.type==="output"&&i.value.type==="literal"&&Ba(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Ba(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function pf(e,t){for(let{message:n,reason:r,path:i}of Rx(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function mf(e,t){let n=(I,p,g=[])=>t.addIssue({code:"custom",message:I,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(I=>[I.id,I])),a=(I,p)=>r.some(g=>g.type===I&&("id"in g?g.id:g.key)===p);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(I=>I.type==="screen");(o.length!==i.size||o.some(I=>!i.has(I.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(I=>c.some(p=>I!==p&&p.startsWith(I+".")))&&n("Variable paths must not overlap","variable");function u(I,p){Object.hasOwn(e.variables,I)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(I)??new Set;g.add(p.id),s.set(I,g)}for(let[I,p]of e.graph.nodes.entries()){let g=["graph","nodes",I],f=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;f&&!a("flag",f)&&n("Flag selectors require an explicit GB resource reference","feature",g);let S=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):[],A="writes"in p?p.writes??{}:{};(S.length!==Object.keys(A).length||S.some(v=>!Object.hasOwn(A,v))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[v,k]of Object.entries(A)){u(k,p);let N=e.variables[k],B=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[v]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[v]:void 0;(N?.source.type!=="node"||B&&N.type!==B)&&n("Node writer source or output type does not match declaration","variable",g)}if(p.type==="coupons"){let v=e.variables[p.writes.value];(v?.type!=="array"||v.items?.type!=="reward"||v.items.nullable||v.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let k of p.couponIds)a("reward",k)||n("Coupons require Reward references","coupon",g)}if(p.type==="split"&&!a("experiment",p.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",g),p.type==="coupon"&&!a("reward",p.couponId)&&n("Coupon selectors require a Reward reference","coupon",g),p.type==="action"&&p.action.type==="claim_offer"&&p.action.coupon.source==="literal"){let v=p.action.coupon.value;(!v||typeof v!="object"||Array.isArray(v)||v.type!=="reward"||typeof v.id!="string"||Object.keys(v).length!==2||!a("reward",v.id))&&n("Coupon claims require a Reward reference","coupon",g)}if(p.type==="offering"&&p.configuration.source==="fixed"&&!a("offering_version",p.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",g),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",g),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",g),p.type==="screen"){let v=i.get(p.screenId);if(p.offering?.source==="fixed"&&!a("offering_version",p.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",g),v?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),v?.type==="paywall"&&!a("paywall_version",v.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),v?.type==="owned"){let k=v.document.pages[0];if(!k){n("Owned screen requires a page","screen",g);continue}er(v.document).some(B=>!B.complete)&&n("Owned screens require complete local content","translations",g);let N=new Set(v.document.actions.map(B=>B.id));(N.size!==Object.keys(p.outputs).length||Object.keys(p.outputs).some(B=>!N.has(B)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",g),Xn(k.root,B=>{!p.offering&&(B.type==="plan_picker"||(B.type==="stack"||B.type==="button")&&B.bind?.plan||B.type==="customer_data"&&["customer_plans","credit_packs"].includes(B.data.source))&&n("Product presentation requires an Offering Version","offering",g),B.type==="customer_data"&&Object.values(B.data.outputs??{}).some(fe=>fe!==void 0&&!N.has(fe))&&n("Customer components require declared screen outcomes","componentOutput",g)})}}p.type==="end"&&["completed","ineligible"].includes(p.outcome)&&!p.output&&n("Completed and ineligible ends require a declared output","output",g),p.type==="end"&&p.output?.type==="literal"&&!dn(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!dn(e.outputSchema,p.value.value)&&n("Terminal output does not match outputSchema","output",g);let P=p.type==="output"?p.value:p.type==="end"?p.output:void 0;if(P?.type==="variable"&&!P.path){let v=e.variables[P.key];v&&!oc(v,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let v=i.get(p.screenId);if(v?.type==="owned")for(let k of cc(v.document))(/^(input|params)\./.test(k)||k.startsWith("variables.")&&!sc(k.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let v of p.cases){for(let k of Mn(v.condition))a("saved_group",k)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let k of Zn(v.condition))k.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",g)}if(p.type==="output"&&p.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",g);for(let[v,k]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let N=p.value[v];if(N)if(N.source==="literal"){let B=v==="coupons"?N.value:[N.value];(!Array.isArray(B)||B.length>20||B.some(fe=>!dn({type:k,nullable:!1},fe)||!a(k,fe.id))||v==="coupons"&&new Set(B.map(fe=>fe.id)).size!==B.length)&&n("Bundle requires distinct scoped resource references",v==="coupons"?"coupon":v==="paywall"?"paywall":"offering",[...g,"value",v])}else{let B=e.variables[N.key];(N.path||!B||B.nullable||(v==="coupons"?B.type!=="array"||B.items?.type!=="reward"||B.items.nullable:B.type!==k))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[I,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...lf(p,c),...g?.type==="owned"?ua(g.document).map(S=>sc(S,c)?.key??S):[]];for(let S of new Set(f)){let k=function(N){if(N===p.id)return!0;if(v.has(N))return!1;v.add(N);let B=e.graph.nodes.find(Ie=>Ie.id===N);return B?(P.has(N)?B.type==="action"?[B.cancel,B.unavailable,B.failure]:B.type==="wait"&&B.wait.type==="event"?[B.wait.timeout]:[]:Ma(B)).some(k):!1};var w=k;if(!Object.hasOwn(e.variables,S)){n("Consumed variable is undeclared","variable",["graph","nodes",I]);continue}let A=e.variables[S];if(p.type==="screen"&&A.source.type==="input"&&e.inputs.some(N=>N.screenId===p.screenId&&N.variable===S)||A.source.type==="parameter"||A.source.type==="attribute")continue;let P=A.source.type==="input"?new Set(e.inputs.filter(N=>N.variable===S&&N.required).flatMap(N=>o.filter(B=>B.screenId===N.screenId).map(B=>B.id))):s.get(S)??new Set,v=new Set;(!P.size||k(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",I])}}(new Set(e.inputs.map(I=>I.variable)).size!==e.inputs.length||new Set(e.inputs.map(I=>`${I.screenId}:${I.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[I,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",I]);let g=i.get(p.screenId),f=g?.type==="owned"?Wi(g.document,p.componentId):null;if((f?.type!=="stack"||!f.interaction||!["input","toggle","select","multiselect","tabs"].includes(f.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",I]),f?.type==="stack"&&f.interaction){let S=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==S&&n("Input variable type does not match component","inputBinding",["inputs",I]);let A=e.variables[p.variable]?.enum;A&&!f.children.filter(P=>!P.hidden).every(P=>A.includes(P.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",I])}}for(let[I,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",I]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===I)&&n("Input variable requires a component binding","inputBinding",["variables",I]);let d=0,m=0;for(let I of e.screens)if(I.type==="owned"){for(let p of I.document.pages)Xn(p.root,()=>{d++});m+=I.document.actions.length}(d>In.components||m>In.actions||on(e)>In.documentBytes)&&n("Funnel document exceeds its budget","budget")}var kx=L.z.strictObject({...Zc,graph:Gc}).superRefine(mf),hi=L.z.strictObject({...Zc,graph:Gc,displayName:L.z.string().trim().min(1).max(80)}).superRefine(mf),eP=hi.superRefine(pf),tP=kx.superRefine(pf),Va=L.z.string().regex(Vt),co={requestId:L.z.uuid(),nodeId:fn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),customerToken:Va.optional()},jx=L.z.discriminatedUnion("type",[L.z.strictObject({type:L.z.literal("screen"),output:fn,answers:ir,selection:L.z.record(fn,L.z.union([L.z.string().max(200),L.z.boolean(),L.z.number().int().min(0).max(1e4)])).optional()}),L.z.strictObject({type:L.z.literal("paywall_quote"),featureQuantities:L.z.record(L.z.uuid(),L.z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:fn,productVersionId:L.z.uuid(),offerId:L.z.uuid().optional(),nativeOffer:ai.optional(),predecessor:L.z.strictObject({operationId:L.z.uuid().nullable(),generation:L.z.number().int().positive()}).optional()}),L.z.strictObject({type:L.z.literal("paywall_confirm"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("paywall_cancel"),operationId:L.z.uuid()}),L.z.strictObject({type:L.z.literal("client_action"),receiptId:L.z.uuid(),outcome:L.z.enum(["success","cancel","failure","opened","failed"])})]),Tx=L.z.object({nodeId:fn,visit:L.z.number().int().nonnegative(),revision:L.z.number().int().nonnegative(),components:L.z.record(fn,L.z.object({resourceKey:L.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:L.z.number().int().min(1).max(1e5),after:Oa.nullable(),filter:L.z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Un=L.z.discriminatedUnion("operation",[L.z.strictObject({operation:L.z.literal("start"),funnelId:L.z.uuid(),requestId:L.z.uuid(),customer:Ta.optional(),customerData:Na.optional(),locale:L.z.string().min(1).max(35),parameters:or}).refine(Da,Fa),L.z.strictObject({operation:L.z.literal("get"),settlementRequestId:L.z.uuid().optional(),data:Tx.optional(),purchase:L.z.strictObject({receiptId:L.z.uuid(),operationId:L.z.uuid()}).optional(),customerToken:Va.optional()}),L.z.strictObject({operation:L.z.literal("resume"),requestId:L.z.uuid(),customerToken:Va.optional()}),L.z.strictObject({operation:L.z.literal("submit"),...co,input:jx}),L.z.strictObject({operation:L.z.literal("back"),...co}),L.z.strictObject({operation:L.z.literal("shown"),...co}),L.z.strictObject({operation:L.z.literal("close"),...co}),L.z.strictObject({operation:L.z.literal("commit_segment"),...co,policyRevision:L.z.number().int().nonnegative(),generation:L.z.string().min(1).max(256)}),L.z.strictObject({operation:L.z.literal("review"),receiptId:L.z.uuid().optional(),customerToken:Va.optional()})]);function Ua(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(p){for(let g of Mn(p))d(g)}function d(p){if(i.has(p)||!Object.hasOwn(t.savedGroups,p))return;let g=t.savedGroups[p];g&&(i.add(p),c.set(p,g),a.push(()=>{!Array.isArray(g)&&g.type==="condition"&&u(g.condition)}))}function m(p){for(let g of["hashAttribute","fallbackAttribute"])if(p[g]!==void 0&&Tc(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])w(g.id),u(g.condition)}function w(p,g=!1){let f=Object.hasOwn(t.features,p)?t.features[p]:void 0;if(!f){if(g)throw new Error("Required GB Feature is unavailable");return}n.has(p)||(n.add(p),o.set(p,f),a.push(()=>{for(let S of f.rules??[]){m(S);for(let A of S.tracks??[])m(A.experiment)}}))}function I(p){let g=Object.hasOwn(t.experiments,p)?t.experiments[p]:void 0;if(!g)throw new Error("Required GB Experiment is unavailable");r.has(p)||(r.add(p),s.set(p,g),a.push(()=>m(g)))}for(let p of e.graph.nodes){p.type==="feature"&&w(p.featureKey,!0),p.type==="split"&&I(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&w(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&w(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}var ie=require("zod");function ff(e,t){let n=[],r={};Lt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Lt(e,o=>{if(o.type==="plan_picker"&&o.id===i.bind?.picker&&a.push(...o.planIds??[]),o.type==="stack"&&o.interaction?.type==="select"&&o.interaction.pickerId===i.bind?.picker)for(let s of o.children)s.type==="stack"&&s.bind?.plan&&a.push(s.bind.plan)}),a.length||n.push(`Quantity control ${i.id} needs a Product binding`);for(let o of new Set(a)){let s=t[o]?.prepaid?.find(u=>u.internalFeatureId===i.internalFeatureId)?.terms,c=r[o]??(r[o]=new Set);(!s||c.has(i.internalFeatureId)||i.minimumQuantity<s.minimumQuantity||i.maximumQuantity>s.maximumQuantity)&&n.push(`Quantity control ${i.id} must match its Product's prepaid Feature and bounds`),c.add(i.internalFeatureId)}});for(let[i,a]of Object.entries(t))for(let o of a.prepaid??[])r[i]?.has(o.internalFeatureId)||n.push(`Product ${i} needs a quantity control for ${o.internalFeatureId}`);return n}function gf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Lt(e,o=>{if(o.hidden)return!1;if(o.type!=="quantity_picker"||o.hidden||(o.bind?.plan??(o.bind?.picker?n[o.bind.picker]:void 0))!==t)return;let c=i.prepaid?.find(d=>d.internalFeatureId===o.internalFeatureId)?.terms,u=n[o.id];if(!c||typeof u!="number"||!Number.isSafeInteger(u)||u<Math.max(c.minimumQuantity,o.minimumQuantity)||u>Math.min(c.maximumQuantity,o.maximumQuantity)||(u-o.minimumQuantity)%o.step!==0||a[o.internalFeatureId]!==void 0)throw new Error("Choose a valid quantity for each prepaid Feature");a[o.internalFeatureId]=u}),(i.prepaid??[]).some(o=>a[o.internalFeatureId]===void 0))throw new Error("Choose a quantity for each prepaid Feature");return a}var Ai=require("zod");var hf=Ai.z.object({defaultLocale:An,locales:Ai.z.record(An,Ai.z.object({name:Ai.z.string().max(80),description:Ai.z.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 Nx=["customer_data","coupon_code"],Dx=ie.z.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),Af=ie.z.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),La=(e,t)=>new Set(e.map(t)).size===e.length,Fx=ie.z.strictObject({currency:he,amountMinor:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Mx=ie.z.strictObject({featureId:ie.z.uuid(),name:ie.z.string().trim().min(1).max(120),allowance:ie.z.string().max(40).nullable(),access:ie.z.boolean()}),qx=ie.z.strictObject({stripe:ie.z.strictObject({prices:ie.z.array(Fx).min(1).max(50)}).optional(),apple:ie.z.strictObject({productIds:ie.z.array(Dx).min(1).max(10)}).optional(),google:ie.z.strictObject({products:ie.z.array(ie.z.strictObject({productId:Af,basePlanId:Af.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!La(e.stripe.prices,n=>n.currency)||e.apple&&!La(e.apple.productIds,n=>n)||e.google&&!La(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Vx=ie.z.strictObject({name:ie.z.string().trim().min(1).max(80),interval:ie.z.enum(["free","week","month","year","one_time"]),intervalCount:ie.z.number().int().min(1).max(100),trial:ie.z.strictObject({days:ie.z.number().int().min(1).max(730),cardRequired:ie.z.boolean()}).nullable(),benefits:ie.z.array(Mx).max(50).refine(e=>La(e,t=>t.featureId),"Duplicate benefit"),channels:qx,prepaid:ie.z.array(Hi).max(100).optional()}),Bx=ie.z.strictObject({digest:pi,content:ie.z.strictObject({discount:Wn,duration:tn,appliesTo:Gs,displayCopy:hf.nullable(),firstPurchaseOnly:ie.z.boolean(),qualificationRequired:ie.z.boolean(),startsAt:ie.z.iso.datetime().nullable(),endsAt:ie.z.iso.datetime().nullable(),grantWindowHours:ie.z.number().int().positive(),perCustomerLimit:ie.z.number().int().positive()})}),Ux=ie.z.discriminatedUnion("type",[ie.z.strictObject({type:ie.z.literal("checkout"),product:xa}),ie.z.strictObject({type:ie.z.literal("close")}),ie.z.strictObject({type:ie.z.literal("action"),action:Ic})]),za=ie.z.strictObject({kind:ie.z.literal("paywall"),formatVersion:ie.z.literal(1),name:ie.z.string().trim().min(1).max(80),offeringVersionId:ie.z.uuid(),presentation:Bn,screen:rn,products:Sa,catalog:ie.z.record(ie.z.uuid(),Vx),buttons:ie.z.record(Te,Ux),coupons:ie.z.record(ie.z.uuid(),Bx)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;ff(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Cc(r,Nx).forEach(n),er(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Lt(r,g=>{let f="bind"in g?g.bind:void 0;f?.promotionCode&&n("Promotion codes must not be published"),f?.plan&&i.add(f.plan),f?.coupon&&a.add(f.coupon),g.type==="plan_picker"&&(g.planIds?.forEach(S=>i.add(S)),g.defaultPlan&&i.add(g.defaultPlan)),g.type==="text"&&g.feature&&o.add(g.feature.id)});let s=e.products.items.map(g=>g.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(g=>!Object.hasOwn(e.catalog,g)))&&n("Catalog must contain exactly the displayed Products");let u=new Set(s);e.products.defaultProductVersionId!==null&&!u.has(e.products.defaultProductVersionId)&&n("Default Product must be displayed");for(let g of i)u.has(g)||n("Screen references a Product that is not displayed");for(let g of Object.values(e.catalog))!g.channels.stripe&&!g.channels.apple&&!g.channels.google&&n("A displayed Product needs at least one sales channel");let d=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(f=>f.featureId)));for(let g of o)d.has(g)||n("Feature text must read a displayed benefit");let m=r.actions.filter(g=>g.type!=="navigate");r.actions.some(g=>g.type!=="event"&&g.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==m.length||m.some(g=>!Object.hasOwn(e.buttons,g.id)))&&n("Buttons must match the screen's actions");let I=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;I=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(S=>!u.has(S))&&n("Checkout may only sell displayed Products")}I||n("A Paywall needs a checkout button");let p=Object.keys(e.coupons);(p.length!==a.size||p.some(g=>!a.has(g)))&&n("Coupons must be exactly the bound Coupons")}),yf=ie.z.strictObject({state:ie.z.enum(["published","archived"]),controlRevision:ie.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ie.z.uuid(),versions:ie.z.record(ie.z.uuid(),ie.z.strictObject({version:ie.z.number().int().positive(),artifact:ie.z.string().min(1),sourceDigest:ie.z.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Zt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},Wc=Oe.z.string().regex(/^[a-f0-9]{64}$/),Yc=Oe.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Xc=ze.extend({environmentId:Oe.z.uuid()}),bf=Oe.z.strictObject({features:Oe.z.array(Oe.z.string()).max(500),experiments:Oe.z.record(Oe.z.uuid(),Oe.z.array(Oe.z.string()).max(20)),savedGroups:Oe.z.array(Oe.z.string()).max(1e3)}),eu=Oe.z.strictObject({kind:Oe.z.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Oe.z.number().int().positive(),url:Oe.z.string().min(1).max(2048),sha256:Wc,byteLength:Oe.z.number().int().positive().max(Zt.maxArtifactBytes),generation:Wc.optional()}),Lx=Oe.z.strictObject({state:Oe.z.enum(["active","paused","archived"]),controlRevision:Yc,evaluationMode:Oe.z.enum(["local","remote"]),evaluationRevision:Yc,currentVersionId:Oe.z.uuid(),versions:Oe.z.record(Oe.z.uuid(),Oe.z.strictObject({artifact:Oe.z.string(),dependencies:bf,definitionDigest:pi.optional(),couponDigests:Oe.z.record(Oe.z.uuid(),pi).optional()}))}),tu=Oe.z.strictObject({kind:Oe.z.literal("sdk_configuration"),schemaVersion:Oe.z.literal(1),scope:Xc,revision:Yc,generation:Wc,policy:Oe.z.strictObject({refreshIntervalSeconds:Oe.z.number().positive().max(15),maxControlAgeSeconds:Oe.z.number().positive().max(60)}),gb:Oe.z.strictObject({features:Oe.z.string().nullable(),pageExperiments:Oe.z.string().nullable()}),artifacts:Oe.z.record(Oe.z.string(),eu),funnels:Oe.z.record(Oe.z.uuid(),Lx),paywalls:Oe.z.record(Oe.z.uuid(),yf).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 It(e){if(Array.isArray(e))return`[${e.map(It).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)}:${It(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function nu(e){return Qr(Jr(typeof e=="string"?new TextEncoder().encode(e):e))}function Sf(e){return nu(It(e))}function xf(e,t){for(let o of Object.values(e.references))if(o.type==="flag"&&(!Object.hasOwn(t.features,o.key)||t.remoteFeatures.includes(o.key))||o.type==="experiment"&&!Object.hasOwn(t.experiments,o.id)||o.type==="saved_group"&&!Object.hasOwn(t.savedGroups,o.id))throw new Error("Funnel dependency is absent from GB public delivery");let n=Ua(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),r=new Set(t.remoteFeatures);for(let o of e.graph.nodes){let s=o.type==="feature"?o.featureKey:o.type==="end"&&o.output?.type==="feature"?o.output.featureKey:o.type==="output"&&o.value.type==="feature"?o.value.featureKey:void 0;if(!s)continue;let c=n.features[s],u=o.type==="feature"?e.variables[o.writes.value]:e.outputSchema;if(!c||!u)throw new Error("Required public Feature declaration is unavailable");if([c.defaultValue,...(c.rules??[]).flatMap(m=>[...Object.hasOwn(m,"force")?[m.force]:[],...m.variations??[],...(m.tracks??[]).flatMap(w=>w.experiment.variations)])].some(m=>m===void 0||!dn(u,m)))throw new Error("GB Feature values violate the Funnel type contract")}let i=new Set,a=o=>{for(let s of Mn(o)){if(i.has(s))continue;let c=t.savedGroups[s];if(!c)throw new Error("Required public Saved Group is unavailable");i.add(s),!Array.isArray(c)&&c.type==="condition"&&a(c.condition)}};for(let o of e.graph.nodes)if(o.type==="condition")for(let s of o.cases)a(s.condition);for(let o of Object.values(n.features))for(let s of o.rules??[]){a(s.condition);for(let c of[...s.parentConditions??[],...(s.tracks??[]).flatMap(u=>u.experiment.parentConditions??[])]){if(r.has(c.id)||!t.features[c.id])throw new Error("Local Funnel requires public Local prerequisites");a(c.condition)}for(let c of s.tracks??[])a(c.experiment.condition)}for(let o of Object.values(n.experiments)){a(o.condition);for(let s of o.parentConditions??[]){if(r.has(s.id)||!t.features[s.id])throw new Error("Local Funnel requires public Local prerequisites");a(s.condition)}}for(let o of e.graph.nodes)if(o.type==="split"){let s=n.experiments[o.experimentId];if(!s)throw new Error("Local Funnel requires a public Experiment");for(let c=0;c<s.variations.length;c++){let u=s.meta?.[c]?.key??String(c);if(!o.routes[u])throw new Error("Experiment variation has no declared Funnel route")}}return bf.parse({features:Object.keys(n.features).sort(),experiments:Object.fromEntries(Object.entries(n.experiments).map(([o,s])=>[o,s.variations.map((c,u)=>s.meta?.[u]?.key??String(u))])),savedGroups:[...i].sort()})}function If(e){return hi.parse(e)}var vf=ht.z.strictObject({...oi,selector:ht.z.discriminatedUnion("type",[ht.z.strictObject({type:ht.z.literal("paywall"),paywallId:ht.z.uuid()}),ht.z.strictObject({type:ht.z.literal("version"),versionId:ht.z.uuid()})]),customerId:ht.z.uuid().optional(),commerce:ei,locale:ht.z.string().min(1).max(35),requirement:Yn.optional()}),uo=ht.z.strictObject({id:ht.z.uuid(),paywallId:ht.z.uuid(),version:ht.z.number().int().positive(),document:di.omit({requirement:!0,offeringId:!0}),offering:ht.z.strictObject({id:ht.z.uuid()}),content:ht.z.strictObject({environmentId:ht.z.uuid(),offeringVersionId:ht.z.uuid(),artifact:eu.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:ti,check:kr.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"})}),Vr=ht.z.strictObject(uo.shape).omit({document:!0,offering:!0}).extend({content:uo.shape.content.unwrap()});function wf(e,t){let n=za.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 o=r.plans[i],s=a.channels.stripe?.prices.find(c=>c.currency===o?.currency);o&&s&&Object.assign(o,{amountMinor:s.amountMinor,interval:a.interval,intervalCount:a.intervalCount,...a.prepaid?.length?{prepaid:a.prepaid}:{}})}return uo.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}})}var Dt=require("zod");var Of={requestId:Dt.z.uuid(),sourceId:Dt.z.uuid(),expectedAvailable:Ut},_f=Dt.z.discriminatedUnion("action",[Dt.z.strictObject({...Of,action:Dt.z.enum(["add","subtract","set_remaining"]),amount:ge}),Dt.z.strictObject({...Of,action:Dt.z.literal("edit"),granted:ge,expiresAt:Dt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Dt.z.iso.datetime({offset:!0}).nullable(),expectedRevision:Dt.z.number().int().nonnegative()})]),ru=Dt.z.strictObject({sourceId:Dt.z.uuid(),available:Ut,held:Ut,spent:Ut,adjustmentGrantId:Dt.z.uuid().nullable()}),Cf=ru.extend({granted:Ut,expiresAt:Dt.z.iso.datetime({offset:!0}).nullable(),nextResetAt:Dt.z.iso.datetime({offset:!0}).nullable(),revision:Dt.z.number().int().nonnegative()});var Wt=require("zod"),Pf=Wt.z.discriminatedUnion("action",[Wt.z.object({action:Wt.z.literal("upsert"),externalId:Wt.z.string().min(1).max(128),name:Wt.z.string().trim().min(1).max(80)}).strict(),Wt.z.object({action:Wt.z.literal("archive"),entityId:Wt.z.uuid()}).strict()]),Ef=Wt.z.object({id:Wt.z.uuid(),externalId:Wt.z.string().min(1).max(128),name:Wt.z.string().min(1).max(80),archived:Wt.z.boolean()}).strict();var jt=require("zod");var ar=require("zod"),kf=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Rf=ar.z.string().regex(/.+\/.+/),iu=ar.z.number().min(-100),Br=ar.z.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),zx=ar.z.strictObject({input:Br,output:Br,cache_read:Br.optional(),cache_write:Br.optional(),reasoning:Br.optional(),input_audio:Br.optional(),output_audio:Br.optional()}),ou=(e,t)=>ar.z.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),GP=ar.z.strictObject({defaultMarkup:iu,providerMarkups:ou(ar.z.string().min(1),iu),modelMarkups:ou(Rf,iu),customModels:ou(Rf,zx.partial())});var pe=require("zod"),Ur=pe.z.iso.datetime({offset:!0}),sr=pe.z.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),$x=pe.z.discriminatedUnion("kind",[pe.z.object({kind:pe.z.literal("absolute"),from:Ur,to:Ur}).strict(),pe.z.object({kind:pe.z.literal("last_days"),days:pe.z.union([pe.z.literal(1),pe.z.literal(7),pe.z.literal(30),pe.z.literal(90)])}).strict(),pe.z.object({kind:pe.z.literal("billing_cycles"),membershipId:pe.z.uuid(),count:pe.z.number().int().min(1).max(12),includeCurrent:pe.z.boolean()}).strict()]),jf=pe.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"),Gx=pe.z.object({key:pe.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:pe.z.array(pe.z.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Lr=pe.z.object({range:$x,timezone:jf,filterBy:pe.z.array(Gx).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:pe.z.enum(["hour","day","week","month"]),internal_feature_id:pe.z.uuid().nullable(),entityId:pe.z.uuid().nullable(),topN:pe.z.number().int().min(1).max(50).nullable(),groupBy:pe.z.union([pe.z.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),pe.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:pe.z.object({bucket:Ur,group:pe.z.string().max(240),isOther:pe.z.boolean(),internal_feature_id:pe.z.uuid(),resourceId:pe.z.uuid()}).strict().nullable(),limit:pe.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)"})}),Tf=pe.z.object({from:Ur,to:Ur,interval:pe.z.enum(["hour","day","week","month"]),timezone:jf,rows:pe.z.array(pe.z.object({bucket:Ur,group:pe.z.string().max(240),isOther:pe.z.boolean(),internal_feature_id:pe.z.uuid(),resourceId:pe.z.uuid(),consumedUnits:sr,refundedUnits:sr,reservedUnits:sr,charged:sr,refunded:sr,reserved:sr,netUnits:sr,netCharged:sr}).strict()).max(100),nextCursor:pe.z.object({bucket:Ur,group:pe.z.string().max(240),isOther:pe.z.boolean(),internal_feature_id:pe.z.uuid(),resourceId:pe.z.uuid()}).strict().nullable()}).strict();var yi=jt.z.string().regex(/^(0|[1-9]\d{0,29})$/),Nf=jt.z.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),au=jt.z.strictObject({bucket:jt.z.iso.datetime({offset:!0}),group:jt.z.string().max(240),isOther:jt.z.boolean(),internal_feature_id:jt.z.uuid()}),Df=jt.z.strictObject({...Lr.shape,groupBy:jt.z.union([jt.z.enum(["customer","entity","entitlement"]),jt.z.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:au.nullable()}).superRefine((e,t)=>{let n=Lr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Ff=jt.z.strictObject({from:jt.z.iso.datetime({offset:!0}),to:jt.z.iso.datetime({offset:!0}),interval:Lr.shape.interval,timezone:Lr.shape.timezone,rows:jt.z.array(jt.z.strictObject({...au.shape,eventCount:yi,units:Nf,tokenEventCount:yi,tokens:jt.z.strictObject(Object.fromEntries(kf.map(e=>[e,yi]))),totalTokens:yi,providerCostEventCount:yi,providerCostUsd:Nf,invalidTelemetryEventCount:yi})).max(100),nextCursor:au.nullable()});var ut=require("zod");var Mf=ut.z.object({requestId:ut.z.uuid(),items:ut.z.array(ut.z.object({customerId:ut.z.uuid(),command:Ui.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"),qf=ut.z.object({batchId:ut.z.uuid(),after:ut.z.number().int().min(-1).max(999),limit:ut.z.number().int().min(1).max(100)}).strict(),Vf=ut.z.object({batchId:ut.z.uuid(),status:ut.z.enum(["queued","complete"]),total:ut.z.number().int().min(1).max(1e3),processed:ut.z.number().int().min(0).max(1e3),items:ut.z.array(ut.z.object({position:ut.z.number().int().min(0).max(999),customerId:ut.z.uuid(),idempotencyKey:ut.z.string().min(1).max(120),status:ut.z.enum(["queued","accepted","rejected","failed"]),receipt:Li.nullable(),errorCode:ut.z.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:ut.z.number().int().min(0).max(999).nullable()}).strict();var E=require("zod");var Kx=E.z.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Bf=E.z.enum(["draft","active","paused","archived"]),Uf=E.z.string().min(1).max(256),Lf=E.z.array(Uf).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Hx=E.z.strictObject({duration:E.z.enum(["day","week","month","year"]),length:E.z.number().int().min(1).max(3660)}),Qx=E.z.strictObject({internal_feature_id:E.z.uuid(),allowance:E.z.number().nonnegative().max(1e15).nullable(),expiry:Hx.nullable()}),Jx=E.z.discriminatedUnion("type",[E.z.strictObject({type:E.z.literal("feature_grant"),grants:E.z.array(Qx).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),E.z.strictObject({type:E.z.literal("free_product"),productId:Uf,duration:tn}),E.z.strictObject({type:E.z.literal("invoice_credits"),amount:E.z.number().positive().max(1e8),duration:tn,rollover:E.z.boolean(),productIds:Lf})]),Zx=E.z.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),zf=E.z.object({key:Zx,name:E.z.string().trim().min(1).max(80),configuration:Jx}).strict(),$f=E.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),su=E.z.object({code:$f,maxUses:E.z.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:E.z.boolean()}).strict(),Gf=E.z.object({key:E.z.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:E.z.string().trim().min(1).max(80),rewardId:E.z.uuid(),redeemOn:E.z.enum(["customer_creation","checkout"]),receivedBy:E.z.enum(["referrer","all"]),maxRedemptions:E.z.number().int().min(1).max(1e6).nullable(),productIds:Lf,excludeTrial:E.z.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Kf={id:E.z.uuid(),projectId:E.z.uuid(),environmentId:E.z.uuid(),revision:E.z.number().int().nonnegative(),status:Bf,createdAt:E.z.iso.datetime({offset:!0}),updatedAt:E.z.iso.datetime({offset:!0})},Wx=zf.extend(Kf).strict(),Yx=Gf.safeExtend(Kf).strict(),tE=E.z.strictObject({id:E.z.uuid(),key:E.z.string(),name:E.z.string(),type:Kx,status:Bf}),nE=E.z.discriminatedUnion("action",[E.z.object({action:E.z.literal("save"),id:E.z.uuid().nullable(),revision:E.z.number().int().nonnegative(),input:zf}).strict(),E.z.object({action:E.z.enum(["activate","pause","resume","archive","delete"]),id:E.z.uuid(),revision:E.z.number().int().nonnegative()}).strict()]),rE=E.z.discriminatedUnion("action",[E.z.object({action:E.z.literal("save"),id:E.z.uuid().nullable(),revision:E.z.number().int().nonnegative(),input:Gf}).strict(),E.z.object({action:E.z.enum(["activate","pause","resume","archive","delete"]),id:E.z.uuid(),revision:E.z.number().int().nonnegative()}).strict()]),Hf=E.z.object({id:E.z.uuid(),rewardId:E.z.uuid(),programId:E.z.uuid().nullable(),customerId:E.z.uuid(),referrerId:E.z.uuid().nullable(),status:E.z.enum(["pending","applied","unavailable"]),result:E.z.record(E.z.string(),E.z.unknown()).nullable(),createdAt:E.z.iso.datetime({offset:!0})}).strict(),Qf=E.z.object({code:$f,requestId:E.z.uuid()}).strict(),Jf=E.z.strictObject({redemptionId:E.z.uuid(),currency:he,requestId:E.z.uuid(),accepted:E.z.literal(!0)}),Xx=E.z.strictObject({type:E.z.literal("checkout"),orderId:E.z.uuid(),productVersionId:E.z.uuid(),currency:he,duration:tn,renewalAmountMinor:E.z.number().int().positive().max(1e8),status:E.z.enum(["created","pending","trialing","paid","cancelled","failed"]),url:E.z.url().nullable()}),Zf=E.z.discriminatedUnion("type",[Xx,E.z.strictObject({type:E.z.literal("subscription"),operationId:E.z.uuid(),membershipId:E.z.uuid(),productVersionId:E.z.uuid(),currency:he,duration:tn,renewalAmountMinor:E.z.number().int().positive().max(1e8),status:E.z.enum(["pending","running","applied","failed"])})]),Wf=E.z.object({programId:E.z.uuid(),requestId:E.z.uuid()}).strict(),Yf=E.z.object({id:E.z.uuid(),programId:E.z.uuid(),code:su.shape.code,createdAt:E.z.iso.datetime({offset:!0})}).strict(),iE=E.z.object({rows:E.z.array(Wx).max(100),nextCursor:E.z.uuid().nullable()}).strict(),oE=E.z.object({rows:E.z.array(Yx).max(100),nextCursor:E.z.uuid().nullable()}).strict(),e0=su.extend({id:E.z.uuid(),redemptions:E.z.number().int().nonnegative()}).strict(),t0=E.z.strictObject({id:E.z.uuid(),programId:E.z.uuid().nullable(),customerId:E.z.uuid().nullable(),referrerId:E.z.uuid().nullable(),code:E.z.string().nullable(),status:E.z.enum(["pending","triggered","applied"]),createdAt:E.z.iso.datetime({offset:!0})}),aE=E.z.object({codes:E.z.array(e0).max(100),redemptions:E.z.array(t0).max(100),customers:E.z.record(E.z.uuid(),E.z.string()),codesCursor:E.z.uuid().nullable(),redemptionsCursor:E.z.uuid().nullable()}).strict(),sE=E.z.discriminatedUnion("action",[E.z.object({action:E.z.literal("create"),rewardId:E.z.uuid(),revision:E.z.number().int().nonnegative(),input:su}).strict(),E.z.object({action:E.z.literal("remove"),rewardId:E.z.uuid(),revision:E.z.number().int().nonnegative(),codeId:E.z.uuid()}).strict()]);var x=require("zod");var Z=require("zod"),En={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},lo=e=>new Set(e).size===e.length,cu=Z.z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),n0=Z.z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),po=Z.z.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"))),r0=Z.z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Xf=Z.z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var eg=Z.z.strictObject({id:Z.z.uuid(),repo:n0,platform:Z.z.enum(["github","gitlab","bitbucket"]),branches:Z.z.array(po).min(1).max(4).refine(lo),workflow:Z.z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.z.array(Z.z.uuid()).min(1).max(4).refine(lo),include:Z.z.array(Xf).min(1).max(16),exclude:Z.z.array(Xf).max(16),methods:Z.z.array(Z.z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(lo),maxAgeHours:Z.z.number().int().min(1).max(720)}),tg=eg.extend({revision:Z.z.number().int().positive()}),uE=Z.z.strictObject({repository:eg,expectedRevision:Z.z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),ng=Z.z.strictObject({repositoryId:Z.z.uuid(),branch:po}),i0=Z.z.array(cu).max(En.keys).refine(lo),rg=Z.z.strictObject({repository:tg.omit({keyIds:!0}),branch:po,keys:i0,keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/)}),o0=Z.z.strictObject({filePath:r0,startingLineNumber:Z.z.number().int().min(1).max(1e7)}),uu=Z.z.strictObject({protocol:Z.z.literal(1),repositoryId:Z.z.uuid(),branch:po,workflow:Z.z.string().max(200),configurationRevision:Z.z.number().int().positive(),keySetHash:Z.z.string().regex(/^[a-f0-9]{64}$/),commit:Z.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.z.uuid(),runNumber:Z.z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.z.number().int().min(1).max(1e4),scannerVersion:Z.z.literal("1"),scannedAt:Z.z.iso.datetime({offset:!0}),coverage:Z.z.strictObject({complete:Z.z.literal(!0),files:Z.z.number().int().min(0).max(En.files),sourceBytes:Z.z.number().int().min(0).max(En.sourceBytes),unresolvedCalls:Z.z.number().int().min(0).max(1e6),unsupportedFiles:Z.z.number().int().min(0).max(En.files)}),features:Z.z.array(Z.z.strictObject({key:cu,refs:Z.z.array(o0).max(En.referencesPerKey)})).max(En.keys)}).superRefine((e,t)=>{lo(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)>En.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),lu=Z.z.strictObject({scanId:Z.z.uuid(),commit:Z.z.string(),receivedAt:Z.z.string(),references:Z.z.number().int().nonnegative(),removedReferences:Z.z.number().int().nonnegative()}),a0=lu.extend({repositoryId:Z.z.uuid(),branch:po,workflow:Z.z.string(),digest:Z.z.string(),configurationRevision:Z.z.number().int().positive(),runNumber:Z.z.number().int().positive(),runAttempt:Z.z.number().int().positive(),scannedAt:Z.z.string(),keySetHash:Z.z.string(),coverage:uu.shape.coverage}),s0=Z.z.strictObject({repositories:Z.z.array(tg).max(En.repositories),scans:Z.z.array(a0).max(En.repositories*En.branches)}),c0=Z.z.strictObject({key:cu,references:Z.z.number().int().nonnegative(),coveredTargets:Z.z.number().int().nonnegative(),expiredTargets:Z.z.number().int().nonnegative(),uncertainTargets:Z.z.number().int().nonnegative()}),lE=Z.z.strictObject({available:Z.z.boolean().default(!0),settings:s0,expectedTargets:Z.z.number().int().min(0).max(80),features:Z.z.array(c0).max(2001),truncated:Z.z.boolean()});var At=require("zod");var u0=At.z.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"]),l0=At.z.strictObject({provider:At.z.literal("stripe"),accountId:At.z.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:At.z.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:u0,occurredAt:At.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:At.z.record(At.z.string(),At.z.unknown()).and(At.z.object({id:At.z.string().min(1).max(255),object:At.z.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:At.z.boolean()}))}),ig=At.z.union([l0,dl]),og=At.z.strictObject({id:At.z.uuid(),eventId:At.z.string().min(1).max(200),source:At.z.literal("merchant"),providerVerified:At.z.literal(!1),outcome:At.z.string().min(1).max(100)});var Ft=require("zod"),sg={customerId:Ft.z.uuid(),eventId:Ft.z.string().trim().min(1).max(200),grantId:Ft.z.uuid(),occurredAt:Ft.z.iso.datetime({offset:!0})},cg=Ft.z.strictObject({...sg,productVersionId:Ft.z.uuid(),subscriptionId:Ft.z.string().trim().min(1).max(255)}),ug=Ft.z.strictObject({...sg,merchandiseId:Ft.z.uuid()}),lg=Ft.z.union([cg,ug]),ag={id:Ft.z.uuid(),couponId:Ft.z.uuid(),status:Ft.z.literal("redeemed"),source:Ft.z.literal("merchant"),recordedAt:Ft.z.iso.datetime({offset:!0})},dg=Ft.z.union([cg.extend(ag),ug.extend(ag)]);var re=require("zod");var pg=Bp,d0=pg.extend({invoice_id:pg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),du=re.z.strictObject({name:re.z.string().trim().min(1).max(255),memo:re.z.string().max(1e4).nullable().optional(),footer:re.z.string().max(1e4).nullable().optional(),net_terms_days:re.z.number().int().positive().nullable().optional()}),p0=du.extend({id:re.z.string().min(1).max(255),created_at:re.z.number().nullable()}),mg=re.z.strictObject({items:re.z.array(p0).max(50),nextCursor:re.z.uuid().nullable()}),hE=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),values:du}),re.z.strictObject({action:re.z.literal("update"),id:re.z.string().min(1).max(255),values:du}),re.z.strictObject({action:re.z.literal("delete"),id:re.z.string().min(1).max(255)})]),fg=re.z.discriminatedUnion("action",[re.z.strictObject({action:re.z.literal("create"),requestId:re.z.uuid(),params:si}),re.z.strictObject({action:re.z.enum(["finalize","send","pay","void"]),requestId:re.z.uuid(),invoiceId:re.z.uuid()}),re.z.strictObject({action:re.z.literal("reissue"),requestId:re.z.uuid(),invoiceId:re.z.uuid(),params:d0})]),pu=re.z.strictObject({id:re.z.uuid(),customerId:re.z.uuid(),providerInvoiceId:re.z.string().nullable(),status:re.z.enum(["draft","open","paid","void","uncollectible"]),currency:re.z.string(),totalMinor:re.z.string().regex(/^-?\d+$/),paidMinor:re.z.string().regex(/^\d+$/),refundedMinor:re.z.string().regex(/^\d+$/),hostedInvoiceUrl:re.z.url().nullable(),createdAt:re.z.number(),collectionMethod:re.z.enum(["send_invoice","charge_automatically"]).nullable()}),gg=pu.extend({lines:re.z.array(re.z.strictObject({id:re.z.uuid(),description:re.z.string(),amountMinor:re.z.string().regex(/^-?\d+$/),netAmountMinor:re.z.string().regex(/^-?\d+$/),quantity:re.z.number().nullable(),periodStart:re.z.number().nullable(),periodEnd:re.z.number().nullable()})).max(1e3)}),bi=re.z.strictObject({taskId:re.z.uuid(),status:re.z.enum(["ready","running","done","dead"]),invoice:pu.nullable(),errorCode:re.z.string().nullable()}),hg=re.z.strictObject({items:re.z.array(pu).max(50),nextCursor:re.z.uuid().nullable(),operations:re.z.array(bi).max(50),operationsLimited:re.z.boolean()});var m0=x.z.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"]),Ag={scope:ze,permissions:x.z.array(m0),expiresAt:x.z.iso.datetime().nullable()},aR=x.z.discriminatedUnion("kind",[x.z.object({...Ag,kind:x.z.literal("server"),keyId:x.z.string().min(1)}),x.z.object({...Ag,kind:x.z.literal("customer"),customerId:x.z.string().min(1),identityKind:x.z.enum(["identified","guest"]),expiresAt:x.z.iso.datetime()})]),z=x.z.object({requestId:x.z.uuid(),scope:ze}).strict(),f0=Xm.safeExtend({fingerprint:ja.optional()}).strict(),g0=z.extend({customer:fi,created:x.z.boolean()});function yg(){return z.extend({offer:Di.nullable(),reason:Ad.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:sp,response:z.extend({message:x.z.object({messageId:x.z.uuid(),channel:Ki,acceptedAt:x.z.iso.datetime({offset:!0}),status:x.z.enum(["accepted","sending","completed","canceled"]),replayed:x.z.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:x.z.strictObject({messageId:x.z.uuid()}),response:z.extend({message:x.z.object({id:x.z.uuid(),channel:Ki,status:x.z.enum(["accepted","sending","completed","canceled"]),deliveries:x.z.array(x.z.object({id:x.z.uuid(),status:up,attempts:x.z.number().int().nonnegative(),receipts:x.z.array(x.z.object({kind:lp,occurredAt:x.z.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Qu,response:z.extend({installation:br})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Ju,response:z.extend({installation:br})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Oo,response:z.extend({installation:br})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:x.z.strictObject({channel:Ki}),response:z.extend({preference:ds})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:cp,response:z.extend({preference:ds})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:x.z.strictObject({cursor:x.z.uuid().optional()}),response:z.extend({templates:mg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),params:si}),response:z.extend({preview:pc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),requestId:x.z.uuid(),params:si}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:bi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:fg}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:z.extend({operation:bi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),taskId:x.z.uuid()}),response:z.extend({operation:bi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),cursor:x.z.uuid().optional()}),response:z.extend({invoices:hg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),invoiceId:x.z.uuid()}),response:z.extend({invoice:gg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:ng,response:z.extend({config:rg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:uu,response:z.extend({receipt:lu})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:x.z.strictObject({}),response:z.extend({payload:io})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:km,response:z.merge(Ia)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:jm,response:z.merge(Tm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),sourceId:x.z.uuid()}),response:z.extend({balance:Cf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:_f}),response:z.extend({balance:ru})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:x.z.strictObject({internal_feature_id:x.z.uuid(),customerId:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:z.extend({internal_feature_id:x.z.uuid(),config:_s,model_markups:Fo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),query:ta}),response:z.extend({usage:zi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:Yd}),response:z.extend({usage:zi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:Kd}),response:z.extend({grant:Js})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:Hd,response:z.extend({grants:Qd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:x.z.union(bm.options.map(e=>e.extend({customerId:x.z.uuid().optional(),customerToken:x.z.string().regex(Vt).optional()}))),response:z.extend({operation:Sm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:cm.extend({customerId:x.z.uuid().optional()}),response:z.extend({setup:Ac})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:um.extend({customerId:x.z.uuid().optional()}),response:z.extend({setup:Ac})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:om.safeExtend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:ga.extend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:ga.extend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:ga.extend({customerId:x.z.uuid()}),response:z.extend({batch:Xi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:x.z.discriminatedUnion("action",[ha.options[0].extend({customerId:x.z.uuid()}),ha.options[1].extend({customerId:x.z.uuid()}),ha.options[2].extend({customerId:x.z.uuid()})]),response:z.extend({trial:hc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:am.extend({customerId:x.z.uuid()}),response:z.extend({trial:hc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ba,response:z.extend({subscriptions:hm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ba,response:z.extend({purchases:Am})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:mm,response:z.extend({conflicts:ym})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:fm,response:z.extend({resolution:gm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:dm,response:z.extend({verification:pm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Wp.safeExtend({...oi,customerId:x.z.uuid().optional()}),response:z.extend({quote:ci})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:ig,response:z.extend({record:og})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional(),intent:x.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:ui})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional()}),response:z.extend({operation:ui})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:em.safeExtend({customerId:x.z.uuid().optional()}),response:z.extend({quote:nm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional(),intent:x.z.enum(["confirm","cancel"]).optional()}),response:z.extend({operation:mc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Dr.extend({customerId:x.z.uuid().optional()}),response:z.extend({operation:mc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:rm.safeExtend({customerId:x.z.uuid()}),response:z.extend({quote:fc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Dr.extend({customerId:x.z.uuid()}),response:z.extend({operation:fa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Dr.extend({customerId:x.z.uuid()}),response:z.extend({operation:fa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:kd,response:z.extend({controls:Hs})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:wd,response:z.extend({prepared:_d})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:Cd,response:z.extend({authorization:Wo})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Fd,response:z.extend({coupons:Md})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Pd,response:z.extend({authorization:Wo})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Nd,response:z.extend({invoices:Dd})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Td.extend({customerId:x.z.uuid()}),response:z.extend({operation:bi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:jd,response:z.extend({invoice:qi})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Rd}).strict(),response:z.extend({controls:Hs})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Pf}).strict(),response:z.extend({entity:Ef})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:x.z.strictObject({customerId:x.z.uuid().nullable(),query:Df}),response:z.extend({analytics:Ff})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:x.z.object({customerId:x.z.uuid().nullable(),query:Lr}).strict(),response:z.extend({analytics:Tf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Mf,response:z.extend({batchId:x.z.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:qf,response:z.extend({batch:Vf})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:fp.extend({customerId:x.z.string().min(1).optional()}),response:z.extend({check:kr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:x.z.strictObject({kind:nr,selector:x.z.discriminatedUnion("type",[x.z.strictObject({type:x.z.literal("resource"),id:x.z.uuid()}),x.z.strictObject({type:x.z.literal("version"),id:x.z.uuid()})]),customerId:x.z.string().min(1).optional()}),response:z.extend({content:uc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:vf,response:z.extend({paywall:Vr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:x.z.strictObject({...oi,selector:wm,customerId:x.z.string().min(1).optional(),commerce:ei,requirement:Yn.optional()}),response:z.extend({offering:Om,candidates:x.z.array(ec).max(20),availability:x.z.array(x.z.strictObject({productVersionId:x.z.uuid(),available:x.z.boolean(),reason:x.z.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:kr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),entityId:x.z.uuid().optional()}).strict(),response:z.extend({holdings:Xd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),query:tp}).strict(),response:z.extend({ledger:np})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Jd.extend({customerId:x.z.uuid().optional()}),response:z.extend({detail:Zd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Zs.safeExtend({customerId:x.z.uuid().optional()}),response:z.extend({statement:Wd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:x.z.object({customerId:x.z.uuid().optional(),command:Ui.options[0]}).strict(),response:z.extend({quote:zd})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),command:x.z.union([x.z.strictObject({eventName:x.z.string().min(1),quantity:ge.optional(),properties:St.optional(),entityId:x.z.uuid().optional(),idempotencyKey:x.z.string().min(1).max(120)}),x.z.strictObject({internal_feature_id:x.z.uuid(),quantity:ge.optional(),properties:St.optional(),entityId:x.z.uuid().optional(),idempotencyKey:x.z.string().min(1).max(120)})])}),response:z.extend({receipts:x.z.array(Li).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:x.z.object({customerId:x.z.uuid(),command:Ui.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:z.extend({receipt:Li})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:Qf,response:z.extend({redemption:Hf})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Wf,response:z.extend({referralCode:Yf})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:Jf,response:z.extend({checkout:Zf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:ip,response:z.extend({seats:Xs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:op,response:z.extend({seats:Xs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:f0,response:g0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Uc,response:z.extend({customer:fi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:nf,response:z.extend(rf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:tf,response:z.extend(ef.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:x.z.object({customerId:x.z.uuid()}).strict(),response:z.extend(Kn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:x.z.strictObject({}),response:z.extend(Kn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:x.z.strictObject({customerId:x.z.uuid(),sessionId:x.z.uuid().optional()}),response:z.extend({revoked:x.z.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:ja.optional()}),response:z.extend({customerId:x.z.uuid(),guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:x.z.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:z.extend(Kn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:x.z.strictObject({guestToken:x.z.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:x.z.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:x.z.uuid()}),response:z.extend({customer:fi,switched:x.z.boolean(),replayed:x.z.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:x.z.strictObject({code:x.z.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:x.z.uuid()}),response:yg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:x.z.object({}).strict(),response:z.extend({offers:x.z.array(Di)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:x.z.object({customerId:x.z.string().min(1).max(255).optional(),couponId:x.z.uuid(),...oi,requestId:x.z.uuid(),couponContentDigest:x.z.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:yg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:lg,response:z.extend({receipt:dg})}},sR={recordBillingEvent:O.recordBillingEvent,sendMessage:O.sendMessage,readMessage:O.readMessage,bindPushInstallation:O.bindPushInstallation,readPushInstallation:O.readPushInstallation,updatePushAddress:O.updatePushAddress,readMessagingPreference:O.readMessagingPreference,setMessagingPreference:O.setMessagingPreference,listInvoiceTemplates:O.listInvoiceTemplates,previewInvoice:O.previewInvoice,createInvoice:O.createInvoice,manageInvoice:O.manageInvoice,readInvoiceOperation:O.readInvoiceOperation,listInvoices:O.listInvoices,getInvoice:O.getInvoice,getCodeReferenceConfig:O.getCodeReferenceConfig,submitCodeReferences:O.submitCodeReferences,getFeatures:O.getFeatures,evaluateFeatures:O.evaluateFeatures,trackEvents:O.trackEvents,setupPayment:O.setupPayment,readPaymentSetup:O.readPaymentSetup,previewSubscriptionBatch:O.previewSubscriptionBatch,confirmSubscriptionBatch:O.confirmSubscriptionBatch,readSubscriptionBatch:O.readSubscriptionBatch,abandonSubscriptionBatch:O.abandonSubscriptionBatch,manageSubscriptionTrial:O.manageSubscriptionTrial,readSubscriptionTrial:O.readSubscriptionTrial,listSubscriptions:O.listSubscriptions,listPurchases:O.listPurchases,listSubscriptionConflicts:O.listSubscriptionConflicts,retrySubscriptionConflict:O.retrySubscriptionConflict,readAiPricing:O.readAiPricing,readUsage:O.readUsage,setUsage:O.setUsage,previewRefund:O.previewRefund,refund:O.refund,readRefund:O.readRefund,previewUpdate:O.previewUpdate,update:O.update,readSubscriptionUpdate:O.readSubscriptionUpdate,restoreNativePurchase:O.restoreNativePurchase,verifySubscriptions:O.verifySubscriptions,previewAttach:O.previewAttach,attach:O.attach,readSubscriptionOperation:O.readSubscriptionOperation,manageBalanceGrant:O.manageBalanceGrant,readBalanceSource:O.readBalanceSource,adjustBalance:O.adjustBalance,listBalanceGrants:O.listBalanceGrants,readBillingControls:O.readBillingControls,prepareBillingAuthorization:O.prepareBillingAuthorization,confirmBillingAuthorization:O.confirmBillingAuthorization,setBillingCoupons:O.setBillingCoupons,revokeBillingAuthorization:O.revokeBillingAuthorization,listBillingInvoices:O.listBillingInvoices,confirmBillingAdjustment:O.confirmBillingAdjustment,prepareBillingAdjustment:O.prepareBillingAdjustment,manageBillingLimits:O.manageBillingLimits,createCustomer:O.createCustomer,getCustomer:O.getCustomer,listCustomers:O.listCustomers,updateCustomer:O.updateCustomer,createSession:O.createSession,refreshSession:O.refreshSession,revokeSessions:O.revokeSessions,createGuestCustomer:O.createGuestCustomer,resumeGuestSession:O.resumeGuestSession,claimGuestCustomer:O.claimGuestCustomer,checkEntitlement:O.checkEntitlement,resolveOffering:O.resolveOffering,resolveContent:O.resolveContent,resolvePaywall:O.resolvePaywall,readHoldings:O.readHoldings,readLedger:O.readLedger,readBillingInvoice:O.readBillingInvoice,readCreditStatement:O.readCreditStatement,quoteBalance:O.quoteBalance,trackUsage:O.trackUsage,mutateBalance:O.mutateBalance,manageUsageEntity:O.manageUsageEntity,readUsageAnalytics:O.readUsageAnalytics,readCreditAnalytics:O.readCreditAnalytics,submitUsageBatch:O.submitUsageBatch,readUsageBatch:O.readUsageBatch,listOffers:O.listOffers,grantOffer:O.grantOffer,recordCouponRedemption:O.recordCouponRedemption,redeemCoupon:O.redeemCoupon,redeemReward:O.redeemReward,createReferralCode:O.createReferralCode,claimRewardProduct:O.claimRewardProduct,readSeats:O.readSeats,manageSeat:O.manageSeat};var $a=require("zod");var mo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function mu(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(d=>Qt(t.attributes??{},d.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new mo("Required GB Feature is unavailable");i=Fn(e.featureKey,t),o=i.value,Object.assign(r,ii(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new mo("Required GB Experiment is unavailable");if(a=Jo(u,t),o=a.value,s=a.inExperiment&&!a.passthrough&&typeof o=="string"?o:"notParticipating",c=s==="notParticipating"?e.notParticipating:e.routes[s],!c)throw new mo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Fn(e.configuration.featureKey,t).value;o={type:"offering_version",id:$a.z.uuid().parse(u)},Object.assign(r,ii(e,{value:o})),c=e.next;break}case"coupon":case"coupons":o=e.type==="coupons"?e.couponIds.map(u=>({type:"reward",id:u})):{type:"reward",id:e.couponId},Object.assign(r,ii(e,{value:o})),c=e.next;break}return{port:s,target:c,projections:r,...o===void 0?{}:{value:o},...i?{feature:i}:{},...a?{experiment:a}:{}}}function bg(e,t,n){$a.z.uuid().parse(e),$a.z.number().int().nonnegative().parse(t);let r=Qr(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)}`}var K=require("zod");var cr=K.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),h0=K.z.enum(["running","waiting","completed","closed","ineligible","failed"]),A0=K.z.discriminatedUnion("type",[Vc,K.z.strictObject({type:K.z.literal("wait"),receiptId:K.z.uuid(),kind:K.z.enum(["timer","event","operation"]),deadline:K.z.iso.datetime({offset:!0}).nullable(),eventName:cr.optional()}),K.z.strictObject({type:K.z.literal("open_url"),receiptId:K.z.uuid(),url:Lc,openIn:zc}),K.z.strictObject({type:K.z.literal("event"),receiptId:K.z.uuid(),event:cr})]),Ga=K.z.strictObject({type:K.z.literal("funnel"),id:K.z.uuid(),versionId:K.z.uuid()}),y0={id:cr,presentation:Bn,outputs:K.z.array(cr).max(250),inputs:_a,values:K.z.record(K.z.string(),Ae).optional(),offeringKey:ft.optional(),capabilities:ti,customerData:xp,dataCursors:K.z.record(cr,Oa.nullable())},b0=K.z.strictObject({...y0,content:K.z.strictObject({type:K.z.literal("document"),document:rn})}),fu=K.z.strictObject({id:K.z.uuid(),source:Ga,revision:K.z.number().int().nonnegative(),visit:K.z.number().int().nonnegative(),nodeId:cr,nodeType:K.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:h0,stopped:K.z.boolean(),canBack:K.z.boolean(),authenticated:K.z.boolean(),locale:K.z.string().min(1).max(35),answers:ir,parameters:or,variables:K.z.record(K.z.string(),Ae),output:Ae.nullable(),screen:b0.nullable(),paywall:K.z.strictObject({receiptId:K.z.uuid(),resolution:K.z.union([uo,Vr]),quote:ci.nullable(),operation:ui.nullable(),purchaseRequestId:K.z.uuid().nullable(),selectionGeneration:K.z.number().int().nonnegative().optional(),canReselect:K.z.boolean().optional()}).nullable(),instruction:A0.nullable(),pendingRequest:K.z.strictObject({requestId:K.z.uuid(),authenticationRequired:K.z.boolean()}).nullable(),runExpiresAt:K.z.iso.datetime({offset:!0}),credentialExpiresAt:K.z.iso.datetime({offset:!0}).nullable()}),fo=K.z.strictObject({scope:ze,run:fu,settlement:K.z.strictObject({requestId:K.z.uuid(),state:K.z.enum(["pending","unknown","settled"]),operationId:K.z.uuid().nullable(),receiptId:K.z.uuid().nullable().optional()}).optional(),purchase:K.z.strictObject({receiptId:K.z.uuid(),quote:ci.nullable(),operation:ui.nullable(),canReselect:K.z.boolean().optional()}).optional(),review:K.z.strictObject({activeOperationId:K.z.uuid().nullable(),pages:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),nodeId:cr,visit:K.z.number().int().nonnegative()})).max(100),page:K.z.strictObject({receiptId:K.z.uuid(),nodeId:cr,visit:K.z.number().int().nonnegative(),document:rn,answers:ir,inputs:_a,values:K.z.record(K.z.string(),Ae).optional()}).nullable(),coupons:K.z.array(K.z.strictObject({grantId:K.z.uuid(),status:K.z.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:K.z.string().nullable()})).max(100),purchases:K.z.array(K.z.strictObject({receiptId:K.z.uuid(),operationId:K.z.uuid(),status:K.z.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:K.z.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:K.z.uuid().optional()}),Sg=fo.extend({run:fu.extend({paywall:fu.shape.paywall.unwrap().extend({resolution:Vr}).nullable()})});var xg="X-Indiana-Server-Key";var Re=require("zod");var Si=Re.z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),vg=Re.z.strictObject({entry:Si,nodes:Re.z.array(Re.z.strictObject({id:Si,type:Re.z.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Re.z.record(Re.z.string(),Si),writes:Re.z.record(ft,ft),resources:Re.z.strictObject({screenId:Si.optional(),paywallVersionId:Re.z.uuid().optional(),couponId:Re.z.uuid().optional(),couponIds:Re.z.array(Re.z.uuid()).max(20).optional(),experimentId:Re.z.uuid().optional(),featureKey:Re.z.string().optional(),offeringVersionId:Re.z.uuid().optional()})})).min(1).max(500)}),Ig={scope:ze,funnelId:Re.z.uuid(),versionId:Re.z.uuid(),evaluationRevision:Re.z.number().int().nonnegative(),expiresAt:Re.z.iso.datetime({offset:!0}).nullable(),topology:vg},Ka=Re.z.discriminatedUnion("evaluationMode",[Re.z.strictObject({...Ig,evaluationMode:Re.z.literal("local"),growth:pn,conditions:Re.z.record(Si,Re.z.array(Re.z.strictObject({condition:Ht,port:Re.z.string()})))}),Re.z.strictObject({...Ig,evaluationMode:Re.z.literal("remote")})]),S0=Ka.options[0].extend({evaluation:Re.z.strictObject({maxTransitions:Re.z.number().int().min(1).max(1e4),variables:Re.z.record(ft,ri),outputSchema:ni,terminals:Re.z.record(Si,Re.z.strictObject({outcome:Re.z.enum(["completed","closed","ineligible","failed"]),output:ao.nullable()}))})});function x0(e){return vg.parse({entry:e.graph.entry,nodes:e.graph.nodes.map(t=>{let n={},r={};switch(t.type){case"entry":case"feature":case"offering":case"coupon":case"coupons":n.next=t.next;break;case"screen":Object.assign(n,t.outputs),r.screenId=t.screenId;{let a=e.screens.find(o=>o.id===t.screenId);a?.type==="paywall"&&(r.paywallVersionId=a.paywallVersionId)}break;case"condition":t.cases.forEach((a,o)=>{n[`case:${o}`]=a.target}),n.default=t.default;break;case"split":Object.assign(n,t.routes),n.notParticipating=t.notParticipating,r.experimentId=t.experimentId;break;case"action":for(let a of["success","cancel","unavailable","failure"])n[a]=t[a];t.action.type==="claim_offer"&&t.action.coupon.source==="literal"&&t.action.coupon.value&&typeof t.action.coupon.value=="object"&&!Array.isArray(t.action.coupon.value)&&(r.couponId=Re.z.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 gu(e){let t=hi.parse(e.document),n=e.evaluationMode==="local"?pn.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:x0(t)};return Ka.parse(e.evaluationMode==="remote"?r:{...r,growth:Ua(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function wg(e){let t=gu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=hi.parse(e.document);return S0.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}]]}))}})}var Ye=require("zod");var Og=Ye.z.string().regex(/^[a-f0-9]{64}$/),I0=mi.omit({variations:!0,active:!0}).extend({changeId:Og,variations:Ye.z.array(Ye.z.strictObject({urlRedirect:Ye.z.string().max(2048)})).min(2).max(20)}),_g=Ye.z.strictObject({environmentId:Ye.z.uuid(),trackExposures:Ye.z.boolean(),generation:Og,experiments:Ye.z.array(I0).max(100),savedGroups:ro}),v0=Ye.z.strictObject({eventUuid:Ye.z.uuid(),timestamp:Ye.z.iso.datetime({offset:!0}).optional(),deviceId:Ye.z.string().min(1).max(128),sessionId:Ye.z.string().min(1).max(128).optional(),url:Ye.z.url().max(2048),pageTitle:Ye.z.string().max(512).optional(),experimentKey:Ye.z.string().min(1).max(255),variationKey:Ye.z.string().min(1).max(64)}),qR=Ye.z.strictObject({events:Ye.z.array(v0).min(1).max(20)}),VR=Ye.z.strictObject({inserted:Ye.z.number().int().nonnegative(),duplicates:Ye.z.number().int().nonnegative(),skipped:Ye.z.number().int().nonnegative(),rejected:Ye.z.array(Ye.z.strictObject({index:Ye.z.number().int().nonnegative(),reason:Ye.z.string()}))});var yt=require("zod");var w0=yt.z.strictObject({selector:yt.z.string().min(1).max(2048),action:yt.z.enum(["set","append","remove"]),attribute:yt.z.string().min(1).max(128).refine(e=>["html","class","style","position","href","src","alt","title","id","role","hidden"].includes(e)||/^(aria|data)-[a-z0-9_-]+$/.test(e)),value:yt.z.string().max(5e4).optional(),parentSelector:yt.z.string().max(2048).optional(),insertBeforeSelector:yt.z.string().max(2048).optional()}),O0=yt.z.strictObject({variation:yt.z.string().min(1).max(128),description:yt.z.string().max(2e3).default(""),css:yt.z.string().max(1e5).default(""),js:yt.z.string().max(1e5).default(""),domMutations:yt.z.array(w0).max(200).default([]),iam:Vm.optional(),renderGuard:va.optional()}),hu=O0.omit({variation:!0,description:!0,iam:!0}),_0=mi.omit({variations:!0,active:!0}).extend({changeId:yt.z.string().regex(/^[a-f0-9]{64}$/),variations:yt.z.tuple([hu,hu]).rest(hu).refine(e=>e.length<=20)}),Cg=yt.z.strictObject({trackExposures:yt.z.boolean(),environmentId:yt.z.uuid(),generation:yt.z.string().regex(/^[a-f0-9]{64}$/),experiments:yt.z.array(_0).max(100),savedGroups:ro});var nt=require("zod");var yu=32,C0=522240;function bu(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 P0=nt.z.strictObject({nodeId:nt.z.string().min(1).max(64),visit:nt.z.number().int().nonnegative(),revision:nt.z.number().int().nonnegative()}),Au=nt.z.record(nt.z.string(),Ae),E0=nt.z.strictObject({id:nt.z.uuid(),nodeId:nt.z.string().min(1).max(64),visit:nt.z.number().int().nonnegative(),input:nt.z.strictObject({schemaVersion:so.shape.schemaVersion,kind:so.shape.kind,selector:so.shape.selector,contract:so.shape.contract}),context:Au,removed:nt.z.array(nt.z.string()).max(100),attributes:Au,removedAttributes:nt.z.array(nt.z.string()).max(100),result:df,offeringVersionId:nt.z.uuid().nullable(),events:nt.z.strictObject({entered:nt.z.string().regex(/^[1-9][0-9]{0,18}$/),decision:nt.z.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),QR=nt.z.strictObject({schemaVersion:nt.z.literal(1),mode:nt.z.enum(["local","remote"]),versionId:nt.z.uuid(),generation:nt.z.number().int().positive(),base:P0,context:Au,steps:nt.z.array(E0).min(1).max(yu)}).refine(e=>on(e)<=C0,"Segment exceeds its byte budget");var Su=class extends Error{constructor(n,r){super(r);Le(this,"code",n);this.name="FunnelLocalCalculationError"}},Pg=(e,t)=>new Su(e,t),R0=e=>({experiments:e.experiments,features:e.features});function k0(e,t=Pg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Zr(e.growth.savedGroups),i=R0(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Fn(o,s).value}return{nodes:n,savedGroups:r,features:i.features,feature:a,evaluate(o,s){let c=n.get(o);if(!c)throw t("NOT_FOUND","Funnel node is unavailable");let u,d;if(c.type==="condition"){let w=e.conditions[c.id];if(!w)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=mu({id:c.id,name:c.id,type:"condition",cases:w.map(I=>({condition:I.condition,target:c.outputs[I.port]})),default:c.outputs.default},s,i.experiments).port}else if(c.type==="feature"){if(!c.resources.featureKey)throw t("INVALID_RESPONSE","Feature reference is unavailable");d=a(c.resources.featureKey,s),u="next"}else if(c.type==="split"){if(!(c.resources.experimentId?e.growth.experiments[c.resources.experimentId]:void 0))throw t("INVALID_RESPONSE","Experiment reference is unavailable");let I=mu({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);d=I.value,u=I.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)d=a(c.resources.featureKey,s),u=c.type==="offering"?"next":"value";else throw t("SERVER_REQUIRED","This node is driven by the authoritative Funnel runtime");let m=c.outputs[u]??(u==="value"?c.id:void 0);if(!m)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:m,...d===void 0?{}:{value:d}}}}}function j0(e,t){let n=Ka.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=k0(n,t);return(o,s)=>(i(),T0(a,o,s))}function T0(e,t,n){let r=xt.parse(n.attributes??{}),{saveStickyBucketAssignmentDoc:i,onFeatureUsage:a,onExperimentViewed:o}=n,s={attributes:r,...i?{saveStickyBucketAssignmentDoc:c=>i(structuredClone(c))}:{},...a?{onFeatureUsage:(c,u)=>a(c,structuredClone(u))}:{},...o?{onExperimentViewed:(c,u)=>o(structuredClone(c),structuredClone(u))}:{},features:e.features,savedGroups:e.savedGroups,...n.stickyBucketAssignmentDocs?{stickyBucketAssignmentDocs:structuredClone(n.stickyBucketAssignmentDocs)}:{}};return e.evaluate(t,s)}function N0(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(m=>m.next.attributeName===s.attributeName&&m.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,d={expected:n.sticky[u]??null,next:s};c<0?r.push(d):r[c]=d},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(Ae.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(Ae.parse({feature:s,value:c.value,source:c.source,...c.ruleId?{ruleId:c.ruleId}:{}}))}});return{port:o.port,...o.value===void 0?{}:{value:o.value},sticky:r,exposures:i,features:a}}function Eg(e,t,n,r=Pg){let i=n,a=new Map(t.graph.nodes.map(g=>[g.id,g])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,d=n.visit,m=!1,w,I=g=>(w??(w=j0(e,r)),N0(w,g,{attributes:Nc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<yu;g++){let f=a.get(u);if(!f||!bu(f))break;if(d>=t.execution.maxTransitions&&(d>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let S,A;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")S=I(f.id),f.type==="offering"&&(S.value={type:"offering_version",id:String(S.value)}),f.type==="condition"?A=S.port==="default"?f.default:f.cases[Number(S.port.slice(5))]?.target:f.type==="split"?A=S.port==="notParticipating"?f.notParticipating:f.routes[S.port]:(f.type==="feature"||f.type==="offering")&&(A=f.next);else if(S={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(A=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(S.value={type:"offering_version",id:f.configuration.versionId},A=f.next),f.type==="end"||f.type==="output"){let v=f.type==="end"?f.output:f.value;if(S=v?.type==="feature"?I(f.id):{...S,port:"value",value:v?.type==="literal"?v.value:v?.type==="variable"?ac({source:"variable",key:v.key,...v.path?{path:v.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},v&&(S.value===void 0||!dn(t.outputSchema,S.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:S}];if(on({steps:P})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:S}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let v=f.type==="coupons"?f.couponIds.map(N=>({type:"reward",id:N})):f.type==="coupon"?{type:"reward",id:f.couponId}:S.value;if(v===void 0)throw r("INVALID_RESPONSE","Node output is missing");let k=ii(f,{value:v});Cp(t.variables,f,k),Object.assign(o,k)}for(let v of S.sticky)s[`${v.next.attributeName}||${v.next.attributeValue}`]=structuredClone(v.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!A)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=A,d++}let p=a.get(u);return{steps:c,...!m&&p&&!bu(p)?{boundary:{nodeId:u,visit:d}}:{}}}var be=require("zod");var Ha=be.z.string().regex(/^[a-f0-9]{64}$/),D0=be.z.strictObject({release:Ha,render:va,button:be.z.strictObject({selector:be.z.string().min(1).max(512),elementKey:be.z.string().min(1).max(256),tag:be.z.enum(["button","a","input"])}).nullable()}),dk=be.z.strictObject({scope:ze.extend({environmentId:be.z.uuid()}),release:Ha,validatedAt:be.z.iso.datetime({offset:!0}),validUntil:be.z.iso.datetime({offset:!0}),entries:be.z.array(be.z.strictObject({id:be.z.uuid(),funnelId:be.z.uuid(),versionId:be.z.uuid(),event:be.z.enum(["screen_enter","button_click"]),target:D0})).max(4e3)}),pk=be.z.strictObject({operation:be.z.literal("entry_start"),funnelId:be.z.uuid(),versionId:be.z.uuid(),entryId:be.z.uuid(),release:Ha,requestId:be.z.uuid(),locale:be.z.string().min(1).max(35).default("en")}),mk=be.z.strictObject({scope:ze,suppressed:be.z.literal(!0),reason:be.z.enum(["frequency","in_progress"]),retryAt:be.z.iso.datetime({offset:!0}).nullable()}),fk=be.z.strictObject({experimentId:be.z.uuid(),splitNodeId:be.z.string().min(1).max(128)}),F0=be.z.strictObject({experimentId:be.z.uuid(),experimentKey:be.z.string().min(1).max(128),variationKey:be.z.string().min(1).max(128),inExperiment:be.z.boolean(),generation:be.z.string().min(1).max(256)}),Rg=be.z.strictObject({operation:be.z.literal("page_experiments"),release:Ha,usedReceiptIds:be.z.array(be.z.uuid()).max(20).default([]),customerToken:be.z.string().regex(Vt).optional()}),kg=be.z.strictObject({scope:ze,runId:be.z.uuid(),assignments:be.z.array(F0.extend({receiptId:be.z.uuid()})).max(20),payload:Cg});var y=class extends Error{constructor(n,r,i,a,o){super(r);Le(this,"code",n);Le(this,"status",i);Le(this,"requestId",a);Le(this,"retryable");Le(this,"recovery");Le(this,"retryAfterSeconds");Le(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=_o(n,i??0,{...o,retryAfter:o?.retryAfterSeconds===void 0?void 0:String(o.retryAfterSeconds)});this.retryable=s.retryable,this.recovery=s.recovery,this.retryAfterSeconds=s.retryAfterSeconds}};var go=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new y("INVALID_STATE","Installation sequence exhausted");return e+1},M0=async e=>[...new Uint8Array(await crypto.subtle.digest("SHA-256",Uint8Array.from(e,t=>t.charCodeAt(0))))].map(t=>t.toString(16).padStart(2,"0")).join("");function Ln(e,t){return e.transaction(n=>{if(!Number.isSafeInteger(n.identitySeq)||n.identitySeq<0||!Number.isSafeInteger(n.addressSeq)||n.addressSeq<0||n.detachSeq!==null&&(!Number.isSafeInteger(n.detachSeq)||n.detachSeq<1||n.detachSeq>n.identitySeq))throw new y("INVALID_STATE","Installation journal is invalid");return t({...n})})}function jg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||ze.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new y("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new y("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=A=>{if(A!==i)throw new y("IDENTITY_CHANGED","Identity changed during Push operation")};async function d(A){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new y("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let v=P.sha256?await P.sha256(Uint8Array.from(A,k=>k.charCodeAt(0))):await M0(A);if(!/^[a-f0-9]{64}$/.test(v))throw new y("INVALID_STATE","Push credential digest is invalid");return v}function m(A){let P=br.parse(A);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new y("INVALID_RESPONSE","Push response belongs to another installation");return P}async function w(A,P){let v=c(),k={installationId:v.installationId,publicKey:v.publicKey,issuedAt:new Date().toISOString(),...P},N=await v.sign(Xu(A,v.scope,k));return{...k,signature:N}}let I=(A,P,v)=>t.requestWithCredential?t.requestWithCredential(A,P,v):t.request(A,P);async function p(){let A=c(),P=i,v=r?await(t.session?.access()??r):null,k=Ln(A,ve=>ve),N;if(k.detachSeq!==null){let ve=k.detachSeq,Me=Zu.parse(await w("detach",{sequence:ve,platform:A.platform}));try{let ke=await t.request("push/installations/detach",{...A.scope,...Me},"POST",{installationDetach:!0});if(!ke||typeof ke!="object"||!("installation"in ke))throw new y("INVALID_RESPONSE","Push detach acknowledgement is invalid");let zt=m(ke.installation);if(zt.bound||zt.identitySeq!==ve)throw new y("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(ke){if(ke instanceof y&&ke.status===404)N=ke;else if(!(ke instanceof y)||ke.status!==412)throw ke}N||Ln(A,ke=>({...ke,detachSeq:ke.detachSeq===ve?null:ke.detachSeq}))}if(u(P),!v){if(N)throw N;return null}let B=O.bindPushInstallation,fe=B.request.parse(await w("bind",{sequence:o,platform:A.platform,credentialDigest:await d(v)}));u(P);let Ie=B.response.parse(await I(B.path,fe,v));u(P);let Ce=m(Ie.installation);if(!Ce.bound||Ce.identitySeq!==o)throw new y("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return N&&k.detachSeq!==null&&o>k.detachSeq&&Ln(A,ve=>({...ve,detachSeq:ve.detachSeq===k.detachSeq?null:ve.detachSeq})),Ce}async function g(){c();let A=i,P=r?await(t.session?.access()??r):null;if(!P)throw new y("NOT_IDENTIFIED","Identify before reading this installation");let v=O.readPushInstallation,k=v.request.parse(await w("read",{credentialDigest:await d(P)}));u(A);let N=v.response.parse(await I(v.path,k,P));return u(A),m(N.installation)}function f(A=p){let P=s.catch(()=>{}).then(A);return s=P,P.catch(v=>{try{e?.onError?.(v instanceof Error?v:new Error("Push synchronization failed"))}catch{}}),P}async function S(A,P,v){let k=c(),N=P.identity,B=P.observation,fe=r?await(t.session?.access()??r):null;if(u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");if(!fe)throw new y("NOT_IDENTIFIED","Identify before recovering a Push address");if(!A.connectionId||!A.kind||!A.token||!["granted","provisional"].includes(A.permission))throw new y("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await f(async()=>{if(u(N),await p(),u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let Ie=Ln(k,zt=>v?zt:{...zt,addressSeq:go(zt.addressSeq)}),ve=await w(v?"recovery_confirm":"recovery_request",{...A,sequence:Ie.addressSeq,credentialDigest:await d(fe),...v?{challenge:v}:{}}),Me=v?Yu.parse(ve):Wu.parse(ve);if(u(N),B!==a)throw new y("INVALID_STATE","Push observation changed during recovery");let ke=await I(`push/installations/recovery/${v?"confirm":"request"}`,Me,fe);if(u(N),B!==a||Ln(k,zt=>zt).addressSeq!==Ie.addressSeq)throw new y("INVALID_STATE","Push observation changed during recovery");if(v){let zt=O.updatePushAddress.response.parse(ke),Xe=m(zt.installation);if(!Xe.bound||Xe.identitySeq!==o||Xe.addressSeq!==Ie.addressSeq||Xe.connectionId!==A.connectionId||Xe.addressStatus!=="active")throw new y("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Xe}if(!ke||typeof ke!="object"||!("recovery"in ke))throw new y("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return ls.parse(ke.recovery)})}return{recoveryObserver(){c();let A={identity:i,observation:++a};return{async request(P){return ls.parse(await S(P,A))},async confirm(P,v){return br.parse(await S(v,A,P))}}},identify(A){if(!e)return;o=Ln(e,v=>({...v,identitySeq:go(v.identitySeq)})).identitySeq,r=A,i++,a++},reset(){if(e)try{Ln(e,A=>{let P=go(A.identitySeq);return{...A,identitySeq:P,detachSeq:P}})}finally{r=null,i++,a++}},start(){e&&f()},async sync(){return await f()},read:g,async recover(){let A=c(),P=i,v=o;return a++,await f(async()=>{u(P);let k=await g();return u(P),o=Ln(A,B=>{if(B.identitySeq!==v)throw new y("IDENTITY_CHANGED","A newer installation intent exists");return{...B,identitySeq:go(Math.max(B.identitySeq,k.identitySeq)),addressSeq:Math.max(B.addressSeq,k.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let A=++a,P=i;return async v=>{if(A!==a||P!==i)return null;let k=c(),N=r?await(t.session?.access()??r):null;if(!N)throw new y("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),A!==a)return null;let B=Ln(k,ve=>({...ve,addressSeq:go(ve.addressSeq)})),fe=O.updatePushAddress,Ie=fe.request.parse(await w("address",{...v,sequence:B.addressSeq,credentialDigest:await d(N)}));if(u(P),A!==a)return null;let Ce=fe.response.parse(await I(fe.path,Ie,N));return u(P),m(Ce.installation)}}}}function Tg(e,t){return{messaging:{async preference(n){let r=O.readMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({channel:n}))).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse(n))).preference}},push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){let n=O.readMessagingPreference;return n.response.parse(await e(n.path,{channel:"push"})).preference},async setPreference(n){let r=O.setMessagingPreference;return r.response.parse(await e(r.path,r.request.parse({...n,channel:"push"}))).preference}}}}var Ng={name:"@tinkerlandai/indiana-sdk",version:"0.10.2",description:"Framework-independent Longplay SDK for customer identity, entitlements, credits, offers and growth surfaces.",license:"UNLICENSED",repository:{type:"git",url:"git+https://github.com/tinkerlandai/Indiana.git",directory:"packages/sdk"},engines:{node:">=22"},publishConfig:{access:"public",tag:"beta"},type:"module",sideEffects:!1,files:["dist","README.md","README.zh-CN.md","CHANGELOG.md","THIRD_PARTY_NOTICES.md"],exports:{"./react-native":{types:"./dist/react-native.d.ts","react-native":"./dist/react-native.js",import:"./dist/react-native.js",default:"./dist/react-native.js"},".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./popup":{types:"./dist/popup.d.ts",import:"./dist/popup.js"},"./server":{types:"./dist/server.d.ts",import:"./dist/server.js"},"./openrouter":{types:"./dist/openrouter.d.ts",import:"./dist/openrouter.js"},"./native-shell":{types:"./dist/native-shell.d.ts",import:"./dist/native-shell.js"},"./page":{types:"./dist/page.d.ts",import:"./dist/page.js"},"./visual":{types:"./dist/visual.d.ts",import:"./dist/visual.js"}},scripts:{build:"tsup",prepack:"pnpm run build",typecheck:"tsc --noEmit",lint:"node ../../scripts/ci/lint.mjs --workspace packages/sdk"},dependencies:{"@ai-sdk/provider":"4.0.26","@types/json-schema":"7.0.15","css-tree":"^3.2.1","dom-mutator":"0.7.0",dompurify:"^3.4.15",zod:"4.6.6"},devDependencies:{"@indiana/contracts":"workspace:*","@openrouter/sdk":"^1.4.25","@types/css-tree":"^3.2.0",ai:"7.0.136",tsup:"^8.5.1",typescript:"^5.9.3","whatwg-url-minimum":"0.2.0"},peerDependencies:{"@openrouter/sdk":"^1.4.25"},peerDependenciesMeta:{"@openrouter/sdk":{optional:!0}}};function Ge(e){return typeof e=="string"?e:String(e)}var V0=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function B0(e){return e.replace(V0,"$1\uFFFD")}function wu(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 zg(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 Dg(e){let t;if(Array.isArray(e)){let n=e.map(Ge);if(n.length===2)return n}else if((t=zg(e))!=null){let n=wu(t.next()),r=wu(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 Fg="0123456789ABCDEF",U0=/(?:%[0-9A-Fa-f]{2})+/g;function Rn(e){return`%${Fg[e>>4&15]}${Fg[15&e]}`}function $g(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Rn(e):String.fromCharCode(e):e<=2047?Rn(192|e>>6)+Rn(128|63&e):e<=65535?Rn(224|e>>12)+Rn(128|e>>6&63)+Rn(128|63&e):Rn(240|e>>18)+Rn(128|e>>12&63)+Rn(128|e>>6&63)+Rn(128|63&e)}function Ou(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function _u(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(U0,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function yo(e){return e<=31||e>126}function L0(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return yo(e)}}function Tu(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return yo(e)}}function z0(e){return Tu(e)||e===39}function Cu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return Tu(e)}}function Ya(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 Cu(e)}}function Mg(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 Ya(n)}})(e)}}function Gg(e,t){return $g(e=e||0,t)}function kn(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),o=a;if(a>=55296&&a<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343&&(o=(a-55296<<10)+s-56320+65536,r++)}i+=$g(o,t,n)}return i}function Nu(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([_u(i.slice(0,a),!0),_u(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Pu(e){let t="";for(let n=0;n<e.length;n++){let r=kn(e[n][0],Mg,!0),i=kn(e[n][1],Mg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var $0=[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],G0=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],K0=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],H0=[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 Q0(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[J0,Z0,W0,qg]=[[[],"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 Y0(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 Kg(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function ho(e,t){let[n,r,i]=e,a=t>>8;for(let c=0;c<n.length;c+=2)if(a>=n[c]&&a<=n[c+1])return!0;let o=r.indexOf(a);if(o<0)return!1;let s=255&t;return!!(i[32*o+(s>>3)]&1<<(7&s))}function X0(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&&Kg(H0,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&ho(qg,t[i]);)i--;let a=n+1;for(;a<t.length&&ho(qg,t[a]);)a++;if(!(i>=0&&a<t.length&&ho(Z0,t[i])&&ho(W0,t[a])))return!1}return!0}var eI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,tI=/\p{Script=Latin}/u;function nI(e){return!eI.test(e)||!tI.test(e)}var ur=36,Ja=1,Eu=26,rI=38,iI=700,oI=72,aI=128,sI=2147483647;function Vg(e){return String.fromCharCode(e+22+75*+(e<26))}function cI(e,t,n){let r=0;for(e=n?Math.floor(e/iI):e>>1,e+=Math.floor(e/t);e>(ur-Ja)*Eu>>1;r+=ur)e=Math.floor(e/(ur-Ja));return Math.floor(r+(ur-Ja+1)*e/(e+rI))}function uI(e){let t=Array.from(e,c=>c.codePointAt(0)),n="",r=0;for(let c=0;c<t.length;c++){let u=t[c];u<128&&(n+=String.fromCharCode(u),r++)}let i=r;i&&(n+="-");let a=aI,o=0,s=oI;for(;r<t.length;){let c=sI;for(let u=0;u<t.length;u++){let d=t[u];d>=a&&d<c&&(c=d)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let d=t[u];if(d<a&&o++,d===a){let m=o;for(let w=ur;;w+=ur){let I=w<=s?Ja:w>=s+Eu?Eu:w-s;if(m<I)break;n+=Vg(I+(m-I)%(ur-I)),m=Math.floor((m-I)/(ur-I))}n+=Vg(m),s=cI(o,r+1,r===i),o=0,r++}}o++,a++}return n}function xu(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=Ou(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Bg(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function Hg(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function Qg(e){return e.length===2&&Hg(e.codePointAt(0),e.codePointAt(1))}function Ug(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function lt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function Jg(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Ru(e,t){if(e[0]==="[")return e[e.length-1]==="]"?(function(r){let i=[0,0,0,0,0,0,0,0],a=null,o=0,s=0,c=Array.from(r,u=>u.codePointAt(0));if(c[s]===58){if(c[s+1]!==58)return null;s+=2,o++,a=o}for(;s<c.length;){if(o===8)return null;if(c[s]===58){if(a!==null)return null;s++,o++,a=o;continue}let u=0,d=0,m=0;for(;m<4&&(u=Ou(c[s]))>=0;)d=(d<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let w=0;for(;c[s]!==void 0;){let I=0;if(w>0)if(c[s]===46&&w<4)s++;else return null;if(c[s]==null||c[s]<48||c[s]>57)return null;for(;c[s]>=48&&c[s]<=57;){if(I=10*I+Ou(c[s]),I>255)return null;s++}i[o]=256*i[o]+I,w++,w%2==0&&o++}if(w!==4)return null;break}else if(c[s]===58){if(c[++s]===void 0)return null}else if(c[s]!==void 0)return null;i[o]=d,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let d=i[a+u-1];i[a+u-1]=i[o],i[o]=d,o--,u--}}else if(a===null&&o!==8)return null;return i})(e.substring(1,e.length-1)):null;if(t)return(function(r){return Ug(r)?null:kn(r,yo)})(e);{let n=(function(i){let a=!1,o=!1;for(let c=0;c<i.length;c++){let u=i.charCodeAt(c);if(u<=32||u===37||u===127)return null;if(u>=128){a=!0;break}u>=65&&u<=90&&(o=!0)}if(!a)return i!==""?o?i.toLowerCase():i:null;if((function(u){for(let d of u){let m=d.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(d)&&!Kg($0,m)||ho(J0,m))return!0}return!1})(i))return null;let s=(i=(function(u){let d="";for(let m of u){let w=m.codePointAt(0);if(w!==8204&&w!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let I=Y0(m,w);if(I){d+=I;continue}let p=G0.indexOf(w);d+=p<0?m:K0[p]}return d})(i).normalize("NFKC").replace(/[\u3002\uff0e\uff61]/g,".").toLowerCase()).split(".");for(let c=0;c<s.length;c++){let u=s[c];if(u==="")continue;let d=/[^\0-\x7f]/.test(u);if(Q0(u)||d&&(/^\p{Mark}/u.test(u)||!X0(u)||!nI(u)||u.startsWith("xn--")))return null;d&&(s[c]=`xn--${uI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:_u(e));return n===null||Ug(n)?null:(function(i){let a=i.length,o=i.lastIndexOf(".",a-2)+1;if(i.charCodeAt(a-1)===46&&a--,a<=o)return!1;if(xu(i.slice(o,a))>=0)return!0;for(;o<a;o++){let s=i.charCodeAt(o);if(s<48||s>57)return!1}return!0})(n)?(function(i){let a=i.split("."),o=a.length;if(a[o-1]||o--,o>4)return null;let s=0;for(let u=0;u<o-1;u++){let d=xu(a[u]);if(d<0||d>255)return null;s+=d*(1<<8*(3-u))}let c=xu(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function ku(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(s){let c=-1,u=-1,d=1,m=0;for(let w=0;w<s.length;++w)s[w]!==0?(m>d&&(c=u,d=m),u=-1,m=0):(u===-1&&(u=w),++m);return m>d?u:c})(n),i="",a=!1;for(let o=0;o<=7;++o)if(!(a&&n[o]===0)){if(a&&(a=!1),r===o){i+=o===0?"::":":",a=!0;continue}i+=n[o].toString(16),o!==7&&(i+=":")}return i})(e)}]`:e}function Zg(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 Wg(e){return e.username!==""||e.password!==""}function Iu(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,q="",xe="",Be=null,V,Za=!1,Wa=!1,zr=!1,dt;function un(e,t,n,r){t||(e=(function(o){let s=0,c=o.length;for(;s<c&&!(o.charCodeAt(s)>32);++s);for(;c>s&&!(o.charCodeAt(c-1)>32);--c);return o.substring(s,c)})(e)),e=(function(o){let s=0;for(;s<o.length;s++){let u=o.charCodeAt(s);if(u===9||u===10||u===13)break}if(s===o.length)return o;let c=o.slice(0,s);for(;s<o.length;s++){let u=o.charCodeAt(s);u!==9&&u!==10&&u!==13&&(c+=o[s])}return c})(e),C=0,q=e,xe="",Be=n||null,V=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Za=!1,Wa=!1,zr=!1,dt=r||0;let i=lI;switch(r){case 3:case 4:i=Xa;break;case 5:i=Fu;break;case 6:i=$r;break;case 7:i=lr;break;case 8:i=jn}return i(G(e,C))!==1?V:null}function X(e,t){return C+=C===e?vn(t):1,C<=q.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function vn(e){return e!=null&&e>65535?2:1}function Yg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var lI=e=>{let t=C;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=C+1;for(e=q.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=q.charCodeAt(n);return xe=q.slice(C,n).toLowerCase(),C=n,dI(n<q.length?e:void 0)}else return dt?1:(--C,X(t,e)?Xg(G(q,C)):0)},dI=e=>{let t=C;if(e===58){if(dt){if(lt(V.scheme)!==lt(xe))return 0;if((Wg(V)||V.port!==null)&&xe==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=xe,dt?(V.port===Jg(V.scheme)&&(V.port=null),0):(xe="",V.scheme==="file"?X(t,e)?Mu(G(q,C)):0:lt(V.scheme)&&Be!==null&&Be.scheme===V.scheme?X(t,e)?pI(G(q,C)):0:lt(V.scheme)?X(t,e)?fI(G(q,C)):0:G(q,C+1)===47?(C++,X(t,e)?mI(G(q,C)):0):(V.path=[""],V.opaquePath=!0,X(t,e)?th(G(q,C)):0))}else return dt?1:(xe="",C=-1,X(t,e)?Xg(G(q,C)):0)},Xg=e=>{let t=C;return Be===null||Be.opaquePath&&e!==35?1:Be.opaquePath&&e===35?(V.scheme=Be.scheme,V.path=Be.path.slice(),V.opaquePath=Be.opaquePath,V.query=Be.query,V.fragment="",X(t,e)?jn(G(q,C)):0):Be.scheme==="file"?(C--,X(t,e)?Mu(G(q,C)):0):(C--,X(t,e)?Du(G(q,C)):0)},pI=e=>{let t=C;return e===47&&G(q,C+1)===47?(++C,X(t,e)?ts(G(q,C)):0):(C--,X(t,e)?Du(G(q,C)):0)},mI=e=>{let t=C;return e===47?X(t,e)?xi(G(q,C)):0:(C--,X(t,e)?wn(G(q,C)):0)},Du=e=>{let t=C;return V.scheme=Be.scheme,e===47||lt(V.scheme)&&e===92?X(t,e)?Lg(G(q,C)):0:(V.username=Be.username,V.password=Be.password,V.host=Be.host,V.port=Be.port,V.path=Be.path.slice(),V.query=Be.query,e===63?(V.query="",X(t,e)?lr(G(q,C)):0):e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):e!=null?(V.query=null,V.path.pop(),C--,X(t,e)?wn(G(q,C)):0):X(t,e)?Du(G(q,C)):0)},Lg=e=>{let t=C;return lt(V.scheme)&&(e===47||e===92)?X(t,e)?ts(G(q,C)):0:e===47?X(t,e)?xi(G(q,C)):0:(V.username=Be.username,V.password=Be.password,V.host=Be.host,V.port=Be.port,C--,X(t,e)?wn(G(q,C)):0)},fI=e=>{let t=C;return e===47&&G(q,C+1)===47?C++:C--,X(t,e)?ts(G(q,C)):0},ts=e=>{let t=C;return e!==47&&e!==92?(C--,X(t,e)?xi(G(q,C)):0):X(t,e)?ts(G(q,C)):0},xi=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!lt(V.scheme))){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&lt(V.scheme))break;n+=vn(r)}return xe+=q.slice(C,n),C=n-1,X(t,e)?xi(G(q,C)):0}if(e===64){Za&&(xe=`%40${xe}`),Za=!0;for(let n=0;n<xe.length;n++){let r=xe.codePointAt(n);if(r===58&&!Wa){Wa=!0;continue}let i=Gg(r,Ya);Wa?V.password+=i:V.username+=i,r!=null&&r>65535&&n++}return xe="",X(t,e)?xi(G(q,C)):0}else return e==null||e===35||e===47||e===63||e===92&&lt(V.scheme)?Za&&xe===""?1:(C-=xe.length+1,xe="",X(t,e)?Xa(G(q,C)):0):(xe+=Yg(e),X(t,e)?xi(G(q,C)):0)},Xa=e=>{let t=C;if(dt&&V.scheme==="file")return C--,X(t,e)?qu(G(q,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!lt(V.scheme))){let n=C+vn(e);for(e===91?zr=!0:e===93&&(zr=!1);n<q.length;){let r=G(q,n);if(r==null||!zr&&r===58||r===35||r===47||r===63||r===92&&lt(V.scheme))break;r===91?zr=!0:r===93&&(zr=!1),n+=vn(r)}return xe+=q.slice(C,n),C=n-1,X(t,e)?Xa(G(q,C)):0}else if(e===58&&!zr){if(xe===""||dt===4)return 1;let n=Ru(xe,!lt(V.scheme));return n===null?1:(V.host=ku(n),xe="",X(t,e)?Fu(G(q,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&lt(V.scheme)){if(C--,lt(V.scheme)&&xe==="")return 1;if(dt&&xe===""&&(Wg(V)||V.port!==null))return 1;let n=Ru(xe,!lt(V.scheme));return n===null?1:(V.host=ku(n),xe="",dt?0:X(t,e)?$r(G(q,C)):0)}else return xe+=Yg(e),X(t,e)?Xa(G(q,C)):0},Fu=e=>{let t=C;if(e!=null&&e>=48&&e<=57){let n=C+1;for(;n<q.length;){let r=q.charCodeAt(n);if(r<48||r>57)break;n++}return xe+=q.slice(C,n),C=n-1,X(t,e)?Fu(G(q,C)):0}else if(dt||e==null||e===35||e===47||e===63||e===92&&lt(V.scheme)){if(xe!==""){let n=parseInt(xe,10);if(n>65535)return 1;if(V.port=n===Jg(V.scheme)?null:n,xe="",dt)return 0}return dt?1:(C--,X(t,e)?$r(G(q,C)):0)}else return 1};function eh(e,t){let n=e.length-t;if(n<2)return!1;if(Hg(G(e,t),G(e,t+1))){if(n===2)return!0;{let r=G(e,t+2);return r===47||r===92||r===63||r===35}}else return!1}var Mu=e=>{let t=C;return V.scheme="file",V.host="",e===47||e===92?X(t,e)?gI(G(q,C)):0:Be?.scheme==="file"?(V.host=Be.host,V.path=Be.path.slice(),V.opaquePath=Be.opaquePath,V.query=Be.query,e===63?(V.query="",X(t,e)?lr(G(q,C)):0):e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):e!=null?(V.query=null,eh(q,C)?V.path=[]:Zg(V),C--,X(t,e)?wn(G(q,C)):0):X(t,e)?Mu(G(q,C)):0):(C--,X(t,e)?wn(G(q,C)):0)},gI=e=>{let t=C;return e===47||e===92?X(t,e)?qu(G(q,C)):0:(Be!==null&&Be.scheme==="file"&&(!eh(q,C)&&(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})(Be.path[0])&&V.path.push(Be.path[0]),V.host=Be.host),C--,X(t,e)?wn(G(q,C)):0)},qu=e=>{let t=C;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=vn(r)}return xe+=q.slice(C,n),C=n-1,X(t,e)?qu(G(q,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!dt&&Qg(xe))return X(t,e)?wn(G(q,C)):0;if(xe==="")return V.host="",dt?0:X(t,e)?$r(G(q,C)):0;{let n=Ru(xe,!lt(V.scheme));return n===null?1:(n==="localhost"&&(n=""),V.host=ku(n),xe="",dt?0:X(t,e)?$r(G(q,C)):0)}}return 1},$r=e=>{let t=C;return lt(V.scheme)?(e!==92&&e!==47&&C--,X(t,e)?wn(G(q,C)):0):!dt&&e===63?(V.query="",X(t,e)?lr(G(q,C)):0):!dt&&e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):e!=null?(e!==47&&C--,X(t,e)?wn(G(q,C)):0):(dt&&V.host===null&&V.path.push(""),X(t,e)?$r(G(q,C)):0)},wn=e=>{let t=C;if(e!=null&&e!==47&&(!lt(V.scheme)||e!==92)&&(dt||e!==63&&e!==35)){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===47||lt(V.scheme)&&r===92||!dt&&(r===63||r===35))break;n+=vn(r)}xe+=kn(q.slice(C,n),Cu),C=n,e=G(q,n)}if(e==null||e===47||lt(V.scheme)&&e===92||!dt&&(e===63||e===35)){let n=lt(V.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}})(xe)?(Zg(V),e!==47&&!n&&V.path.push("")):Bg(xe)&&e!==47&&!n?V.path.push(""):Bg(xe)||(V.scheme==="file"&&V.path.length===0&&Qg(xe)&&(xe=`${xe[0]}:`),V.path.push(xe)),xe="",e===63?(V.query="",X(t,e)?lr(G(q,C)):0):e===35?(V.fragment="",X(t,e)?jn(G(q,C)):0):X(t,e)?wn(G(q,C)):0}else return xe+=Gg(e,Cu),X(t,e)?wn(G(q,C)):0},th=e=>{let t=C;if(e===63)return V.query="",X(t,e)?lr(G(q,C)):0;if(e===35)return V.fragment="",X(t,e)?jn(G(q,C)):0;if(e!=null){let n=C+vn(e);for(;n<q.length;){let i=G(q,n);if(i===63||i===35)break;n+=vn(i)}let r=q.slice(C,n);if(n<q.length&&r.charCodeAt(r.length-1)===32?V.path[0]+=kn(r.slice(0,-1),yo)+"%20":V.path[0]+=kn(r,yo),C=n,(e=G(q,n))===63)return V.query="",X(t,e)?lr(G(q,C)):0;if(e===35)return V.fragment="",X(t,e)?jn(G(q,C)):0}return X(t,e)?th(G(q,C)):0},lr=e=>{let t=C,n=C;if(e!=null){if(dt)n=q.length;else{let i=q.indexOf("#",C);n=i===-1?q.length:i}let r=lt(V.scheme)?z0:Tu;V.query+=kn(q.slice(C,n),r)}return C=n,G(q,n)===35&&!dt?(V.fragment="",X(t,e)?jn(G(q,C)):0):X(t,e)?lr(G(q,C)):0},jn=e=>{let t=C;return e!=null&&(V.fragment+=kn(q.slice(C),L0),C=q.length),X(t,e)?jn(G(q,C)):0};function ju(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function nh(e){switch(e.scheme){case"blob":{let t=un(ju(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":nh(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 $e=Symbol("URLImpl"),gn=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=un(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=un(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[$e]={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=un(n,null,null,0),r==null)?!1:un(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+=ju(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[$e].url)}set href(t){let n=un(t=Ge(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[$e].url=n,this[$e].query&&vu(this[$e].query,n.query)}get origin(){return nh(this[$e].url)}get protocol(){return`${this[$e].url.scheme}:`}set protocol(t){un(`${t=Ge(t)}:`,this[$e].url,null,2)}get username(){return this[$e].url.username}set username(t){t=Ge(t),Iu(this[$e].url)||(function(r,i){r.username=kn(i,Ya)})(this[$e].url,t)}get password(){return this[$e].url.password}set password(t){t=Ge(t),Iu(this[$e].url)||(function(r,i){r.password=kn(i,Ya)})(this[$e].url,t)}get host(){let{url:t}=this[$e];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Ge(t),this[$e].url.opaquePath||un(t,this[$e].url,null,3)}get hostname(){let{url:t}=this[$e];return t.host!=null?t.host:""}set hostname(t){t=Ge(t),this[$e].url.opaquePath||un(t,this[$e].url,null,4)}get port(){let{url:t}=this[$e];return t.port!=null?`${t.port}`:""}set port(t){t=Ge(t);let{url:n}=this[$e];Iu(n)||(t?un(t,n,null,5):n.port=null)}get pathname(){return ju(this[$e].url)}set pathname(t){t=Ge(t);let{url:n}=this[$e];n.opaquePath||(n.path=[],un(t,n,null,6))}get search(){let{url:t}=this[$e];return t.query?`?${t.query}`:""}set search(t){t=Ge(t);let{url:n,query:r}=this[$e];if(!t)n.query=null,r&&vu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",un(i,n,null,7),r&&vu(r,n.query)}}get searchParams(){let t=this[$e],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new es;return o[rt].url=i,o[rt].serialized=a==null,a&&(o[rt].list=Nu(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[$e];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Ge(t);let{url:n}=this[$e];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",un(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(gn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var rt=Symbol("URLSearchParamsImpl"),hI=Symbol.dispose||Symbol.for("dispose");function vu(e,t){t?e[rt].list=Nu(t):e[rt].list.length=0,e[rt].serialized=t==null}function Qa(e){if(e.url){let t=Pu(e.list);(function(r,i){r[$e].url.query=i})(e.url,t||null),e.serialized=!0}}var AI=typeof Iterator<"u"?Iterator:Object,Ao=class extends AI{constructor(t,n){super(),this[rt]={ptr:t,map:n,index:0}}next(){let t=this[rt];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}[hI](){}},es=class{constructor(t){let n=this[rt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Dg(t[i]));else if((r=zg(t))!=null){let i;for(;!(i=wu(r.next())).done;)n.list.push(Dg(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 o=i[a],s=B0(o),c=Ge(t[o]),u=n.list.find(d=>d[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Ge(t);i=i[0]==="?"?i.substring(1):i,n.list=Nu(i)}}get size(){return this[rt].list.length}append(t,n){t=Ge(t),n=Ge(n),this[rt].list.push([t,n]);let r=this[rt];r.url&&r.serialized?(function(a,o){let s=a[$e].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Pu([[t,n]])):Qa(r)}delete(t,n){t=Ge(t),n=n!=null?Ge(n):void 0;let{list:r}=this[rt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;Qa(this[rt])}get(t){t=Ge(t);let{list:n}=this[rt];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[rt];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[rt];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[rt],i=!1,a=!1,o=0;for(;o<r.length;)r[o][0]===t?i?(r.splice(o,1),a=!0):(i=!0,r[o][1]!==n&&(r[o][1]=n,a=!0),o++):o++;i||(r.push([t,n]),a=!0),a&&Qa(this[rt])}sort(){this[rt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),Qa(this[rt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[rt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new Ao(this[rt],t=>t)}keys(){return new Ao(this[rt],t=>t[0])}values(){return new Ao(this[rt],t=>t[1])}toString(){return Pu(this[rt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(es.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var dr="https://api.longplayai.com";function rh(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,w){let I=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}I===r&&(t=m,n=w,o())}let c=()=>s();function u(m,w=!1){let I=Kn.safeParse(m);if(!I.success||w&&Date.parse(I.data.expiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<=Date.now()||Date.parse(I.data.refreshExpiresAt)<Date.parse(I.data.expiresAt))throw new y("INVALID_RESPONSE","Invalid customer session credentials");return I.data}async function d(){if(i)return i;let m=t,w=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new y("UNAUTHENTICATED","Customer authentication is required",401);let I=(async()=>{try{let p=await e(m.refreshToken);if(w!==r)throw new y("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new y("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw w!==r?new y("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof y&&p.status===401&&c(),p)}})();i=I;try{return await I}finally{i===I&&(i=void 0)}}return{identify(m){let w=typeof m=="string"?void 0:u(m),I=typeof m=="string"?m:w.accessToken;if(!I.trim()||/\s/.test(I)||I.length>4096)throw new y("INVALID_TOKEN","A server-issued token is required");s(w,I)},reset:c,subscribeIdentity(m,w){return a.set(m,w),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return d().then(()=>{if(!n)throw new y("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new y("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:d}}var ih=Symbol("IndianaNoContent");function pr(e,t,n=gn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?ze.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??dr);if(o.username||o.password||o.search||o.hash)throw new y("INVALID_URL","baseUrl must not contain credentials, query, or fragment");if(o.protocol!=="https:"&&!(o.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(o.hostname)))throw new y("INVALID_URL","Use HTTPS, or HTTP on localhost during development");let s=e.fetch??globalThis.fetch.bind(globalThis),c=e.timeoutMs??1e4;if(!Number.isFinite(c)||c<1||c>12e4)throw new y("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,d=0,m=null,w=new Set,I=e.session??rh(async A=>{let P=await S("customer-sessions/refresh",{},"POST",{},A);if(!P||typeof P!="object")throw new y("INVALID_RESPONSE","Invalid refresh response");let{requestId:v,scope:k,...N}=P;return N});function p(){d+=1,u=null,m=null;for(let A of w)A.abort();w.clear()}let g=I.subscribeIdentity(p);function f(){I.reset()}async function S(A,P={},v="POST",k={},N){let B=k.installationDetach===!0;if(B&&(A!=="push/installations/detach"||v!=="POST"))throw new y("INVALID_REQUEST","Installation authority only detaches this installation");if(!N&&!u&&!B)throw new y("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let fe=d,Ie=new AbortController;B||w.add(Ie);let Ce=()=>!B&&fe!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new y("TIMEOUT","Longplay request timed out"),ve,Me=new Promise((Xe,Tt)=>{ve=()=>Tt(Ce()),Ie.signal.addEventListener("abort",ve,{once:!0})}),ke=setTimeout(()=>Ie.abort(),c),zt=async()=>{let Xe=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:v,headers:{"Content-Type":"application/json",...B?{}:{Authorization:`Bearer ${N??u}`},[gs]:hs.current,[il]:Ng.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:v==="POST"?JSON.stringify(P):void 0,signal:Ie.signal,credentials:"omit",cache:"no-store",redirect:"error",...k.keepalive?{keepalive:!0}:{}});if(Ie.signal.aborted)throw Ce();let Tt;try{Tt=Xe.status===204?ih:await Xe.json()}catch{throw Ie.signal.aborted?Ce():new y(Xe.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",Xe.status,Xe.headers.get("X-Request-Id")??void 0)}if(Ie.signal.aborted)throw Ce();if(!B&&fe!==d)throw new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!Xe.ok){let st=fs.safeParse(Tt),$t=st.success&&(!Nn.safeParse(st.data.error.code).success||nl(st.data.error.code,Xe.status)),gr=$t?st.data.error.code:"HTTP_ERROR",hr=_o(gr,Xe.status,{retryAfter:Xe.headers.get("Retry-After"),recovery:$t?st.data.error.recovery:void 0,reason:$t?st.data.error.reason:void 0});throw new y(gr,$t?st.data.error.message:"Longplay request failed",Xe.status,Xe.headers.get("X-Request-Id")??(st.success?st.data.requestId:void 0),{...hr,...st.success&&st.data.error.retryable===!1?{retryable:!1}:{},...hr.retryAfterSeconds===void 0&&st.success&&st.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:st.data.error.retryAfterSeconds}:{}})}if(Xe.headers.get(gs)!==hs.current)throw new y("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&Tt!==ih){let st=Tt&&typeof Tt=="object"&&"scope"in Tt?Tt:Tt&&typeof Tt=="object"&&"configuration"in Tt?Tt.configuration:null;if(!st||typeof st!="object"||!("scope"in st))throw new y("INVALID_RESPONSE","Response is missing its App/environment scope");let $t=ze.safeParse(st.scope);if(!$t.success||$t.data.projectId!==a.projectId||$t.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Gr=Xe.headers.get("X-Indiana-Telemetry-Subject");if(Gr){if(!/^[a-f0-9]{64}$/.test(Gr))throw new y("INVALID_RESPONSE","Invalid telemetry identity");m!==Gr&&(m=Gr,t?.(m))}return Tt};try{return await Promise.race([zt(),Me])}catch(Xe){throw!B&&fe!==d?new y("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):Xe instanceof y?Xe:new y(Ie.signal.aborted?"TIMEOUT":"NETWORK_ERROR",Ie.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(ke),Ie.signal.removeEventListener("abort",ve),w.delete(Ie)}}return{session:I,requestWithCredential(A,P,v){return S(A,P,"POST",{},v)},subjectKey:()=>m,identify(A){if(a&&typeof A=="object"&&"scope"in A){let P=ze.safeParse(A.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new y("SCOPE_MISMATCH","Customer session belongs to another App/environment")}I.identify(A),u=I.peek()??null},reset:f,dispose(){g(),p()},request(A,P={},v="POST",k={}){if(k.installationDetach)return S(A,P,v,k);let N=d;try{let B=I.access(),fe=Ie=>{if(N!==d)throw new y("IDENTITY_CHANGED","Customer identity changed before dispatch");return S(A,P,v,k,Ie)};return typeof B=="string"?fe(B):B.then(fe)}catch(B){return Promise.reject(B)}}}}function oh(e,t,n={}){let r=!!e.session.peek(),i=new Set,a=o=>{for(let s of i)try{s(o)}catch{}};return e.session.subscribeIdentity(()=>{r=!!e.session.peek(),a(r),n.afterChange?.()},()=>{r=!1,t()}),{isIdentified:()=>r,methods:{subscribeIdentity(o){return i.add(o),()=>{i.delete(o)}},identify(o){let s=typeof o=="string"?o:o.accessToken;if(!Vt.test(s))throw new y("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}var sh=require("zod");function ah(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof sh.ZodError?new y(n,r):i}}async function me(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=ah(t.request,n,"INVALID_REQUEST",a.request),s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):ah(t.response,s,"INVALID_RESPONSE",a.response)}function Ue(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new y("INVALID_REQUEST","Customer requests use the verified session identity")}function ch(e){return{async checkEntitlement(t){Ue(t);let n=O.checkEntitlement;return me(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return me(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function uh(e){return{async readLedger(t){let n=O.readLedger;return me(e,n,{query:t})},async readCreditStatement(t){Ue(t);let n=O.readCreditStatement;return me(e,n,t)},async quoteBalance(t){Ue(t);let n=O.quoteBalance;return me(e,n,{command:t})}}}function lh(e){return{async setupPayment(t){Ue(t);let n=O.setupPayment;return me(e,n,t)},async readPaymentSetup(t){Ue(t);let n=O.readPaymentSetup;return me(e,n,t)},async readBillingInvoice(t){Ue(t);let n=O.readBillingInvoice;return me(e,n,t)},async readBillingControls(t={}){Ue(t);let n=O.readBillingControls;return me(e,n,t)},async prepareBillingAuthorization(t){Ue(t);let n=O.prepareBillingAuthorization;return me(e,n,t)},async confirmBillingAuthorization(t){Ue(t);let n=O.confirmBillingAuthorization;return me(e,n,t)},async setBillingCoupons(t){Ue(t);let n=O.setBillingCoupons;return me(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Ue(t);let n=O.revokeBillingAuthorization;return me(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Ue(t);let n=O.listBillingInvoices;return me(e,n,t)},async confirmBillingAdjustment(t){Ue(t);let n=O.confirmBillingAdjustment;return me(e,n,t)}}}function dh(e){return{async previewUpdate(t){Ue(t);let n=O.previewUpdate;return me(e,n,t)},async update(t){Ue(t);let n=O.update;return me(e,n,t)},async readSubscriptionUpdate(t){Ue(t);let n=O.readSubscriptionUpdate;return me(e,n,t)},async restoreNativePurchase(t){Ue(t);let n=O.restoreNativePurchase;return me(e,n,t)},async previewAttach(t){Ue(t);let n=O.previewAttach;return me(e,n,t)},async attach(t){Ue(t);let n=O.attach;return me(e,n,t)},async readSubscriptionOperation(t){Ue(t);let n=O.readSubscriptionOperation;return me(e,n,t)}}}function ph(e){return{async redeemReward(t){return Ue(t),(await me(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Ue(t),(await me(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Ue(t),(await me(e,O.createReferralCode,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid referral program",response:"Invalid referral code"})).referralCode},async redeemCoupon(t,n=crypto.randomUUID()){let r=await me(e,O.redeemCoupon,{code:t,requestId:n},{request:"Invalid coupon code",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async claimCoupon(t,n=crypto.randomUUID()){let r=await me(e,O.grantOffer,{couponId:t,requestId:n},{request:"Invalid Coupon claim",response:"Invalid Coupon receipt"});return{offer:r.offer,reason:r.reason}},async listOffers(){return(await me(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function mh(e){return{...ch(e),...uh(e),...lh(e),...dh(e),...ph(e)}}function fh(e){return{async resolveContent(t){Ue(t);let n=O.resolveContent;return me(e,n,t)},async resolvePaywall(t){Ue(t);let n=O.resolvePaywall;return me(e,n,t)},async resolveOffering(t){Ue(t);let n=O.resolveOffering;return me(e,n,t)}}}var gh=e=>new TextEncoder().encode(JSON.stringify(e)).length,hh=16384;function Ah(e,t){let n=0,r,i=p=>{r={config:structuredClone(p),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,m().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function d(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!Em(r.config,p))return;I();let S=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(gh({events:[S]})>hh)throw new y("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new y("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(S)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let S={inserted:0,duplicates:0,rejected:0,skipped:0},A=a.length;for(;A&&g===n;){let P=[];for(let N of a.slice(0,Math.min(A,100))){if(P.length&&gh({events:[...P,N]})>hh)break;P.push(N)}let v=O.trackEvents,k=await me(e,v,{events:P},void 0,{keepalive:p});if(g!==n)throw new y("IDENTITY_CHANGED","Event identity changed during delivery");if(k.inserted+k.duplicates+k.rejected+k.skipped!==P.length)throw new y("INVALID_RESPONSE","Incomplete event acknowledgement");i(k.analyticsConfig),a.splice(0,P.length),A-=P.length,S.inserted+=k.inserted,S.duplicates+=k.duplicates,S.rejected+=k.rejected,S.skipped+=k.skipped}return S})();o=f;try{return await f}finally{o===f&&(o=null)}}let w;function I(){if(w||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),w=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return I(),d(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){w?.(),w=void 0}}}function ns(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,d=()=>{for(let A of u)try{A()}catch{}},m={attributes:xt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(A,P)=>{!o.has(A)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(A,structuredClone(P),structuredClone(m.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(A,P)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(A),structuredClone(P),structuredClone(m.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?A=>e.saveStickyBucketAssignmentDoc(structuredClone(A)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},w=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function I(A,P=new Set){return o.has(A)?!s||!s.features[A]||["unknownFeature","cyclicPrerequisite"].includes(s.features[A].source):P.has(A)?!1:(P.add(A),(t?.features[A]?.rules??[]).some(v=>[...v.parentConditions??[],...(v.tracks??[]).flatMap(k=>k.experiment.parentConditions??[])].some(k=>I(k.id,P))))}let p=A=>{if(e.assertUsable?.(t?.generation),!t)throw new Error("Initialize the Feature client before evaluation");if(t.expiresAt&&Date.parse(t.expiresAt)<=Date.now())throw new Error("Feature configuration expired; refresh before evaluation");return s?.expiresAt&&Date.parse(s.expiresAt)<=Date.now()&&(s=null,m.features=t.features),o.has(A)?!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?w():structuredClone(s.features[A]??w()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||I(A)?w():structuredClone(Fn(A,m))};async function g(){if(!t||!o.size&&!m.attributes?.merchandise&&!m.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(o.size)throw new Error("Remote Feature evaluation requires a server loader");return}let A=i;if(c?.revision===A)return c.loading;let P=r,v=t,k=[...o],N=(async()=>{let B=Ia.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:k}));if(!(P!==r||A!==i||v!==t)){if(e.assertUsable?.(v.generation),B.generation!==v.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(k.some(fe=>!Object.hasOwn(B.features,fe))||Object.keys(B.features).some(fe=>!o.has(fe)))throw new Error("Invalid remote Feature results");if(m.attributes?.merchandise||m.attributes?.merchandiseId){if(!B.merchandiseContext)throw new Error("Server did not resolve merchandise context");m.attributes=xt.parse({...m.attributes,...B.merchandiseContext}),a=!0}s=structuredClone(B),m.features={...v.features,...Object.fromEntries(Object.entries(s.features).map(([fe,Ie])=>[fe,{defaultValue:Ie.value}]))},d()}})();c={revision:A,loading:N};try{await N}finally{c?.loading===N&&(c=null)}}function f(){g().catch(A=>{try{e.onError?.(A)}catch{}})}async function S(){if(n)return n;let A=r,P=(async()=>{let v=await e.load(),k="remoteFeatures"in v?io.parse(v):null,N=k??pn.parse(v);if(N.scope.projectId!==e.scope.projectId||N.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(A!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===N.generation){let{evaluatedAt:fe,expiresAt:Ie,...Ce}=t,{evaluatedAt:ve,expiresAt:Me,...ke}=N;if(It(Ce)!==It(ke))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=N.evaluatedAt,t.expiresAt=N.expiresAt,d(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let B=new Set(k?.remoteFeatures??[]);if([...B].some(fe=>Object.hasOwn(N.features,fe)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in N&&!t.analyticsConfig.experimentViewsEnabled&&k?.analyticsConfig.experimentViewsEnabled&&m.trackedExperiments?.clear(),t=structuredClone(N),o=B,s=null,c=null,i++,m.features=t.features,m.savedGroups=Zr(t.savedGroups),m.trackedFeatureUsage={},d(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:S,refresh:S,refreshRemote:g,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(A){return u.add(A),()=>{u.delete(A)}},setAttributes(A){let P=xt.parse(A);(m.attributes?.merchandise||m.attributes?.merchandiseId||A.merchandise||A.merchandiseId)&&m.trackedExperiments?.clear(),m.attributes=P,i++,a=!1,s=null,c=null,m.features=t?.features??{},m.trackedFeatureUsage={},d(),f()},evalFeature:p,isOn(A){return p(A).on},isOff(A){return p(A).off},getFeatureValue(A,P){let v=p(A).value;return structuredClone(v===null?P:v)},reset(){r++,i++,n=null,c=null,t=null,s=null,o.clear(),m.features={},m.savedGroups={},m.stickyBucketAssignmentDocs={},m.attributes={},m.trackedFeatureUsage={},m.trackedExperiments?.clear(),d()}}}function yh(e){let t=e.merchandise;if(typeof e.merchandiseId=="string")return{internalId:e.merchandiseId};if(!(!t||typeof t!="object"||Array.isArray(t))){if(typeof t.internalId=="string")return{internalId:t.internalId};if(typeof t.externalId=="string")return{id:t.externalId};if(typeof t.id=="string")return{id:t.id}}}function yI(e){let t=yh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function bh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new y("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new y("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let d=a,m=!1,w=async()=>{if(m||d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let Ce=O.getFeatures,ve=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await me(e,Ce,{});if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");if(r&&(ve.scope.projectId!==r.projectId||ve.scope.environment!==r.environment))throw new y("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(ve.payload.analyticsConfig),ve},I=await w(),p=!0,g,f=Ce=>{try{u.onError?.(Ce)}catch{}},S=(Ce,ve,Me)=>{try{let ke=yh(Me);n.track(Ce,ve,ke?{merchandise:ke}:{})}catch(ke){f(ke)}},A=ns({assertUsable:i?.assertFeatures,scope:I.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,I.payload):(await w()).payload,evaluateRemote:async Ce=>{if(d!==a)throw new y("IDENTITY_CHANGED","Feature identity changed");let ve=O.evaluateFeatures,Me=await me(e,ve,{...Ce,attributes:yI(Ce.attributes)});if(Me.scope.projectId!==I.scope.projectId||Me.scope.environment!==I.scope.environment)throw new y("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Me.generation,evaluatedAt:Me.evaluatedAt,expiresAt:Me.expiresAt,features:Me.features,...Me.merchandiseContext?{merchandiseContext:Me.merchandiseContext}:{}}},onExperimentViewed:(Ce,ve,Me)=>S("Experiment Viewed",{experimentId:Ce.key,variationId:ve.key},Me),onFeatureUsage:(Ce,ve,Me)=>S("Feature Evaluated",{feature:Ce,value:ve.value,source:ve.source,ruleId:ve.ruleId,...ve.experimentResult?{variationId:ve.experimentResult.key}:{}},Me)}),P=A.refresh;function v(){clearTimeout(g),!i&&(m||d!==a||!A.expiresAt||(g=setTimeout(()=>{k().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function k(){try{return await P()}finally{v()}}let N=()=>{m||k().catch(f)},B=A.subscribe(v),fe=i?.subscribe(()=>{!m&&i.fresh&&k().catch(f)});function Ie(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",N),B(),fe?.(),A.reset(),o.delete(Ie))}o.add(Ie);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(Ce){throw Ie(),Ce}return v(),!i&&typeof window<"u"&&window.addEventListener("focus",N),Object.assign(A,{refresh:k,destroy:Ie})}return{features:c,reset(u){a++,u();for(let d of o)d()}}}var Sh=require("zod");function xh(e,t){let n="source"in t?{funnelId:t.source.id,funnelVersionId:t.source.versionId}:"versionId"in t?{funnelId:t.funnelId,funnelVersionId:t.versionId}:t,r=Sh.z.object({funnelId:Ga.shape.id,funnelVersionId:Ga.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new y("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new y("INVALID_REQUEST","Customer identity cannot be overridden");if("funnelId"in o&&o.funnelId!==void 0&&o.funnelId!==i.funnelId||"funnelVersionId"in o&&o.funnelVersionId!==void 0&&o.funnelVersionId!==i.funnelVersionId)throw new y("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await me(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return me(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return me(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return me(e,s,a(o))}}}function Ih(e){let t=pr(e),n=t.request,r=jg(e.push,t,e.scope??e.configuration?.scope),i=oh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=Ah(n,i.isIdentified),o=bh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Tg(n,r),...mh(n),...fh(n),forFunnel(s){return xh(n,s)},async features(s={}){return o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ii(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,a)=>Ii(i,t[a]));if(!e||!t||typeof e!="object"||typeof t!="object")return!1;let n=Object.entries(e),r=Object.entries(t);return n.length===r.length&&n.every(([i,a])=>Object.hasOwn(t,i)&&Ii(a,Reflect.get(t,i)))}async function rs(e,t){let n=Sg.safeParse(t);if(!n.success)throw new y("INVALID_RESPONSE","Funnel response contract changed");let r=n.data;if(e.scope&&(r.scope.projectId!==e.scope.projectId||r.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Funnel scope changed");return r}var vi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function is(e){let t=Vt.test(e.apiKey);if(typeof window<"u"&&!t)throw new y("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!vi.test(e.apiKey))throw new y("INVALID_TOKEN","A customer credential or server API key is required");let n=pr({...e,timeoutMs:e.timeoutMs??35e3});return e.session||n.identify(e.apiKey),{async start(r){let i=Un.safeParse({...r,operation:"start"});if(!i.success||i.data.operation!=="start"||(t?i.data.customer!==void 0:i.data.customer===void 0))throw new y("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=fo.safeParse(await rs(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new y("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!Ii(s.run.parameters,a.parameters??{})||(a.customer?!s.customerId||a.customer.type==="id"&&s.customerId!==a.customer.value:s.customerId!==void 0))throw new y("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function Vu(e,t,n){if(Number(e.headers.get("content-length"))>t)throw n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0;try{for(;;){n.signal?.throwIfAborted();let c=await r.read();if(c.done)break;if(a+=c.value.length,a>t)throw n.error("limit");i.push(c.value)}}finally{await r.cancel().catch(()=>{})}n.signal?.throwIfAborted();let o=new Uint8Array(a),s=0;for(let c of i)o.set(c,s),s+=c.length;return o}async function vh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Vu(e,t,n))}function os(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&nu(n)===t.sha256}async function as(e,t){let n=Vr.parse(t),{artifact:r,environmentId:i}=n.content,a=new gn(e.baseUrl??dr).origin,o=new gn(r.url,a);if(o.origin!==a||o.username||o.password||o.search||o.hash||o.pathname!==`/api/v1/configuration/${i}/artifacts/${r.sha256}`)throw new y("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c=setTimeout(()=>s.abort(),Zt.initializationMs);try{let u=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(!u.ok||!u.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(u.headers.get("content-length"))>r.byteLength)throw new y("INVALID_RESPONSE","Public Paywall is unavailable");let d=await Vu(u,r.byteLength,{signal:s.signal,error:m=>new y("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!os(d,r))throw new y("INVALID_RESPONSE","Public Paywall digest or size changed");return wf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(d)))}finally{clearTimeout(c)}}var wh=(e,t)=>new y(e,t);async function Bu(e,t,{predict:n=!0}={}){let r=t.instruction;if(r?.type!=="evaluate_segment")throw new Error("Local segment instruction required");if(!e)throw new y("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new y("SCOPE_MISMATCH","Evaluation environment changed");let i=null,a;if(n)try{let o=await e.funnel(t.source.id,t.source.versionId);a=o.manifest.generation,i=bI(e,t,o)}catch{i=null}return a??(a=e.snapshot?.generation??(await e.refresh()).generation),{advance:{policyRevision:r.policyRevision,generation:a},prediction:i}}function bI(e,t,n){let r=t.instruction;if(r?.type!=="evaluate_segment"||!n.growth||n.control.evaluationMode!=="local"||n.control.evaluationRevision!==r.policyRevision)return null;let{analyticsConfig:i,remoteFeatures:a,...o}=n.growth,s=gu({scope:{projectId:e.scope.projectId,environment:e.scope.environment},funnelId:t.source.id,versionId:t.source.versionId,evaluationMode:"local",evaluationRevision:r.policyRevision,document:n.document,payload:pn.parse(o)}),c=SI(s,n.document,{...t,...r}),u=c.steps.at(-1),d=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return d?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:d.nodeId,visit:d.visit,terminal:!c.boundary}:null}function SI(e,t,n){return Eg(e,t,n,wh)}var On=require("zod");var Oh=Un.refine(e=>!["start","get","review"].includes(e.operation)&&!("customerToken"in e),"Persist only the original mutation, without credentials").transform(e=>{if(e.operation==="start"||e.operation==="get"||e.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),_h=On.z.strictObject({schemaVersion:On.z.literal(1),scope:ze,runId:On.z.uuid(),funnelId:On.z.uuid(),versionId:On.z.uuid(),command:Oh.optional(),closeCommand:Oh.refine(e=>e.operation==="close").optional(),purchase:On.z.strictObject({receiptId:On.z.uuid(),operationId:On.z.uuid(),generation:On.z.number().int().nonnegative()}).optional(),closed:On.z.literal(!0).optional()}).refine(e=>!e.closeCommand||e.command&&e.command.operation!=="close"&&e.command.requestId!==e.closeCommand.requestId,"Close requires a separate request identity").refine(e=>e.command!==void 0||e.purchase!==void 0,"A recovery record requires an original obligation"),Yt=()=>new y("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ss=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Ch(e){let t=0,n=null,r=c=>JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]),i=Promise.resolve();async function a(){let c=await e.read();if(!Number.isSafeInteger(c.revision)||c.revision<0)throw new y("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:_h.parse(c.entry)}}function o(c){let u=i.then(c);return i=u.catch(()=>{}),u}async function s(c){for(let u=0;u<4;u++){let d=await a();if(d.entry&&n!==null&&r(d.entry)!==n)throw Yt();let m=c(d.entry,d.revision);if(ss(d.entry,m)){t=d.revision;return}let w=await e.write(d.revision,m);if(w!==null){if(!Number.isSafeInteger(w)||w<=d.revision)throw Yt();t=w;return}}throw Yt()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw Yt();n=u},async load(){let c=await a();return t=c.revision,n=c.entry?r(c.entry):null,c.entry},retain(c){let u=_h.parse(c),d=u.command;return!d||n!==null&&r(u)!==n?Promise.reject(Yt()):(n??(n=r(u)),o(()=>s((m,w)=>{if(m&&!ss(r(m),r(u)))throw Yt();if(!m){if(w!==t&&d.operation!=="close")throw Yt();return u}if(!m.command)return{...m,command:d,...d.operation==="close"?{closed:!0}:{}};if(d.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===d.requestId||m.closeCommand&&!ss(m.closeCommand,d))throw Yt();return{...m,closeCommand:d,closed:!0}}if(!ss(m.command,d))throw Yt();return m})))},observePurchase(c,u,d){return o(()=>s((m,w)=>{if(!m&&w!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw Yt();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw Yt();return d?!m?.purchase||m.purchase.operationId!==u.operationId?m:m.command?{...m,purchase:void 0}:null:{schemaVersion:1,...c,...m,purchase:u}}))},settle(c){return o(()=>s(u=>u?u.command&&"requestId"in u.command&&u.command.requestId===c?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand&&"requestId"in u.closeCommand&&u.closeCommand.requestId===c?{...u,closeCommand:void 0}:u:null))}}}function Ph(e){let t,n,r=()=>new y("COMMAND_STORAGE_INVALID","Durable command storage is unavailable"),i=Promise.resolve().then(async()=>{if(t=e.storage??globalThis.localStorage,n=e.locks??globalThis.navigator?.locks,!t||!n||!globalThis.crypto?.subtle)throw r();let s=new TextEncoder().encode(JSON.stringify([new URL(e.baseUrl??dr).href,e.runToken])),c=new Uint8Array(await crypto.subtle.digest("SHA-256",s));return"indiana.funnel.commands.v1."+Array.from(c,u=>u.toString(16).padStart(2,"0")).join("")});i.catch(()=>{});async function a(s){try{let c=await i;return await n.request(c,{mode:"exclusive"},()=>s(c))}catch(c){throw c instanceof y?c:r()}}function o(s){let c=t.getItem(s);if(c===null)return{revision:0,entry:null};if(c.length>1048576)throw r();let u=JSON.parse(c);if(!u||typeof u!="object"||!("revision"in u)||!("entry"in u)||!Number.isSafeInteger(u.revision)||Number(u.revision)<0)throw r();return{revision:Number(u.revision),entry:u.entry}}return{read:()=>a(o),write:(s,c)=>a(u=>{if(o(u).revision!==s)return null;if(!Number.isSafeInteger(s+1))throw r();return t.setItem(u,JSON.stringify({revision:s+1,entry:c})),s+1})}}function Eh(e){let t=null,n=0,r=!1,i,a=0,o=new Set;return{get view(){return t},get generation(){return n},get disposed(){return r},get customerToken(){return i},get readSequence(){return a},nextRead(){return++a},assertCurrent(s,c="Run identity changed during the request"){if(s!==n||r)throw new y("IDENTITY_CHANGED",c)},assertRun(s){if(t&&(s.id!==t.id||s.source.type!==t.source.type||s.source.id!==t.source.id||s.source.versionId!==t.source.versionId||s.locale!==t.locale||!Ii(s.parameters,t.parameters)))throw new y("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new y("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,d,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&d!==void 0&&d<a)&&(s.operation==="review"&&!c.run.stopped&&["running","waiting"].includes(c.run.status)&&t&&c.run.nodeId===t.nodeId&&c.run.visit===t.visit&&c.run.revision===t.revision&&(c.run.screen=t.screen,(t.paywall?.quote?.operationId===c.review?.activeOperationId||!t.paywall?.quote&&c.review?.activeOperationId===null)&&(c.run.paywall=t.paywall)),!(t?.paywall&&c.run.paywall&&t.paywall.receiptId===c.run.paywall.receiptId&&(c.run.paywall.selectionGeneration??0)<(t.paywall.selectionGeneration??0)))){if(!t||c.run.revision>=t.revision)t=c.run;else if(!m)return;if(t)for(let w of o)try{w(structuredClone(t))}catch{}}},identify(s){if(!Vt.test(s))throw new y("INVALID_TOKEN","Customer credential required");n++,i=s},subscribe(s){return o.add(s),()=>o.delete(s)},reset(){r=!0,n++,i=void 0,t=null,o.clear()}}}function mr(e){let{customerToken:t,...n}=e;return n}var xI=e=>!(e instanceof y)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function Rh({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,d=null,m=t?t.load().then(f=>{if(n.disposed)throw new y("IDENTITY_CHANGED","Controller was reset during command restoration");if(d=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new y("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let S=Un.parse(f.command);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("COMMAND_STORAGE_INVALID","Stored mutation required");i=S,f.closeCommand&&(a=f.closeCommand,o=!0),S.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function w(f=i){if(t&&await m,!f)throw new y("INVALID_REQUEST","No command is pending");let S=f,A=n.generation;if(t){if(!n.view||!e.scope)throw new y("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await t.retain({schemaVersion:1,scope:e.scope,runId:n.view.id,funnelId:n.view.source.id,versionId:n.view.source.versionId,command:mr(S)})}if(A!==n.generation||i!==S&&a!==S)throw new y("IDENTITY_CHANGED","Run changed before command dispatch");let P={...S,...n.customerToken?{customerToken:n.customerToken}:{}},v=c;c=!0;try{return await r(P,k=>{if(!k.settlement)throw new y("INVALID_RESPONSE","Exact command settlement is missing");if(k.settlement.requestId!==S.requestId)throw new y("INVALID_RESPONSE","Command settlement identity changed");if(A===n.generation&&(i===S||a===S)&&k.run.pendingRequest?.requestId!==S.requestId&&k.settlement.state==="settled"&&(!o||S.operation==="close"||k.settlement?.state==="settled"&&!["running","waiting"].includes(k.run.status))){let N=()=>A!==n.generation||i!==S&&a!==S?!1:(i===S&&(i=null),a===S&&(a=null),c=i!==null,d=null,!0);return t?t.settle(S.requestId).then(N):N()}return!1})}catch(k){throw A===n.generation&&i===S&&!v&&!xI(k)&&(t&&await t.settle(S.requestId),A===n.generation&&i===S&&(i=null,c=!1,d=null)),k}}function I(f){let S=Un.parse(f);if(S.operation==="start"||S.operation==="get"||S.operation==="review")throw new y("INVALID_REQUEST","Mutation required");if(o&&S.operation!=="close"){if(i?.requestId===S.requestId)return g(S.requestId);throw new y("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(S.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(mr(a))!==JSON.stringify(mr(S)))throw new y("COMMAND_PENDING","Retry the original Close");return a??(a=S),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(mr(i))!==JSON.stringify(mr(S)))throw new y("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=S,c=!1;return p(i,"command")}function p(f,S){let A=w(f);s[S]=A;let P=()=>{s[S]===A&&(s[S]=null)};return A.then(P,P),A}async function g(f){let S=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(S.settlement?.requestId!==f)throw new y("INVALID_RESPONSE","Exact command settlement is missing");return S.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),S}return{ready:m,get pending(){return i},get closing(){return a},get closeRequested(){return o},get inFlight(){return s.command},get closeFlight(){return s.close},get purchase(){return u},assertBinding(f){if(d&&(f.run.id!==d.runId||f.run.source.id!==d.funnelId||f.run.source.versionId!==d.versionId))throw new y("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,S,A,P){t?.bind({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId}),t&&!e.scope&&(e.scope=S.scope);let v=S.run.paywall,k=v??S.purchase,N=k?.operation,B=S.settlement&&(!v||v.purchaseRequestId===S.settlement.requestId)&&(!u||u.operationId===S.settlement.operationId)?S.settlement:void 0,fe=N?.operationId??k?.quote?.operationId??B?.operationId,Ie=k?.receiptId??B?.receiptId,Ce=v?.selectionGeneration??u?.generation??0;if(t&&fe&&Ie&&f.operation!=="review"&&(!n.view||S.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Ce>=u.generation)){let ve={receiptId:Ie,operationId:fe,generation:Ce},Me=N?.status==="complete"||k?.canReselect===!0;return t.observePurchase({scope:S.scope,runId:S.run.id,funnelId:S.run.source.id,versionId:S.run.source.versionId},ve,Me).then(()=>{n.assertCurrent(A),Me?u?.operationId===ve.operationId&&(u=void 0):u=ve})}},stop(){o=!0},submit:I,executePending:w,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function wi(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new y("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!vi.test(e.serverKey)))throw new y("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new y("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=pr({...e,session:void 0,...e.serverKey?{fetch:(f,S)=>{let A=new Headers(S?.headers),P=typeof S?.body=="string"?JSON.parse(S.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||A.set(xg,e.serverKey),(e.fetch??globalThis.fetch)(f,{...S,headers:A})}}:{},...e.session?{fetch:async(f,S)=>{let A=await e.session.access(),P=typeof S?.body=="string"?JSON.parse(S.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new y("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...S,body:JSON.stringify({...P,customerToken:A})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Eh(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Ph(e):void 0),o=a&&Ch(a),s=Rh({options:e,journal:o,state:n,call:c});async function c(f,S,A){let P=n.generation,v=()=>n.assertCurrent(P);o&&await s.ready,v();let k=n.view,N=fo.parse(await rs(e,await t.request("funnels",Un.parse(f))));if(f.operation==="review"&&!N.review)throw new y("INVALID_RESPONSE","Historical projection is missing");if(v(),N.runToken&&N.runToken!==e.runToken)throw new y("INVALID_RESPONSE","Run credential changed");let B=f.operation==="get"?f.settlementRequestId:"requestId"in f&&f.operation!=="start"?f.requestId:void 0;if(B&&N.settlement?.requestId!==B)throw new y("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(N),n.assertRun(N.run);let fe=s.observePurchase(f,N,P,A);if(fe&&await fe,!N.run.stopped&&["running","waiting"].includes(N.run.status)&&f.operation==="get"&&f.settlementRequestId)return N;let Ie=S?.(N),Ce=typeof Ie=="boolean"?Ie:Ie?await Ie:!1;return v(),["running","waiting"].includes(N.run.status)||s.stop(),n.publish(f,N,k,A,Ce),N}let u=s.submit,d=null,m=new WeakMap;function w(f){let S=m.get(f);if(S)return S;let A=p(f);return m.set(f,A),A}let I=!1;async function p(f){let S=await f;if(S.run.instruction?.type!=="evaluate_segment")return S;if(d)return d;I=!0;let A=n.generation,P=(async()=>{for(let v=0;v<32&&S.run.instruction?.type==="evaluate_segment";v++){if(s.pending||s.closeRequested)return S;let k=S.run;if(S.run.instruction?.type==="evaluate_segment"){let{advance:B}=await Bu(e.configuration,k,{predict:!1});if(A!==n.generation)throw new y("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return S;if(n.view&&(n.view.revision!==k.revision||n.view.visit!==k.visit||n.view.nodeId!==k.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let fe=!0;Bu(e.configuration,k).then(({prediction:Ie})=>{fe&&A===n.generation&&!s.closeRequested&&n.view?.id===k.id&&!n.view.stopped&&n.view.nodeId===k.nodeId&&n.view.visit===k.visit&&n.view.revision===k.revision&&(i=Ie)}).catch(()=>{});try{S=await u({operation:"commit_segment",requestId:bg(k.id,k.visit,`segment:${k.revision}`),nodeId:k.nodeId,visit:k.visit,revision:k.revision,...B})}finally{fe=!1,i=null}}}return S})();d=P;try{return await P}finally{d===P&&(d=null)}}let g={get configuration(){return I?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let f=s.closing??s.pending;return f?structuredClone(mr(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(mr(f)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let f=n.view;return i&&f&&!f.stopped&&["running","waiting"].includes(f.status)&&f.id===i.runId&&f.nodeId===i.from.nodeId&&f.visit===i.from.visit&&f.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(f){return as(e,f)},async pageExperiments(f,S=[]){let A=n.generation;n.assertCurrent(A);let P=n.view?.id;if(!P)throw new y("INVALID_REQUEST","Read the Run before its page experiments");let v=kg.parse(await t.request("funnels",Rg.parse({operation:"page_experiments",release:f,usedReceiptIds:S,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(A),v.runId!==P||v.scope.projectId!==e.scope?.projectId||v.scope.environment!==e.scope?.environment)throw new y("SCOPE_MISMATCH","Page experiment Run changed");return v},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,S){o&&await s.ready,S??(S=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let A=n.nextRead();return w(c({operation:"get",...f?{data:f}:{},...S?{purchase:S}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,A))},resume(f=n.view?.pendingRequest?.requestId){return f?s.closeRequested?g.settle(f):s.pending?.requestId===f?w(u(s.pending)):w(u({operation:"resume",requestId:f})):Promise.reject(new y("INVALID_REQUEST","No interrupted command is available"))},submit(f){return w(u(f))},retry(){return s.closeFlight?s.closeFlight:s.closing?s.executePending(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?w(s.inFlight):s.pending?w(u(s.pending)):Promise.reject(new y("INVALID_REQUEST","No command is pending"))},identify(f){n.identify(f),i=null,t.identify(e.runToken)},subscribe:n.subscribe,reset(){r?.(),n.reset(),s.reset(),i=null,t.reset()}};return g}function kh(e){if(!Vt.test(e.customerToken))throw new y("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new y("INVALID_REQUEST","An explicit App and environment scope is required");let t=is({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=wi({...e,runToken:r.runToken});i.identify(e.customerToken);let a=r.run.instruction?.type==="evaluate_segment"?await i.get():r;return{...r,...a,controller:i}}}}function jh(e,t){let n=r=>"document"in r?r.offering.id:r.content.offeringVersionId;return e.id===t.id&&n(e)===n(t)&&e.content?.artifact.sha256===t.content?.artifact.sha256}function Th(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new y("INVALID_RESPONSE",n)}function Nh(e,t,n){let r=Object.fromEntries((e.lines[0]?.prepaid??[]).map(i=>[i.internal_feature_id,i.quantity]));if(t.featureQuantities&&(Object.keys(r).length!==Object.keys(t.featureQuantities).length||Object.entries(t.featureQuantities).some(([i,a])=>r[i]!==a)))throw new y("INVALID_RESPONSE","The purchase quote changed its selected quantities");if(e.lines.length!==1||e.lines[0].productVersionId!==t.productVersionId||t.currency!==void 0&&e.currency!==t.currency||t.provider!==void 0&&e.provider!==t.provider&&!(t.provider==="stripe"&&e.provider==="merchant"&&e.execution?.provider==="merchant"))throw new y("INVALID_RESPONSE",n)}function Dh(e,t,n=!1){return!e||e.operationId!==t?.operationId?t:e.status==="complete"&&t.status!=="complete"||e.status!=="pending"&&(t.status==="pending"||n&&t.status!=="complete")?e:t}async function Fh(e,t){if(!Vt.test(t.customerToken))throw new y("INVALID_TOKEN","A verified Customer credential is required");let n=pr(e);if(!e.session)n.identify(t.customerToken);else if(e.session.peek()!==t.customerToken)throw new y("SCOPE_MISMATCH","Paywall credential does not match the shared session");let r=O.resolvePaywall.request.parse({funnelId:t.funnelId,funnelVersionId:t.funnelVersionId,selector:t.paywallVersionId?{type:"version",versionId:t.paywallVersionId}:{type:"paywall",paywallId:t.paywallId},commerce:t.commerce,locale:t.locale,...t.requirement?{requirement:t.requirement}:{}}),i=null,a=!1,o=null,s=null,c=null,u=null,d=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await me(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await as(e,g.paywall)};if(a)throw new y("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new y("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!jh(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new y("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function w(p){if(!o)throw new y("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await me(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return Th(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=Dh(s,f.operation),structuredClone(s)}let I={get view(){return i?structuredClone(i):null},get quote(){return o?structuredClone(o):null},get operation(){return s?structuredClone(s):null},get webViewUrl(){return"bundled"},refresh:m,async preview(p){if(!i)throw new y("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new y("INVALID_REQUEST","Choose an authored purchase action");let f=_m(g.product,p.selection,i.capabilities);if(!f)throw new y("PRODUCT_UNAVAILABLE","Choose an available Product");let S=gf(i.document.screen,f,p.selection,i.capabilities),A=O.previewAttach.request.parse({funnelId:r.funnelId,funnelVersionId:r.funnelVersionId,requestId:p.requestId,plans:[{productVersionId:f,...Object.keys(S).length?{featureQuantities:S}:{}}],provider:r.commerce.provider,currency:r.commerce.currency,...p.offerId?{offerId:p.offerId}:{},...p.nativeOffer?{nativeOffer:p.nativeOffer}:{}}),P=JSON.stringify(A);if(c&&c!==P&&(!s||s.status==="pending"))throw new y("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===P){if(u)return u;if(o)return structuredClone(o)}c=P;let v=(async()=>{let k=O.previewAttach,N=await me(n.request,k,A);return Nh(N.quote,{productVersionId:f,featureQuantities:S,currency:r.commerce.currency,provider:r.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=N.quote,s=null,structuredClone(o)})();u=v;try{return await v}finally{u===v&&(u=null)}},confirm:()=>w("confirm"),cancel:()=>w("cancel"),read:()=>w("read"),destroy(){d?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),I}function Mh(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new y("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new y("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new y("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let I=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,I)).catch(()=>{})}),d=e.nativeEvents?.(I=>{!n||!e.nativeModule||typeof I?.requestId!="string"||(async()=>{let p=await n;if(I.instanceId!==p)return;if(I.kind==="credential"){let S=r,A=null;try{if(!o&&I.revision===S){let P=await t.access();!o&&r===S&&(A=P)}}finally{await e.nativeModule.provideCredential(p,I.requestId,A)}return}let g=!1,f=r;try{if(o||I.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(I.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,I.requestId,g)}})().catch(()=>{})});async function m(I,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new y("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,S=await t.access();if(o||r!==f)throw c();if(!n){let v=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=v,v.catch(()=>{n===v&&(n=void 0)})}let A=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let k=(async()=>{if(await g.identify(A,JSON.stringify({revision:f,credentials:S})),o||r!==f)throw await g.reset(A,f),c();i=f})();a={epoch:f,task:k}}let v=a;try{await v.task}finally{a===v&&(a=void 0)}}let P=await g.invoke(A,I,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new y("INVALID_RESPONSE","Native host returned invalid JSON")}}async function w(I,p){let g=await m(I,p);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new y("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(I){return w("showFunnel",{runToken:I})},showPaywall(I){return w("showPaywall",I)},showContent(I){return w("showContent",I)},purchaseSubscription(I,p){return m("purchaseSubscription",{operationId:I,accepted:p})},switchSubscription(I,p){return m("switchSubscription",{operationId:I,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(I){return m("manageSubscriptions",I?{productId:I}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),d?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var II=O.trackUsage.request.shape.command,vI=O.trackUsage.response;function wI(e){let t=ze.parse(e.scope),n=Ih({...e,scope:t}),r={...e,scope:t,session:n.session},i=0;n.subscribeIdentity(()=>{i++});let a=()=>{let o=n.session.peek();if(!o)throw new y("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:Mh(e,n.session),funnel(){return kh({...r,customerToken:a()})},resumeFunnel(o){return a(),wi({...r,runToken:o})},paywall(o){return Fh(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new y("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new y("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=II.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new y("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new y("IDENTITY_CHANGED","Customer identity changed during usage reporting");let d=vI.parse(u);if(d.scope.projectId!==t.projectId||d.scope.environment!==t.environment)throw new y("INVALID_RESPONSE","Usage response scope differs");return d}}}var Uh=require("zod");var Oi=require("zod");var OI=Oi.z.record(Oi.z.string().regex(/^[a-f0-9]{64}$/),Oi.z.strictObject({at:Oi.z.number(),text:Oi.z.string()})),qh=2*1048576,_I=100;function CI(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Vh(e,t){let n=t===void 0?CI():t,r=Promise.resolve();async function i(o){if(!n)return null;let s;try{return await Promise.race([Promise.resolve().then(()=>n.getItem(o)),new Promise(c=>{s=setTimeout(()=>c(null),_I)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=qh)return OI.parse(JSON.parse(o))}catch{}return{}}return{async readManifest(){return i(e)},writeManifest(o){Promise.resolve().then(()=>n?.setItem(e,o)).catch(()=>{})},async readArtifact(o){let s=(await a())[o];return s&&Date.now()>=s.at&&Date.now()-s.at<=Zt.retentionMs?s.text:void 0},writeArtifact(o,s){n&&(r=r.catch(()=>{}).then(async()=>{let c=await a(),u=Date.now();c[o]={at:u,text:s};let d={},m=2,w=0;for(let[I,p]of Object.entries(c).sort(([,g],[,f])=>f.at-g.at)){if(p.at>u||u-p.at>Zt.retentionMs)continue;let g=new TextEncoder().encode(JSON.stringify({[I]:p})).byteLength;m+g>qh||w>=128||(d[I]=p,m+=g,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(d))}).catch(()=>{}))}}}var _e=(e,t)=>new y(e,t),fr=()=>performance.now(),Bh=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function Lh(e){let t=Xc.parse(e.scope),n=new gn(e.origin??dr);if(n.username||n.password||n.search||n.hash||n.pathname!=="/"||n.protocol!=="https:"&&!(n.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(n.hostname)))throw _e("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(ee=>{let H=new gn(ee);if(H.protocol!=="https:"||H.username||H.password||H.search||H.hash||H.pathname!=="/")throw _e("INVALID_URL","Invalid configuration asset origin");return H.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${It(t)}`,s=Vh(o,e.storage),c,u=0,d=0,m=!1,w=!1,I=0,p=0,g,f,S,A,P=0,v=new Set,k=new Set,N=new Map,B=new Map,fe=0,Ie=!1;function Ce(){for(let ee of v)try{ee()}catch{}}function ve(ee){try{e.onError?.(ee)}catch{}}let Me=()=>!w&&!m&&!!c&&fr()<u&&Date.now()<d;function ke(){if(!Me())throw _e("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function zt(ee,H){let ce=new TextEncoder().encode(H).byteLength;if(!N.has(ee)){for(;N.size&&(N.size>=128||fe+ce>Zt.maxCacheBytes);){let ue=N.entries().next().value;fe-=new TextEncoder().encode(ue[1]).byteLength,N.delete(ue[0])}N.set(ee,H),fe+=ce}}function Xe(ee,H,ce){return vh(ee,H,{signal:ce,error:ue=>_e("INVALID_RESPONSE",ue==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Tt(ee){let H=new gn(ee,n);if(!r.has(H.origin)||H.username||H.password||H.hash||H.search)throw _e("INVALID_URL","Configuration artifact origin is not trusted");return H.href}async function bo(ee,H,ce=!1){let ue=await i(Tt(ee),{method:"GET",credentials:"omit",redirect:"error",cache:ce?"default":"no-cache",signal:H,headers:{}});if(ue.status===429){let Ne=ue.headers.get("retry-after")??"";P=/^\d+$/.test(Ne)?Number(Ne)*1e3:Math.max(0,Date.parse(Ne)-Date.now())||15e3}if(!ue.ok&&ue.status!==304)throw _e(`CONFIGURATION_HTTP_${ue.status}`,"Configuration synchronization failed");return ue}function Gr(ee,H,ce){let ue=Date.parse(ee.headers.get("x-indiana-config-validated-at")??""),Ne=Date.parse(ee.headers.get("x-indiana-config-valid-until")??""),Ct=Date.parse(ee.headers.get("date")??""),Ke=ee.headers.get("age"),Xt=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![ue,Ne,Ct,Xt].every(Number.isFinite)||Ne<=ue||Ne-ue>Zt.maxControlAgeMs||ue>Ct+1e3)throw _e("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Pt=Math.min(Ne-ue,ce.maxControlAgeSeconds*1e3,Zt.maxControlAgeMs)-Math.max(Xt,Ct-ue,0)-(fr()-H);if(Pt<=0)throw _e("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return fr()+Pt}function st(){if(clearTimeout(S),clearTimeout(A),w||!v.size)return;Me()&&(A=setTimeout(()=>{Me()?st():Ce()},Math.max(1,u-fr())),Bh(A));let ee=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);S=setTimeout(()=>{$t().catch(ve)},Math.max(P,ee*(.8+Math.random()*.2))),Bh(S)}async function $t(){if(w)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let ee=I,H=new AbortController;f=H;let ce=(async()=>{if(!Ie){Ie=!0;try{let xo=await s.readManifest();if(xo&&!c){let Tn=tu.parse(JSON.parse(xo));It(Tn.scope)===It(t)&&(c=Tn)}}catch{}}H.signal.throwIfAborted();let Ke=c,Xt=fr(),Mt=await bo(a,H.signal);Mt.status===304&&(!Ke||!Mt.headers.has("x-indiana-config-validated-at")||!Mt.headers.has("x-indiana-config-valid-until")||!Mt.headers.has("age"))&&(Mt=await bo(a,H.signal));let Pt=Mt.status===304?Ke:tu.parse(JSON.parse(await Xe(Mt,Zt.maxManifestBytes,H.signal))),{generation:zn,...$n}=Pt,Ar=Mt.headers.get("etag");if(It(Pt.scope)!==It(t)||Sf($n)!==zn||Ar!==`"${zn}"`&&Ar!==`W/"${zn}"`)throw _e("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(Pt.revision<Ke.revision||Pt.revision===Ke.revision&&Pt.generation!==Ke.generation))throw _e("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[xo,Tn]of Object.entries(Ke?.funnels??{})){let yr=Pt.funnels[xo];if(yr&&(yr.controlRevision<Tn.controlRevision||yr.evaluationRevision<Tn.evaluationRevision||yr.controlRevision===Tn.controlRevision&&yr.state!==Tn.state||yr.evaluationRevision===Tn.evaluationRevision&&yr.evaluationMode!==Tn.evaluationMode))throw _e("INVALID_RESPONSE","Funnel control revision changed identity")}let Gu=Gr(Mt,Xt,Pt.policy);if(H.signal.throwIfAborted(),ee!==I)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Pt,u=Gu,d=Date.now()+Math.max(0,Gu-fr()),m=!1,p=0,P=0,s.writeManifest(It(Pt)),Ce(),structuredClone(Pt)})(),ue=setTimeout(()=>H.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs),Ne=new Promise((Ke,Xt)=>H.signal.addEventListener("abort",()=>Xt(H.signal.reason),{once:!0})),Ct=Promise.race([ce,Ne]).catch(Ke=>{throw p++,(Ke instanceof Uh.z.ZodError||Ke instanceof SyntaxError||Ke instanceof y&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,m=!0,Ce()),Ke}).finally(()=>{clearTimeout(ue),g===Ct&&(g=void 0),st()});return g=Ct,Ct}async function gr(ee){let H=ee.sha256,ce=zn=>os(zn,ee);Tt(ee.url);let ue=N.get(H);if(ue&&ce(ue))return N.delete(H),N.set(H,ue),ue;if(B.has(H))return B.get(H);let Ne=new AbortController;k.add(Ne);let Ct=I,Ke=(async()=>{try{let Ar=await s.readArtifact(H);if(Ar&&ce(Ar))return zt(H,Ar),Ar}catch{}Ne.signal.throwIfAborted();let zn=await bo(ee.url,Ne.signal,!0),$n=await Xe(zn,ee.byteLength,Ne.signal);if(!ce($n))throw _e("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(w||Ct!==I)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return zt(H,$n),s.writeArtifact(H,$n),$n})(),Xt=setTimeout(()=>Ne.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Zt.initializationMs),Mt=new Promise((zn,$n)=>Ne.signal.addEventListener("abort",()=>$n(Ne.signal.reason),{once:!0})),Pt=Promise.race([Ke,Mt]).finally(()=>{clearTimeout(Xt),k.delete(Ne),B.delete(H)});return B.set(H,Pt),Pt}async function hr(){return Me()||await $t(),ke(),c}async function _i(ee){let H,ce=new Promise((ue,Ne)=>{H=setTimeout(()=>Ne(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs)});try{return await Promise.race([ee(),ce])}finally{clearTimeout(H)}}function Ci(ee,H){if(ke(),c?.generation!==ee.generation)throw _e("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(H&&c.funnels[H]?.state!=="active")throw _e("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function Uu(ee){let H=ee.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let ce=ee.artifacts[H];if(ce.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let ue=_c.parse(JSON.parse(await gr(ce)));if(It(ue.scope)!==It({projectId:t.projectId,environment:t.environment})||ue.generation!==ce.generation||ue.remoteFeatures.some(Ne=>Object.hasOwn(ue.features,Ne)))throw _e("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ci(ee),{...ue,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-fr())).toISOString()}}async function Lu(ee,H){let ce=await hr(),ue=ce.funnels[ee];H&&(!ue||ue.evaluationMode==="local"&&!ue.versions[H])&&(g&&await g,ce=await $t()),Ci(ce,ee);let Ne=ce.funnels[ee];if(Ne.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let Ct=H??Ne.currentVersionId,Ke=Ne.versions[Ct];if(!Ke)throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(ce.artifacts[Ke.artifact].formatVersion!==3)throw _e("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Xt,Mt]=await Promise.all([gr(ce.artifacts[Ke.artifact]).then(Pt=>If(JSON.parse(Pt))),Ne.evaluationMode==="local"?Uu(ce):void 0]);if(Mt&&It(xf(Xt,Mt))!==It(Ke.dependencies))throw _e("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ci(ce,ee),{document:Xt,growth:Mt,versionId:Ct,control:structuredClone(Ne),manifest:structuredClone(ce)}}async function zu(ee,H){try{return await Lu(ee,H)}catch(ce){if(!(ce instanceof y)||!(ce.code==="CONFIGURATION_CHANGED"||ce.code==="CONFIGURATION_HTTP_404"&&Me()))throw ce;let ue=c?.generation;if(g&&await g,await $t(),ce.code!=="CONFIGURATION_CHANGED"&&c?.generation===ue)throw ce;return Lu(ee,H)}}function cs(){m=!0,Ce(),$t().catch(ve)}let So=()=>{(typeof document>"u"||document.visibilityState==="visible")&&cs()};function $h(ee){if(w)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return v.add(ee),v.size===1&&(typeof window<"u"&&(window.addEventListener("online",cs),window.addEventListener("focus",So),document.addEventListener("visibilitychange",So)),st()),()=>{v.delete(ee),v.size||(clearTimeout(S),clearTimeout(A),$u())}}function $u(){typeof window<"u"&&(window.removeEventListener("online",cs),window.removeEventListener("focus",So),document.removeEventListener("visibilitychange",So))}return{scope:Object.freeze({...t}),refresh:$t,subscribe:$h,assertFresh:ke,assertFeatures(ee){ke();let H=c.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(ee!==void 0&&c.artifacts[H].generation!==ee)throw _e("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Me()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Me()?Math.max(0,u-fr()):0},async features(){return _i(async()=>Uu(await hr()))},pageExperiments:()=>_i(async()=>{let ee=await hr(),H=ee.gb.pageExperiments;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let ce=ee.artifacts[H];if(ce.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let ue=_g.parse(JSON.parse(await gr(ce)));if(ue.environmentId!==t.environmentId||ue.generation!==ce.generation)throw _e("INVALID_RESPONSE","Page experiment scope or generation changed");return Ci(ee),ue}),funnel:(ee,H)=>_i(()=>zu(ee,H)),paywall:(ee,H)=>_i(async()=>{let ce=await hr(),ue=ce.paywalls?.[ee];if(!ue||!H&&ue.state!=="published")throw _e("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ne=H??ue.currentVersionId,Ct=ue.versions[Ne],Ke=Ct&&ce.artifacts[Ct.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Xt=za.parse(JSON.parse(await gr(Ke)));return Ci(ce),{document:Xt,versionId:Ne,version:Ct.version,control:structuredClone(ue),manifest:structuredClone(ce)}}),async localFunnel(ee,H){let ce=await _i(()=>zu(ee,H));if(!ce.growth)throw _e("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:ue,remoteFeatures:Ne,...Ct}=ce.growth;return wg({scope:{projectId:t.projectId,environment:t.environment},funnelId:ee,versionId:ce.versionId,evaluationMode:"local",evaluationRevision:ce.control.evaluationRevision,document:ce.document,payload:Ct})},assertFunnel(ee,H,ce){ke();let ue=c.funnels[ee];if(!ue||ue.state!=="active")throw _e("FUNNEL_STOPPED","Funnel is paused or unavailable");if(ue.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel now executes at Longplay");if(H!==void 0&&ue.controlRevision!==H)throw _e("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(ce!==void 0&&!ue.versions[ce])throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!w){w=!0,I++,u=0,f?.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(S),clearTimeout(A),$u(),Ce(),v.clear();for(let ee of k)ee.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));N.clear(),fe=0}}}}async function zh(e){e={...e};let t=e.configuration;if(!t)throw new y("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&It(n)!==It(e.scope))throw new y("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new y("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=vi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new y("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=is({...e,scope:n,apiKey:e.credential}),o=s=>{let c=wi({...e,scope:n,runToken:s,...i?{serverKey:e.credential}:{}});return i||c.identify(e.credential),c};return{async start(s){let c=await a.start({...s,funnelId:e.funnelId,...i?{customer:{type:"id",value:e.customerId}}:{}}),u=o(c.runToken),d=await u.get();return{...c,...d,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new y("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}