@tinkerlandai/longplay-react-native 0.10.8 → 0.10.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/index.cjs +2 -2
  2. package/dist/index.d.cts +26549 -12669
  3. package/dist/index.d.ts +26549 -12669
  4. package/dist/index.js +2 -2
  5. package/native-sdk/android/assets/indiana/index.html +42 -42
  6. package/native-sdk/android/java/ai/tinkerland/indiana/BundledWebView.kt +6 -2
  7. package/native-sdk/android/java/ai/tinkerland/indiana/CustomerSession.kt +9 -3
  8. package/native-sdk/android/java/ai/tinkerland/indiana/FeatureClient.kt +46 -22
  9. package/native-sdk/android/java/ai/tinkerland/indiana/FunnelConfigurationRelay.kt +47 -21
  10. package/native-sdk/android/java/ai/tinkerland/indiana/FunnelProcess.kt +120 -0
  11. package/native-sdk/android/java/ai/tinkerland/indiana/FunnelSession.kt +57 -16
  12. package/native-sdk/android/java/ai/tinkerland/indiana/GoogleStorefront.kt +18 -2
  13. package/native-sdk/android/java/ai/tinkerland/indiana/HTTPTransport.kt +48 -20
  14. package/native-sdk/android/java/ai/tinkerland/indiana/IndianaClient.kt +36 -44
  15. package/native-sdk/android/java/ai/tinkerland/indiana/PaywallSession.kt +82 -59
  16. package/native-sdk/android/java/ai/tinkerland/indiana/SDKVersion.kt +1 -1
  17. package/native-sdk/android/java/ai/tinkerland/indiana/WireSchema.kt +3 -1
  18. package/native-sdk/android/java/ai/tinkerland/longplay/Longplay.kt +3 -0
  19. package/native-sdk/android/resources/funnel-wire-schemas.json +1 -1
  20. package/native-sdk/ios/BundledWebView.swift +5 -1
  21. package/native-sdk/ios/CustomerSession.swift +7 -3
  22. package/native-sdk/ios/FeatureClient.swift +75 -29
  23. package/native-sdk/ios/FunnelConfigurationRelay.swift +1 -0
  24. package/native-sdk/ios/FunnelProcess.swift +148 -0
  25. package/native-sdk/ios/FunnelSession.swift +37 -9
  26. package/native-sdk/ios/HTTPTransport.swift +2 -0
  27. package/native-sdk/ios/IndianaClient.swift +25 -60
  28. package/native-sdk/ios/NativeReceiptRelay.swift +3 -3
  29. package/native-sdk/ios/PaywallSession.swift +5 -4
  30. package/native-sdk/ios/SDKVersion.swift +1 -1
  31. package/native-sdk/ios/WebView/index.html +42 -42
  32. package/native-sdk/ios/funnel-wire-schemas.json +1 -1
  33. package/package.json +1 -1
  34. package/native-sdk/android/java/ai/tinkerland/indiana/NativePendingKeystore.kt +0 -81
  35. package/native-sdk/ios/NativePendingKeychain.swift +0 -52
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var Dh=Object.defineProperty;var Fh=(e,t,n)=>t in e?Dh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var De=(e,t,n)=>Fh(e,typeof t!="symbol"?t+"":t,n);import{z as os}from"zod";var Mh=os.enum(["sandbox","live"]),Ue=os.object({projectId:os.string().min(1),environment:Mh}).strict();import{z as Le}from"zod";var Oi=Le.number().int().min(1).max(Number.MAX_SAFE_INTEGER),Gu=Le.enum(["unknown","denied","provisional","granted"]),Ku=Le.enum(["ios","android"]),So=Le.strictObject({installationId:Le.uuid(),publicKey:Le.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:Le.iso.datetime({offset:!0}),signature:Le.string().regex(/^[A-Za-z0-9_-]{86}$/)}),as=Le.string().regex(/^[a-f0-9]{64}$/),Hu=So.extend({sequence:Oi,platform:Ku,credentialDigest:as}),Qu=So.extend({credentialDigest:as}),Ju=So.extend({sequence:Oi,platform:Ku}),xo=So.extend({sequence:Oi,credentialDigest:as,connectionId:Le.uuid().nullable(),kind:Le.enum(["fcm_token","apns_token"]).nullable(),token:Le.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:Gu}),Zu=xo,Wu=xo.extend({challenge:Le.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),ss=Le.strictObject({requested:Le.literal(!0),expiresAt:Le.iso.datetime({offset:!0})}),gr=Le.strictObject({installationId:Le.uuid(),bound:Le.boolean(),identitySeq:Oi,bindingGeneration:Oi,addressSeq:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:Le.uuid().nullable(),addressStatus:Le.enum(["active","invalid"]).nullable(),permission:Gu}),cs=Le.strictObject({channel:Le.enum(["email","sms","voice","push"]),state:Le.enum(["unknown","allowed","denied"]),revision:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:Le.iso.datetime({offset:!0}).nullable()}),CI=Le.strictObject({state:Le.enum(["allowed","denied"]),revision:Le.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function Yu(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))}import{z as It}from"zod";var Tn=It.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"]),RI=It.enum([...Tn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),kI=It.enum([...Tn.options,"stale_revision"]),us=It.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"]),ls=It.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),el={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 Xu={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 qh(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(Xu,e)){let r=Xu[e];return{retryable:r==="retry_same_request",recovery:r}}let n=Tn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:el[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function tl(e,t){let n=Tn.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):el[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 Vh(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 nl=It.object({retryable:It.boolean(),recovery:us,reason:ls.optional(),retryAfterSeconds:It.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),ds=It.object({requestId:It.uuid().optional(),error:It.object({code:It.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:It.string(),...nl.partial().shape})}),jI=It.object({error:ds.shape.error.extend({requestId:It.uuid().optional()})}),TI=It.object({error:It.string(),code:It.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:It.uuid(),...nl.shape});function Io(e,t,n={}){let r=qh(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?Vh(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var ps="X-Indiana-Protocol",rl="X-Indiana-SDK-Version";var ms={current:"0.10"};import{z as Bh}from"zod";var Uh=["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=Bh.enum(Uh);import{z as _}from"zod";var Dt=_.string().min(1).max(200),Gt=_.iso.datetime({offset:!0}),mt=_.number().int().nonnegative().max(1e8),vo=_.string().regex(/^[A-Z]{3}$/),Lh=["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"],il=_.enum(Lh),ol=_.strictObject({priceId:_.uuid(),productVersionId:_.uuid(),productId:Dt,quantity:_.number().int().min(1).max(1e6),unitAmountMinor:mt,totalMinor:mt,interval:_.enum(["week","month","year","one_off"]),intervalCount:_.number().int().min(1).max(52),kind:_.enum(["fixed","prepaid","seat"]),tiers:_.strictObject({mode:_.enum(["graduated","volume"]),tiers:_.array(_.strictObject({upTo:_.number().int().positive().nullable(),unitAmountMinor:mt,flatAmountMinor:mt.optional()})).min(2).max(12)}).nullable()}),zh=_.strictObject({grantId:_.uuid(),couponId:_.uuid(),amountMinor:mt,terms:_.discriminatedUnion("type",[_.strictObject({type:_.literal("percent"),percentOff:_.number().gt(0).max(100)}),_.strictObject({type:_.literal("amount"),amountOffMinor:mt,currency:vo})]),duration:_.discriminatedUnion("type",[_.strictObject({type:_.literal("once")}),_.strictObject({type:_.literal("forever")}),_.strictObject({type:_.literal("repeating"),months:_.number().int().min(1).max(36)})])}),As={provider:_.literal("merchant"),executor:_.literal("merchant"),operationId:_.uuid(),customerId:_.uuid(),configurationRevision:_.number().int().nonnegative(),connectionRevision:_.number().int().nonnegative(),currency:vo,expiresAt:Gt},wo=_.strictObject({...As,type:_.literal("purchase"),mode:_.enum(["payment","subscription"]),lineItems:_.array(ol).min(1).max(100),catalogAmountMinor:mt,discount:zh.nullable(),trialPeriodDays:_.number().int().min(1).max(730).nullable(),automaticTax:_.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"),Oo=_.strictObject({...As,type:_.literal("subscription_change"),subscriptionId:_.uuid(),merchantSubscriptionId:Dt,membershipId:_.uuid(),subscriptionAction:_.enum(["update","cancel","schedule","release"]),supersedesOperationId:_.uuid().nullable(),change:_.discriminatedUnion("type",[_.strictObject({type:_.literal("cancel")}),_.strictObject({type:_.literal("uncancel")}),_.strictObject({type:_.literal("plan"),productVersionId:_.uuid()}),_.strictObject({type:_.literal("seats"),licenseKey:Dt,quantity:_.number().int().nonnegative().max(1e6)}),_.strictObject({type:_.literal("quantity"),internal_feature_id:_.uuid(),quantity:_.number().int().nonnegative().max(1e6)}),_.strictObject({type:_.literal("billing_cycle"),billingCycleAnchor:_.union([_.literal("now"),_.number().int().positive()])})]),timing:_.enum(["immediate","renewal"]),effectiveAt:Gt,creditMinor:mt,debitMinor:mt,totalMinor:mt,discountMinor:mt,taxMinor:mt,proration:_.enum(["none","create_prorations","always_invoice"]),lineItems:_.array(ol.extend({quantity:_.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:_.array(_.uuid()).max(100)}),_o=_.strictObject({...As,type:_.literal("refund"),invoiceId:_.uuid(),merchantInvoiceId:Dt,amountMinor:mt.refine(e=>e>0),mode:_.enum(["full","partial"]),entitlementAction:_.enum(["retain","revoke"]),cancelSubscriptions:_.array(Dt).max(100)}),al=_.discriminatedUnion("type",[wo,Oo,_o]);var _i=_.strictObject({phase:_.enum(["execution","payment","fulfillment","recording"]),code:Tn,reason:ls.optional(),recovery:us,retryable:_.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),fs={operationId:_.uuid(),customerId:_.uuid(),merchantExecutionId:Dt,fulfillmentStatus:_.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:_.enum(["not_ready","pending","accepted","failed"]),updatedAt:Gt,problem:_i.nullable(),pollAfterMs:_.number().int().min(1e3).max(6e4).nullable()},hr=_.discriminatedUnion("type",[_.strictObject({...fs,type:_.literal("purchase"),merchantOrderId:Dt.nullable(),paymentStatus:_.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:_.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"),_.strictObject({...fs,type:_.literal("subscription_change"),status:_.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Dt,scheduledFor:Gt.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),_.strictObject({...fs,type:_.literal("refund"),status:_.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Dt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),sl=_.discriminatedUnion("lookup",[_.strictObject({lookup:_.literal("found"),operationId:_.uuid(),customerId:_.uuid(),execution:hr,readAt:Gt}),_.strictObject({lookup:_.literal("not_received"),operationId:_.uuid(),customerId:_.uuid(),execution:_.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"),gs=_.strictObject({merchantSubscriptionId:Dt,revision:_.number().int().positive(),status:_.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Gt,periodEndsAt:Gt,cancelAtPeriodEnd:_.boolean(),hasDiscounts:_.boolean(),items:_.array(_.strictObject({merchantItemId:Dt,priceId:_.uuid(),quantity:_.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"),hs=_.strictObject({merchantInvoiceId:Dt,currency:vo,subtotalMinor:mt,discountMinor:mt,taxMinor:mt,totalMinor:mt,paidMinor:mt,periodStartsAt:Gt.nullable(),periodEndsAt:Gt.nullable(),lines:_.array(_.strictObject({merchantLineId:Dt,priceId:_.uuid(),quantity:_.number().int().nonnegative().max(1e6),subtotalMinor:_.number().int().min(-1e8).max(1e8),discountMinor:mt,taxMinor:mt,totalMinor:_.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"),Vr={provider:_.literal("merchant"),eventId:_.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:_.uuid(),occurredAt:Gt},cl=_.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),ul=_.discriminatedUnion("type",[_.strictObject({...Vr,type:_.literal("purchase.completed"),operationId:_.uuid(),merchantOrderId:Dt,paymentStatus:_.enum(["paid","trialing","no_payment_required"]),invoice:hs.nullable(),subscription:gs.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),_.strictObject({...Vr,type:_.literal("purchase.closed"),operationId:_.uuid(),status:_.enum(["failed","expired","canceled"])}),_.strictObject({...Vr,type:_.literal("subscription.observed"),operationId:_.uuid().nullable(),subscription:gs}),_.strictObject({...Vr,type:_.literal("subscription.change.completed"),operationId:_.uuid(),status:_.enum(["scheduled","applied"]),scheduledFor:Gt.nullable(),subscription:gs,invoice:hs.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),_.strictObject({...Vr,type:_.literal("invoice.paid"),merchantSubscriptionId:Dt,invoice:hs}),_.strictObject({...Vr,type:_.literal("refund.updated"),operationId:_.uuid(),merchantRefundId:Dt,status:_.enum(["pending","succeeded","failed"]),amountMinor:mt.refine(e=>e>0),currency:vo})]);import{z as k}from"zod";import{z as Ar}from"zod";var Ft=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Gn=Ar.object({customerId:Ar.uuid(),sessionId:Ar.uuid(),accessToken:Ar.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:Ar.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:Ar.iso.datetime(),refreshExpiresAt:Ar.iso.datetime()});var bs=3;var $h=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],Gh=k.enum($h);var Kh=k.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),dl=k.string().regex(/^[A-Za-z0-9_-]{1,64}$/),Hh=k.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),Qh=k.strictObject({keyId:dl,signingSecret:Hh}),Jh=k.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),pl=k.array(Gh).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),ml=k.strictObject({bridgeVersion:k.literal(bs),projectId:k.uuid(),environmentId:k.uuid(),environment:k.enum(["sandbox","live"]),capabilities:pl,catalog:k.enum(["endpoint","static","none"]),billingEvents:k.array(cl).max(6),profiles:k.array(il).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"})}),fl=k.strictObject({origin:Jh,requiredCapabilities:pl}),Zh=k.strictObject({revision:k.number().int().nonnegative(),checkedAt:k.iso.datetime(),outcome:k.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:k.strictObject({ping:k.enum(["passed","failed","not_checked"]),authentication:k.enum(["passed","failed","not_checked"]),catalog:k.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:ml.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),KI=k.strictObject({projectId:k.uuid(),environmentId:k.uuid(),environment:k.enum(["sandbox","live"]),execution:k.enum(["indiana","record_only"]),accountId:k.string().nullable(),revision:k.number().int().nonnegative(),authentication:k.strictObject({keyId:dl}).nullable(),secretStoreConfigured:k.boolean().optional(),connection:fl.nullable(),check:Zh.nullable()});var ll=k.strictObject({projectId:k.uuid(),environmentId:k.uuid()}),HI=k.discriminatedUnion("action",[ll.extend({action:k.literal("save"),revision:k.number().int().nonnegative(),connection:fl,authentication:Qh.optional()}),ll.extend({action:k.literal("check"),revision:k.number().int().nonnegative()})]),Ss=k.strictObject({projectId:k.uuid(),environmentId:k.uuid(),environment:k.enum(["sandbox","live"])});var Wh=k.strictObject({nativeUserId:k.string().min(1).max(128),session:Gn.strict()}),Yh=k.strictObject({nativeUserId:k.string().min(1).max(128),presentation:k.strictObject({customerId:k.uuid(),decisionId:k.uuid(),offeringVersionId:k.uuid(),paywallVersionId:k.uuid(),variant:k.string().min(1).max(128)}).nullable()}),Xh=k.strictObject({decisionId:k.uuid(),eventId:k.uuid()}),Co=k.strictObject({operationId:k.uuid(),customerId:k.uuid()}),Po=k.strictObject({scope:Ss,operationId:k.uuid(),customerId:k.uuid(),confirmedAt:k.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:k.boolean(),instruction:al}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),ys=hr,Nn=k.string().min(1).max(120),eA=k.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),tA=k.strictObject({revision:Nn,updatedAt:k.iso.datetime(),provider:k.literal("merchant"),items:k.array(k.strictObject({merchantProductId:Nn,productVersionId:k.uuid(),name:k.string().min(1).max(255),kind:k.enum(["subscription","credit_pack"]),merchantPriceId:Nn,currency:k.string().regex(/^[a-z]{3}$/),amountMinor:k.number().int().nonnegative().max(1e8),interval:k.enum(["one_time","month","year"]),intervalCount:k.literal(1),includedCredits:k.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:k.enum(["none","month"]),creditPolicyId:Nn,available:k.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)}),nA=k.strictObject({customerId:k.uuid(),revision:k.string().min(1).max(128),observedAt:k.iso.datetime(),subscriptions:k.array(k.strictObject({merchantSubscriptionId:Nn,merchantProductId:Nn,productVersionId:k.uuid().nullable(),status:k.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:k.iso.datetime().nullable(),currentPeriodEndsAt:k.iso.datetime().nullable(),cancelAtPeriodEnd:k.boolean(),scheduledChange:k.strictObject({effectiveAt:k.iso.datetime(),merchantProductId:Nn}).nullable()})).max(100),purchaseHistory:k.strictObject({complete:k.boolean(),hasPaidPurchase:k.boolean(),lastPaidAt:k.iso.datetime().nullable()}),balances:k.array(k.strictObject({bucketId:Nn,key:Nn,available:eA,expiresAt:k.iso.datetime().nullable(),nextResetAt:k.iso.datetime().nullable()})).max(100)}),QI=k.strictObject({bridgeVersion:k.literal(bs),requestId:k.uuid(),command:k.string().min(1).max(64),scope:Ss,error:k.strictObject({code:k.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:k.string().min(1).max(500),retryable:k.boolean(),recovery:k.string().min(1).max(80)})}),Ci=k.strictObject({}),rA={"bridge.ping":k.strictObject({challenge:k.uuid()}),"bridge.describe":Ci,"session.create":Ci,"catalog.read":Ci,"customer.commerce.read":Ci,"presentation.resolve":Ci,"presentation.report":Xh,"purchase.execute":Co,"operation.read":Co,"subscription.change":Co,"refund.execute":Co},JI={"bridge.ping":k.strictObject({challenge:k.uuid()}),"bridge.describe":ml,"session.create":Wh,"catalog.read":tA,"customer.commerce.read":nA,"presentation.resolve":Yh,"presentation.report":k.strictObject({queued:k.literal(!0)}),"purchase.execute":ys,"operation.read":sl,"subscription.change":ys,"refund.execute":ys},ZI=k.strictObject({bridgeVersion:k.literal(bs),requestId:k.uuid(),scope:Ss,command:Kh,data:k.unknown()}).superRefine((e,t)=>{rA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});import{z as Br}from"zod";var Eo=Br.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"),ev=Br.object({amountCents:Br.number().int().min(0).max(1e8),currency:he,interval:Br.enum(["free","month","year"]),currencyOptions:Br.partialRecord(he,Br.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");import{z as D}from"zod";var iA=D.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),Al=D.enum(["single_use","continuous_use"]),xs=D.record(D.string(),D.union([D.string(),D.number(),D.boolean()]).transform(String).pipe(D.string())),gl=D.string().min(1).max(64).refine(e=>!e.includes("::")),yl={credit_amount:D.number(),tier_behavior:D.never().optional(),tiers:D.never().optional()},bl={credit_amount:D.never().optional(),tier_behavior:D.literal("graduated"),tiers:D.array(D.strictObject({to:D.union([D.number(),D.literal("inf")]),credit_amount:D.number()}))},oA=D.union([D.strictObject({match:xs,priority:D.number().int().optional(),...yl}),D.strictObject({match:xs,priority:D.number().int().optional(),...bl})]),aA=D.strictObject({match:xs,factor:D.number().positive().optional(),add:D.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),hl={metered_feature_id:D.string(),feature_amount:D.number().optional(),dimensions:D.record(gl,oA).optional(),multipliers:D.record(gl,aA).optional()},Is=D.union([D.strictObject({...hl,...yl}),D.strictObject({...hl,...bl})]),ko=D.number().min(-100),Sl=D.record(D.string(),D.strictObject({markup:ko})).nullish(),jo=D.record(D.string().regex(/.+\/.+/),D.strictObject({markup:ko.optional(),input_cost:D.number().min(0).optional(),output_cost:D.number().min(0).optional()})).nullish(),sA=D.strictObject({default_markup:ko.optional(),provider_markups:Sl,model_markups:jo}),rv=D.strictObject({schema:D.array(Is).optional(),markups:sA.optional()}),cA=D.strictObject({filters:D.array(D.strictObject({property:D.string(),operator:D.string(),value:D.array(D.string())})),aggregate:D.strictObject({type:D.string(),property:D.string().nullable()}),usage_type:Al}),xl=D.strictObject({schema:D.array(Is).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.boolean().optional(),usage_type:Al.default("single_use").overwrite(()=>"single_use"),default_markup:ko.optional(),provider_markups:Sl}),vs=xl.safeExtend({schema:D.array(Is).length(0)}),Ro={id:iA,name:D.string().min(1),display:D.strictObject({singular:D.string().optional(),plural:D.string().optional()}).nullish(),event_names:D.array(D.string()).default([]),model_markups:jo,stripe_meter:D.strictObject({id:D.string(),event_name:D.string()}).nullish(),stripe_product_id:D.string().nullish()},ws=e=>D.discriminatedUnion("type",[D.strictObject({...Ro,...e,type:D.literal("boolean"),config:D.null()}),D.strictObject({...Ro,...e,type:D.literal("metered"),config:cA}),D.strictObject({...Ro,...e,type:D.literal("credit_system"),config:xl}),D.strictObject({...Ro,...e,type:D.literal("ai_credit_system"),config:vs})]),iv=ws({}),uA=D.strictObject({id:D.boolean(),type:D.boolean(),usage_type:D.boolean()}),lA={internal_id:D.uuid(),org_id:D.uuid(),created_at:D.number(),env:D.enum(["sandbox","live"]),archived:D.boolean(),project_id:D.uuid(),environment_id:D.uuid(),revision:D.number().int().nonnegative(),update_rules:uA},Il=ws(lA),ov=D.strictObject({rows:D.array(Il).max(200),nextCursor:D.uuid().nullable()}),av=D.strictObject({features:D.array(Il).max(500),limited:D.boolean()}),sv=D.union([ws({action:D.literal("save"),internal_id:D.uuid().nullable(),revision:D.number().int().nonnegative()}),D.strictObject({action:D.enum(["archive","restore","delete"]),internal_id:D.uuid(),revision:D.number().int().nonnegative()})]);import{z as zr}from"zod";import{z as ot}from"zod";var Kt=ot.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),ge=ot.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),To=ot.string().regex(/^-?(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>{let t=e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e;return t==="-0"?"0":t}),Os=ge.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),vl=ot.string().min(1).max(64),yr=ot.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),wl=ot.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),gt=ot.record(vl,ot.union([ot.string().max(120),ot.number().finite(),ot.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)]))),Ol=ot.record(vl,ot.union([ot.string().max(120),ot.number().finite(),ot.boolean()]).transform(String)).refine(e=>Object.keys(e).length<=8,"\u5339\u914D\u6761\u4EF6\u6700\u591A 8 \u4E2A\u5C5E\u6027"),Ur=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},_l=ot.array(ot.object({upTo:Os.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&&Ur(t.upTo)>Ur(r))}),"\u9636\u68AF\u4E0A\u9650\u5FC5\u987B\u9012\u589E\uFF0C\u6700\u540E\u4E00\u6863\u4E3A\u65E0\u9650"),dA=ot.object({key:wl,match:Ol,priority:ot.number().int().default(0),cost:ge.optional(),tiers:_l.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),pA=ot.object({key:wl,match:Ol,factor:Os.optional(),add:To.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"})),mA=ot.object({units:Os.default("1"),cost:ge,tiers:_l.optional(),dimensions:ot.array(dA).max(12).optional(),multipliers:ot.array(pA).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=Ur(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(I=>f.match[I]!==void 0&&f.match[I]!==p.match[I]))))continue;let u=Ur(o),l=BigInt("1"),m=BigInt("0");for(let[p,g]of r.entries())s&1<<p&&(u*=Ur(g.factor??"1"),l*=BigInt("1000000"),m+=Ur(g.add??"0"));let S=(u+m*l)*BigInt("1000000"),y=l*a;(S<BigInt("0")||S%y!==BigInt("0")||S/y>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"})}}),lv=mA.safeExtend({featureKey:yr});import{z as Lr}from"zod";var Cl=Lr.number().int().min(0).max(1e8),Pi=Lr.strictObject({kind:Lr.enum(["graduated","volume"]),tiers:Lr.array(Lr.strictObject({upTo:Lr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Cl,flatAmountMinor:Cl.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 _s(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?Pi.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 No(e){return _s({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var fA=ge.refine(e=>/[1-9]/.test(e)),Do=zr.strictObject({units:fA,prices:zr.array(zr.strictObject({currency:he,amountMinor:zr.number().int().min(0).max(1e8),pricing:Pi.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:zr.number().int().min(0).max(1e4),maximumQuantity:zr.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&&_s({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 Pl(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 El(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Pl(e)+Pl(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:"")}import{z as h}from"zod";import{z as X}from"zod";import{z as Ct}from"zod";import{z as j}from"zod";function Rl(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 Fo(e,t,n){return n===2?Rl(Rl(e+t)+"")%1e4/1e4:null}function gA(e){return e<=0?[]:new Array(e).fill(1/e)}function Mo(e,t){return e>=t[0]&&e<t[1]}function kl(e,t){for(let[n,r]of t.entries())if(Mo(e,r))return n;return-1}function jl(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=gA(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 Tl(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 Nl(e){try{return e()}catch{return!1}}function Ei(e){return typeof e=="string"?e:JSON.stringify(e)}function Xt(e){typeof e=="number"&&(e=e+""),(!e||typeof e!="string")&&(e="0");let t=e.replace(/(^v|\+.*$)/g,"").split(/[-.]/);return t.length===3&&t.push("~"),t.map(n=>n.match(/^[0-9]+$/)?n.padStart(5," "):n).join("-")}function hA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function Dl(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=bA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function AA(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 yA(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=>!AA(i[0],i[1],i[2]))}catch{return!1}}function bA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=hA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return yA(r,n);return!1}catch{return!1}}function Cs(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 qo(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 Fl(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);qo(e.savedGroups??{})}var SA=e=>e/2**32|0,xA=e=>e>>>0;function Ml(e,t,n,r){let i=SA(n),a=xA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function ql(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ps=e=>e?`"${e}" `:"";function IA(e,t=""){if(typeof e!="number")throw new TypeError(Ps(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ps(t)+"expected integer >= 0, got "+e);return e}function Vo(e,t,n=""){if(ql(e)&&(t===void 0||e.length===t))return e;t!==void 0&&IA(t,"length");let r=ql(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=Ps(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var vA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Vl=(e,t)=>{vA(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 Es(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function Bl(e,t){Vo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Rs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Bo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function fn(e,t){return e<<32-t|e>>>t}var wA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",OA=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function $r(e){if(Vo(e),wA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=OA[e[n]];return t}function _A(e,t,n="opts"){return Vl(e,"defaults"),t!==void 0&&Vl(t,n),Object.assign(Object.create(null),e,t)}function Ul(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=_A({},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 Ll=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function zl(e,t,n){return e&t^~e&n}function $l(e,t,n){return e&t^e&n^t&n}var Uo=class{constructor(t,n,r,i){De(this,"blockLen");De(this,"outputLen");De(this,"canXOF",!1);De(this,"padOffset");De(this,"isLE");De(this,"buffer");De(this,"view");De(this,"finished",!1);De(this,"length",0);De(this,"pos",0);De(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Bo(this.buffer)}update(t){Es(this),Vo(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=Bo(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){Es(this),Bl(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)),Ml(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:Bo(t),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");for(let m=0;m<u;m++)s.setUint32(4*m,l[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()}},Gl=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var CA=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]),Kn=new Uint32Array(64),ks=class extends Uo{constructor(n,r){super(64,n,8,!1);De(this,"A",0);De(this,"B",0);De(this,"C",0);De(this,"D",0);De(this,"E",0);De(this,"F",0);De(this,"G",0);De(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 S=0;S<16;S++,r+=4)Kn[S]=n.getUint32(r,!1);for(let S=16;S<64;S++){let y=Kn[S-15],p=Kn[S-2],g=fn(y,7)^fn(y,18)^y>>>3,f=fn(p,17)^fn(p,19)^p>>>10;Kn[S]=f+Kn[S-7]+g+Kn[S-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:l,H:m}=this;for(let S=0;S<64;S++){let y=fn(c,6)^fn(c,11)^fn(c,25),p=m+y+zl(c,u,l)+CA[S]+Kn[S]|0,f=(fn(i,2)^fn(i,13)^fn(i,22))+$l(i,a,o)|0;m=l,l=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,l=l+this.G|0,m=m+this.H|0,this.set(i,a,o,s,c,u,l,m)}roundClean(){Rs(Kn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Rs(this.buffer)}},js=class extends ks{constructor(){super(32,Gl)}};var Gr=Ul(()=>new js,Ll(1));var Kl=new Map,Ts=32,Hl=new WeakMap,Ql=new WeakMap;function PA(e){return $r(Gr(new TextEncoder().encode(String(e))))}var zo=e=>Array.isArray(e)?e.map(zo):typeof e=="string"||typeof e=="number"?PA(e):null,Lo=e=>typeof e=="string"?e.toLowerCase():e;function Xl(e){let t=Hl.get(e);return t||(t=new Set(e),Hl.set(e,t)),t}function EA(e){let t=Ql.get(e);return t||(t=new Set(e.map(Lo)),Ql.set(e,t)),t}function Kr(e){qo(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=Ts&&Xl(n)}return e}function Qt(e,t,n,r){n=n||{},r||qo(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!Yl(e,a,n,r))return!1;break;case"$nor":if(Yl(e,a,n,r))return!1;break;case"$and":if(!NA(e,a,n,r))return!1;break;case"$not":if(Qt(e,a,n,r))return!1;break;case"$savedGroup":if(!RA(e,a,n,r))return!1;break;default:if(!Ri(a,ed(e,i),n,!1,r))return!1}return!0}function RA(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=ed(e,c);return br(o.type==="hashed"?zo(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:Qt(e,o.condition,n,s):!1}function ed(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 Jl(e,t=!1){let n=`${e}${t?"/i":""}`,r=Kl.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),Kl.set(n,r)),r}function Ri(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)||!td(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!TA(o,t,a[o],n,i))return!1;return!0}function td(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function kA(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 jA(e,t,n,r){if(!Array.isArray(e))return!1;let i=td(t)?a=>Ri(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 br(e,t,n=!1){if(n){let i;if(t.length>=Ts){let a=EA(t);i=o=>{let s=Lo(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Lo(a)===Lo(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=Ts?(i=>a=>i.has(a))(Xl(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function Zl(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function Wl(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(Ri(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function TA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return Xt(t)===Xt(n);case"$vne":return Xt(t)!==Xt(n);case"$vgt":return Xt(t)>Xt(n);case"$vgte":return Xt(t)>=Xt(n);case"$vlt":return Xt(t)<Xt(n);case"$vlte":return Xt(t)<=Xt(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)?br(t,n):!1;case"$ini":return Array.isArray(n)?br(t,n,!0):!1;case"$inGroup":{let s=r[n],c=Zl(s);return c===null?!1:br(s?.type==="hashed"?zo(t):t,c)}case"$notInGroup":{let s=r[n],c=Zl(s);return c===null?!1:!br(s?.type==="hashed"?zo(t):t,c)}case"$nin":return Array.isArray(n)?!br(t,n):!1;case"$nini":return Array.isArray(n)?!br(t,n,!0):!1;case"$not":return!Ri(n,t,r,!1,i);case"$size":return Array.isArray(t)?Ri(n,t.length,r,!1,i):!1;case"$elemMatch":return jA(t,n,r,i);case"$all":return Array.isArray(n)?Wl(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?Wl(t,n,r,!0,i):!1;case"$regex":try{return Jl(n).test(t)}catch{return!1}case"$regexi":try{return Jl(n,!0).test(t)}catch{return!1}case"$type":return kA(t)===n;default:return!1}}function Yl(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 NA(e,t,n,r){for(let i of t)if(!Qt(e,i,n,r))return!1;return!0}function Ns(e){return Fl(e),{context:e,stack:{evaluatedFeatures:new Set}}}function Ds(e){return{...e.attributes,...e.attributeOverrides}}function Hn(e,t,n){let r=t||"id",i="",a=Ds(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function He(e,t,n){e.context.log?.(t,n)}function $o(e,t){return t=t||0,`${e}__${t}`}function Fs(e,t){return`${e}||${t}`}function DA(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Hn(e,t),o=Fs(i,Ei(a)),{hashAttribute:s,hashValue:c}=Hn(e,n),u=c?Fs(s,Ei(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function nd({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=$o(t,n),c=DA(e,r,i);if(a>0)for(let m=0;m<a;m++){let S=$o(t,m);if(c[S]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let l=o.findIndex(m=>m.key===u);return l<0?{variation:-1}:{variation:l}}function rd(e,t,n,r){let i=Fs(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 id(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function Go(e,t){let n=Ns(t),r=ad(e,null,n);return t.onExperimentEval?.(e,r),r}function Dn(e,t){return qs(e,Ns(t))}function FA(e){return e.forcedVariations||{}}function od(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=ud(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Ms(()=>r.onExperimentViewed?.(t,n))}function MA(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}Ms(()=>r.onFeatureUsage?.(t,n))}function Ms(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function qs(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return He(t,`evalFeature: circular dependency detected: ${t.stack.id} -> ${e}`,{from:t.stack.id,to:e}),Qn(t,e,null,"cyclicPrerequisite");t.stack.evaluatedFeatures.add(e),t.stack.id=e;let r=n.features?.[e];for(let a of r?.rules??[])Cs(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return He(t,"Global override",{id:e,value:i.get(e)}),Qn(t,e,i.get(e),"override");if(!r)return He(t,"Unknown feature",{id:e}),Qn(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 l=qs(u.id,t);if(l.source==="cyclicPrerequisite")return Qn(t,e,null,"cyclicPrerequisite");let m={value:l.value};if(!Qt(m,u.condition||{},n.savedGroups||{})){if(u.gate)return He(t,"Feature blocked by prerequisite",{id:e,rule:o}),Qn(t,e,null,"prerequisite");He(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&cd(o.filters,t)){He(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!sd(o.condition,t)){He(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!qA(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){He(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return He(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{od(t,u.experiment,u.result)}),Qn(t,e,o.force,"force",o.id)}if(!o.variations){He(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=ad(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Qn(t,e,c.value,"experiment",o.id,s,c)}}return He(t,"Use default value",{id:e,value:r.defaultValue}),Qn(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function ad(e,t,n){let{context:r}=n;Cs(e);let i=e.key,a=e.variations.length;if(a<2)return He(n,"Invalid experiment",{id:i}),_t(n,e,-1,!1,t);if(r.enabled===!1)return He(n,"Context disabled",{id:i}),_t(n,e,-1,!1,t);if(e.urlPatterns&&!Dl(r.url||"",e.urlPatterns))return He(n,"Skip because of url targeting",{id:i}),_t(n,e,-1,!1,t);let o=Tl(i,r.url||"",a);if(o!==null)return He(n,"Force via querystring",{id:i,variation:o}),_t(n,e,o,!1,t);let c=FA(r)[i];if(c!==void 0)return He(n,"Force via dev tools",{id:i,variation:c}),_t(n,e,c,!1,t);if(e.active===!1)return He(n,"Skip because inactive",{id:i}),_t(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=Hn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return He(n,"Skip because missing hashAttribute",{id:i}),_t(n,e,-1,!1,t);let m=-1,S=!1,y=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:f,versionIsBlocked:I}=nd(id({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));S=f>=0,m=f,y=!!I}if(!S){if(e.filters&&cd(e.filters,n))return He(n,"Skip because of filters",{id:i}),_t(n,e,-1,!1,t);if(e.include&&!Nl(e.include))return He(n,"Skip because of include function",{id:i}),_t(n,e,-1,!1,t);if(e.condition&&!sd(e.condition,n))return He(n,"Skip because of condition exp",{id:i}),_t(n,e,-1,!1,t);if(e.parentConditions){let f=new Set(n.stack.evaluatedFeatures);for(let I of e.parentConditions){n.stack.evaluatedFeatures=new Set(f);let A=qs(I.id,n);if(A.source==="cyclicPrerequisite")return _t(n,e,-1,!1,t);let P={value:A.value};if(!Qt(P,I.condition||{},r.savedGroups||{}))return He(n,"Skip because prerequisite evaluation fails",{id:i}),_t(n,e,-1,!1,t)}}}let p=Fo(e.seed||i,l,e.hashVersion??2);if(p===null)return He(n,"Skip because of invalid hash version",{id:i}),_t(n,e,-1,!1,t);if(!S){let f=e.ranges||jl(a,e.coverage===void 0?1:e.coverage,e.weights);m=kl(p,f)}if(y)return He(n,"Skip because sticky bucket version is blocked",{id:i}),_t(n,e,-1,!1,t,void 0,!0);if(m<0)return He(n,"Skip because of coverage",{id:i}),_t(n,e,-1,!1,t);if("force"in e)return He(n,"Force variation",{id:i,variation:e.force}),_t(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return He(n,"Skip because QA mode",{id:i}),_t(n,e,-1,!1,t);let g=_t(n,e,m,!0,t,p,S);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:f,key:I,doc:A}=rd(r,u,Ei(l),{[$o(e.key,e.bucketVersion)]:g.key});if(f){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[I]=A;let P=r.saveStickyBucketAssignmentDoc;Ms(()=>P(A))}}return od(n,e,g),He(n,"In experiment",{id:i,variation:g.variationId}),g}function Qn(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"&&MA(e,t,s),s}function sd(e,t){return Qt(Ds(t.context),e,t.context.savedGroups||{})}function cd(e,t){return e.some(n=>{let{hashValue:r}=Hn(t.context,n.attribute);if(!r)return!0;let i=Fo(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>Mo(i,a))})}function qA(e,t,n,r,i,a,o){if(!i&&a===void 0)return!0;if(!i&&a===0)return!1;let{hashValue:s}=Hn(e.context,n,r);if(!s)return!1;let c=Fo(t,s,o??2);return c===null?!1:i?Mo(c,i):a!==void 0?c<=a:!0}function _t(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}=Hn(e.context,t.hashAttribute,e.context.saveStickyBucketAssignmentDoc&&!t.disableStickyBucketing?t.fallbackAttribute:void 0),l=t.meta?.[n]??{},m=t.variations[0];for(let[y,p]of t.variations.entries())if(y===n){m=p;break}let S={key:l.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:m,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return l.name&&(S.name=l.name),a!==void 0&&(S.bucket=a),l.passthrough&&(S.passthrough=l.passthrough),S}function ud(e,t){return t.hashAttribute+t.hashValue+e.key+t.variationId}/*!
1
+ var eA=Object.defineProperty;var tA=(e,t,n)=>t in e?eA(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Fe=(e,t,n)=>tA(e,typeof t!="symbol"?t+"":t,n);import{z as gs}from"zod";var nA=gs.enum(["sandbox","live"]),je=gs.object({projectId:gs.string().min(1),environment:nA}).strict();import{z as ze}from"zod";var ki=ze.number().int().min(1).max(Number.MAX_SAFE_INTEGER),ol=ze.enum(["unknown","denied","provisional","granted"]),al=ze.enum(["ios","android"]),Eo=ze.strictObject({installationId:ze.uuid(),publicKey:ze.string().regex(/^[A-Za-z0-9_-]{80,200}$/),issuedAt:ze.iso.datetime({offset:!0}),signature:ze.string().regex(/^[A-Za-z0-9_-]{86}$/)}),hs=ze.string().regex(/^[a-f0-9]{64}$/),sl=Eo.extend({sequence:ki,platform:al,credentialDigest:hs}),cl=Eo.extend({credentialDigest:hs}),ul=Eo.extend({sequence:ki,platform:al}),Ro=Eo.extend({sequence:ki,credentialDigest:hs,connectionId:ze.uuid().nullable(),kind:ze.enum(["fcm_token","apns_token"]).nullable(),token:ze.string().regex(/^[\x21-\x7e]{16,4096}$/).nullable(),permission:ol}),ll=Ro,dl=Ro.extend({challenge:ze.string().regex(/^[A-Za-z0-9_-]{100,3500}$/)}),As=ze.strictObject({requested:ze.literal(!0),expiresAt:ze.iso.datetime({offset:!0})}),Ar=ze.strictObject({installationId:ze.uuid(),bound:ze.boolean(),identitySeq:ki,bindingGeneration:ki,addressSeq:ze.number().int().min(0).max(Number.MAX_SAFE_INTEGER),addressRevision:ze.number().int().min(0).max(Number.MAX_SAFE_INTEGER),connectionId:ze.uuid().nullable(),addressStatus:ze.enum(["active","invalid"]).nullable(),permission:ol}),ys=ze.strictObject({channel:ze.enum(["email","sms","voice","push"]),state:ze.enum(["unknown","allowed","denied"]),revision:ze.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:ze.iso.datetime({offset:!0}).nullable()}),ev=ze.strictObject({state:ze.enum(["allowed","denied"]),revision:ze.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)});function pl(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))}import{z as Ct}from"zod";var qn=Ct.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"]),rv=Ct.enum([...qn.options,"INVALID_SERVER_RESPONSE","RESPONSE_TOO_LARGE","AMBIGUOUS_AUTHENTICATION","BROWSER_REQUIRED","INVALID_REDIRECT_URI","AUTHORIZATION_UNAVAILABLE","UNREGISTERED_CLIENT","MANAGEMENT_OPERATION_FAILED"]),iv=Ct.enum([...qn.options,"stale_revision"]),bs=Ct.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"]),xs=Ct.enum(["CAPABILITY_NOT_ENABLED","INTEGRATION_MISSING","PROVIDER_CREDENTIAL_REJECTED","PRICE_BINDING_REQUIRED","IDEMPOTENCY_CONFLICT","RESULT_UNKNOWN","STATE_CHANGED","IDENTITY_CONTEXT_CHANGED","CUSTOMER_BINDING_CONFLICT","RUN_CONTRACT_MISMATCH","OPERATION_IN_PROGRESS","FUNNEL_VERSION_RETIRED"]),fl={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 ml={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 rA(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(ml,e)){let r=ml[e];return{retryable:r==="retry_same_request",recovery:r}}let n=qn.safeParse(e);return n.success?{retryable:e==="RATE_LIMITED"||e==="SERVICE_UNAVAILABLE",recovery:fl[n.data].recovery}:{retryable:!1,recovery:"contact_support"}}function gl(e,t){let n=qn.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):fl[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 iA(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 hl=Ct.object({retryable:Ct.boolean(),recovery:bs,reason:xs.optional(),retryAfterSeconds:Ct.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()}),Ss=Ct.object({requestId:Ct.uuid().optional(),error:Ct.object({code:Ct.string().regex(/^[A-Z][A-Z0-9_]{0,95}$/),message:Ct.string(),...hl.partial().shape})}),ov=Ct.object({error:Ss.shape.error.extend({requestId:Ct.uuid().optional()})}),av=Ct.object({error:Ct.string(),code:Ct.string().regex(/^[A-Za-z][A-Za-z0-9_]{0,95}$/),requestId:Ct.uuid(),...hl.shape});function ko(e,t,n={}){let r=rA(e,t),i=n.reason==="RESULT_UNKNOWN"?"recover_operation":n.recovery??r.recovery,a=r.retryable&&n.retryable!==!1&&i!=="recover_operation",o=a?iA(n.retryAfter??null):void 0;return{...r,retryable:a,recovery:i,...o===void 0?{}:{retryAfterSeconds:o},...n.reason?{reason:n.reason}:{}}}var Is="X-Indiana-Protocol",Al="X-Indiana-SDK-Version";var vs={current:"0.10"};import{z as oA}from"zod";var aA=["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"],be=oA.enum(aA);import{z as P}from"zod";var Bt=P.string().min(1).max(200),Ht=P.iso.datetime({offset:!0}),At=P.number().int().nonnegative().max(1e8),jo=P.string().regex(/^[A-Z]{3}$/),sA=["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"],yl=P.enum(sA),bl=P.strictObject({priceId:P.uuid(),productVersionId:P.uuid(),productId:Bt,quantity:P.number().int().min(1).max(1e6),unitAmountMinor:At,totalMinor:At,interval:P.enum(["week","month","year","one_off"]),intervalCount:P.number().int().min(1).max(52),kind:P.enum(["fixed","prepaid","seat"]),tiers:P.strictObject({mode:P.enum(["graduated","volume"]),tiers:P.array(P.strictObject({upTo:P.number().int().positive().nullable(),unitAmountMinor:At,flatAmountMinor:At.optional()})).min(2).max(12)}).nullable()}),cA=P.strictObject({grantId:P.uuid(),couponId:P.uuid(),amountMinor:At,terms:P.discriminatedUnion("type",[P.strictObject({type:P.literal("percent"),percentOff:P.number().gt(0).max(100)}),P.strictObject({type:P.literal("amount"),amountOffMinor:At,currency:jo})]),duration:P.discriminatedUnion("type",[P.strictObject({type:P.literal("once")}),P.strictObject({type:P.literal("forever")}),P.strictObject({type:P.literal("repeating"),months:P.number().int().min(1).max(36)})])}),Cs={provider:P.literal("merchant"),executor:P.literal("merchant"),operationId:P.uuid(),customerId:P.uuid(),configurationRevision:P.number().int().nonnegative(),connectionRevision:P.number().int().nonnegative(),currency:jo,expiresAt:Ht},To=P.strictObject({...Cs,type:P.literal("purchase"),mode:P.enum(["payment","subscription"]),lineItems:P.array(bl).min(1).max(100),catalogAmountMinor:At,discount:cA.nullable(),trialPeriodDays:P.number().int().min(1).max(730).nullable(),automaticTax:P.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"),No=P.strictObject({...Cs,type:P.literal("subscription_change"),subscriptionId:P.uuid(),merchantSubscriptionId:Bt,membershipId:P.uuid(),subscriptionAction:P.enum(["update","cancel","schedule","release"]),supersedesOperationId:P.uuid().nullable(),change:P.discriminatedUnion("type",[P.strictObject({type:P.literal("cancel")}),P.strictObject({type:P.literal("uncancel")}),P.strictObject({type:P.literal("plan"),productVersionId:P.uuid()}),P.strictObject({type:P.literal("seats"),licenseKey:Bt,quantity:P.number().int().nonnegative().max(1e6)}),P.strictObject({type:P.literal("quantity"),internal_feature_id:P.uuid(),quantity:P.number().int().nonnegative().max(1e6)}),P.strictObject({type:P.literal("billing_cycle"),billingCycleAnchor:P.union([P.literal("now"),P.number().int().positive()])})]),timing:P.enum(["immediate","renewal"]),effectiveAt:Ht,creditMinor:At,debitMinor:At,totalMinor:At,discountMinor:At,taxMinor:At,proration:P.enum(["none","create_prorations","always_invoice"]),lineItems:P.array(bl.extend({quantity:P.number().int().nonnegative().max(1e6)})).max(100),removePriceIds:P.array(P.uuid()).max(100)}),Do=P.strictObject({...Cs,type:P.literal("refund"),invoiceId:P.uuid(),merchantInvoiceId:Bt,amountMinor:At.refine(e=>e>0),mode:P.enum(["full","partial"]),entitlementAction:P.enum(["retain","revoke"]),cancelSubscriptions:P.array(Bt).max(100)}),xl=P.discriminatedUnion("type",[To,No,Do]);var ji=P.strictObject({phase:P.enum(["execution","payment","fulfillment","recording"]),code:qn,reason:xs.optional(),recovery:bs,retryable:P.boolean()}).refine(e=>e.reason!=="RESULT_UNKNOWN"||!e.retryable&&e.recovery==="recover_operation","Unknown financial effects require recovery of the original operation"),ws={operationId:P.uuid(),customerId:P.uuid(),merchantExecutionId:Bt,fulfillmentStatus:P.enum(["not_started","pending","applied","failed","not_applicable"]),recordingStatus:P.enum(["not_ready","pending","accepted","failed"]),updatedAt:Ht,problem:ji.nullable(),pollAfterMs:P.number().int().min(1e3).max(6e4).nullable()},yr=P.discriminatedUnion("type",[P.strictObject({...ws,type:P.literal("purchase"),merchantOrderId:Bt.nullable(),paymentStatus:P.enum(["not_started","pending","succeeded","not_required","failed","expired","unknown"]),checkoutUrl:P.url().refine(e=>new URL(e).protocol==="https:").nullable(),checkoutExpiresAt:Ht.nullable()}).refine(e=>!e.checkoutUrl||["not_started","pending"].includes(e.paymentStatus)&&e.checkoutExpiresAt!==null,"Only an unfinished original purchase may expose its checkout"),P.strictObject({...ws,type:P.literal("subscription_change"),status:P.enum(["pending","scheduled","applied","failed","unknown"]),merchantSubscriptionId:Bt,scheduledFor:Ht.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"A scheduled change retains its future effective time"),P.strictObject({...ws,type:P.literal("refund"),status:P.enum(["pending","succeeded","failed","unknown"]),merchantRefundId:Bt.nullable()}).refine(e=>e.status!=="succeeded"||e.merchantRefundId!==null,"A successful refund retains its original merchant identity")]),Sl=P.discriminatedUnion("lookup",[P.strictObject({lookup:P.literal("found"),operationId:P.uuid(),customerId:P.uuid(),execution:yr,readAt:Ht}),P.strictObject({lookup:P.literal("not_received"),operationId:P.uuid(),customerId:P.uuid(),execution:P.null(),readAt:Ht})]).refine(e=>!e.execution||e.execution.operationId===e.operationId&&e.execution.customerId===e.customerId,"Lookup must retain the original Customer and operation"),Os=P.strictObject({merchantSubscriptionId:Bt,revision:P.number().int().positive(),status:P.enum(["incomplete","trialing","active","past_due","canceled","unpaid","paused","incomplete_expired"]),periodStartsAt:Ht,periodEndsAt:Ht,cancelAtPeriodEnd:P.boolean(),hasDiscounts:P.boolean(),items:P.array(P.strictObject({merchantItemId:Bt,priceId:P.uuid(),quantity:P.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"),Ps=P.strictObject({merchantInvoiceId:Bt,currency:jo,subtotalMinor:At,discountMinor:At,taxMinor:At,totalMinor:At,paidMinor:At,periodStartsAt:Ht.nullable(),periodEndsAt:Ht.nullable(),lines:P.array(P.strictObject({merchantLineId:Bt,priceId:P.uuid(),quantity:P.number().int().nonnegative().max(1e6),subtotalMinor:P.number().int().min(-1e8).max(1e8),discountMinor:At,taxMinor:At,totalMinor:P.number().int().min(-1e8).max(2e8),periodStartsAt:Ht.nullable(),periodEndsAt:Ht.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"),Gr={provider:P.literal("merchant"),eventId:P.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),customerId:P.uuid(),occurredAt:Ht},Il=P.enum(["purchase.completed","purchase.closed","subscription.observed","subscription.change.completed","invoice.paid","refund.updated"]),vl=P.discriminatedUnion("type",[P.strictObject({...Gr,type:P.literal("purchase.completed"),operationId:P.uuid(),merchantOrderId:Bt,paymentStatus:P.enum(["paid","trialing","no_payment_required"]),invoice:Ps.nullable(),subscription:Os.nullable()}).refine(e=>e.paymentStatus!=="paid"||e.invoice!==null,"A paid purchase includes its Invoice"),P.strictObject({...Gr,type:P.literal("purchase.closed"),operationId:P.uuid(),status:P.enum(["failed","expired","canceled"])}),P.strictObject({...Gr,type:P.literal("subscription.observed"),operationId:P.uuid().nullable(),subscription:Os}),P.strictObject({...Gr,type:P.literal("subscription.change.completed"),operationId:P.uuid(),status:P.enum(["scheduled","applied"]),scheduledFor:Ht.nullable(),subscription:Os,invoice:Ps.nullable()}).refine(e=>e.status==="scheduled"==(e.scheduledFor!==null),"Scheduled and applied changes are distinct facts"),P.strictObject({...Gr,type:P.literal("invoice.paid"),merchantSubscriptionId:Bt,invoice:Ps}),P.strictObject({...Gr,type:P.literal("refund.updated"),operationId:P.uuid(),merchantRefundId:Bt,status:P.enum(["pending","succeeded","failed"]),amountMinor:At.refine(e=>e>0),currency:jo})]);import{z as T}from"zod";import{z as br}from"zod";var Et=/^gg_ct_[A-Za-z0-9_-]{32,128}$/,Kn=br.object({customerId:br.uuid(),sessionId:br.uuid(),accessToken:br.string().regex(/^gg_ct_[A-Za-z0-9_-]{43}$/),refreshToken:br.string().regex(/^gg_rt_[A-Za-z0-9_-]{43}$/),expiresAt:br.iso.datetime(),refreshExpiresAt:br.iso.datetime()});var Es=3;var uA=["session","catalog","customer_commerce","presentation","presentation_events","purchases","operation_status","billing_records","subscription_changes","refunds"],lA=T.enum(uA);var dA=T.enum(["bridge.ping","bridge.describe","session.create","catalog.read","customer.commerce.read","presentation.resolve","presentation.report","purchase.execute","operation.read","subscription.change","refund.execute"]),Ol=T.string().regex(/^[A-Za-z0-9_-]{1,64}$/),pA=T.string().regex(/^[A-Za-z0-9_-]{43}$/).refine(e=>"AEIMQUYcgkosw048".includes(e.at(-1)),"Use canonical base64url for a 32-byte key"),mA=T.strictObject({keyId:Ol,signingSecret:pA}),fA=T.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),Pl=T.array(lA).max(10).refine(e=>new Set(e).size===e.length,"Capabilities must be unique"),Cl=T.strictObject({bridgeVersion:T.literal(Es),projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"]),capabilities:Pl,catalog:T.enum(["endpoint","static","none"]),billingEvents:T.array(Il).max(6),profiles:T.array(yl).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"})}),_l=T.strictObject({origin:fA,requiredCapabilities:Pl}),gA=T.strictObject({revision:T.number().int().nonnegative(),checkedAt:T.iso.datetime(),outcome:T.enum(["valid","unreachable","invalid","scope_mismatch","authentication_failed","credentials_missing"]),diagnostics:T.strictObject({ping:T.enum(["passed","failed","not_checked"]),authentication:T.enum(["passed","failed","not_checked"]),catalog:T.enum(["passed","failed","not_checked","static","unsupported"])}),manifest:Cl.nullable()}).superRefine((e,t)=>{e.outcome==="valid"!=(e.manifest!==null)&&t.addIssue({code:"custom",path:["manifest"],message:"Only a valid declaration carries a manifest"})}),bv=T.strictObject({projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"]),execution:T.enum(["indiana","record_only"]),accountId:T.string().nullable(),revision:T.number().int().nonnegative(),authentication:T.strictObject({keyId:Ol}).nullable(),secretStoreConfigured:T.boolean().optional(),connection:_l.nullable(),check:gA.nullable()});var wl=T.strictObject({projectId:T.uuid(),environmentId:T.uuid()}),xv=T.discriminatedUnion("action",[wl.extend({action:T.literal("save"),revision:T.number().int().nonnegative(),connection:_l,authentication:mA.optional()}),wl.extend({action:T.literal("check"),revision:T.number().int().nonnegative()})]),Rs=T.strictObject({projectId:T.uuid(),environmentId:T.uuid(),environment:T.enum(["sandbox","live"])});var hA=T.strictObject({nativeUserId:T.string().min(1).max(128),session:Kn.strict()}),AA=T.strictObject({nativeUserId:T.string().min(1).max(128),presentation:T.strictObject({customerId:T.uuid(),decisionId:T.uuid(),offeringVersionId:T.uuid(),paywallVersionId:T.uuid(),variant:T.string().min(1).max(128)}).nullable()}),yA=T.strictObject({decisionId:T.uuid(),eventId:T.uuid()}),Fo=T.strictObject({operationId:T.uuid(),customerId:T.uuid()}),Mo=T.strictObject({scope:Rs,operationId:T.uuid(),customerId:T.uuid(),confirmedAt:T.iso.datetime({offset:!0}).nullable(),initialExecutionAllowed:T.boolean(),instruction:xl}).refine(e=>e.operationId===e.instruction.operationId&&e.customerId===e.instruction.customerId,"Authority must refer to the original Customer and operation"),_s=yr,Bn=T.string().min(1).max(120),bA=T.string().regex(/^-?[0-9]+(?:\.[0-9]{1,6})?$/),xA=T.strictObject({revision:Bn,updatedAt:T.iso.datetime(),provider:T.literal("merchant"),items:T.array(T.strictObject({merchantProductId:Bn,productVersionId:T.uuid(),name:T.string().min(1).max(255),kind:T.enum(["subscription","credit_pack"]),merchantPriceId:Bn,currency:T.string().regex(/^[a-z]{3}$/),amountMinor:T.number().int().nonnegative().max(1e8),interval:T.enum(["one_time","month","year"]),intervalCount:T.literal(1),includedCredits:T.string().regex(/^[0-9]{1,18}(?:\.[0-9]{1,6})?$/),creditReset:T.enum(["none","month"]),creditPolicyId:Bn,available:T.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)}),SA=T.strictObject({customerId:T.uuid(),revision:T.string().min(1).max(128),observedAt:T.iso.datetime(),subscriptions:T.array(T.strictObject({merchantSubscriptionId:Bn,merchantProductId:Bn,productVersionId:T.uuid().nullable(),status:T.enum(["active","trialing","past_due","cancelled","expired"]),currentPeriodStartsAt:T.iso.datetime().nullable(),currentPeriodEndsAt:T.iso.datetime().nullable(),cancelAtPeriodEnd:T.boolean(),scheduledChange:T.strictObject({effectiveAt:T.iso.datetime(),merchantProductId:Bn}).nullable()})).max(100),purchaseHistory:T.strictObject({complete:T.boolean(),hasPaidPurchase:T.boolean(),lastPaidAt:T.iso.datetime().nullable()}),balances:T.array(T.strictObject({bucketId:Bn,key:Bn,available:bA,expiresAt:T.iso.datetime().nullable(),nextResetAt:T.iso.datetime().nullable()})).max(100)}),Sv=T.strictObject({bridgeVersion:T.literal(Es),requestId:T.uuid(),command:T.string().min(1).max(64),scope:Rs,error:T.strictObject({code:T.string().regex(/^MERCHANT_BRIDGE_[A-Z_]+$/),message:T.string().min(1).max(500),retryable:T.boolean(),recovery:T.string().min(1).max(80)})}),Ti=T.strictObject({}),IA={"bridge.ping":T.strictObject({challenge:T.uuid()}),"bridge.describe":Ti,"session.create":Ti,"catalog.read":Ti,"customer.commerce.read":Ti,"presentation.resolve":Ti,"presentation.report":yA,"purchase.execute":Fo,"operation.read":Fo,"subscription.change":Fo,"refund.execute":Fo},Iv={"bridge.ping":T.strictObject({challenge:T.uuid()}),"bridge.describe":Cl,"session.create":hA,"catalog.read":xA,"customer.commerce.read":SA,"presentation.resolve":AA,"presentation.report":T.strictObject({queued:T.literal(!0)}),"purchase.execute":_s,"operation.read":Sl,"subscription.change":_s,"refund.execute":_s},vv=T.strictObject({bridgeVersion:T.literal(Es),requestId:T.uuid(),scope:Rs,command:dA,data:T.unknown()}).superRefine((e,t)=>{IA[e.command].safeParse(e.data).success||t.addIssue({code:"custom",path:["data"],message:"Invalid command data"})});import{z as Kr}from"zod";var qo=Kr.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"),Cv=Kr.object({amountCents:Kr.number().int().min(0).max(1e8),currency:be,interval:Kr.enum(["free","month","year"]),currencyOptions:Kr.partialRecord(be,Kr.number().int().min(1).max(1e8)).optional()}).refine(e=>e.interval==="free"?e.amountCents===0:e.amountCents>0,"\u514D\u8D39\u5957\u9910\u91D1\u989D\u5FC5\u987B\u4E3A 0\uFF0C\u4ED8\u8D39\u91D1\u989D\u5FC5\u987B\u5927\u4E8E 0").refine(e=>!e.currencyOptions||!Object.hasOwn(e.currencyOptions,e.currency)&&(e.interval!=="free"||Object.keys(e.currencyOptions).length===0),"\u9644\u52A0\u5E01\u79CD\u4E0D\u80FD\u91CD\u590D\u9ED8\u8BA4\u5E01\u79CD\uFF1B\u514D\u8D39\u5957\u9910\u4E0D\u8BBE\u7F6E\u9644\u52A0\u4EF7\u683C");import{z as F}from"zod";var vA=F.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),kl=F.enum(["single_use","continuous_use"]),ks=F.record(F.string(),F.union([F.string(),F.number(),F.boolean()]).transform(String).pipe(F.string())),El=F.string().min(1).max(64).refine(e=>!e.includes("::")),jl={credit_amount:F.number(),tier_behavior:F.never().optional(),tiers:F.never().optional()},Tl={credit_amount:F.never().optional(),tier_behavior:F.literal("graduated"),tiers:F.array(F.strictObject({to:F.union([F.number(),F.literal("inf")]),credit_amount:F.number()}))},wA=F.union([F.strictObject({match:ks,priority:F.number().int().optional(),...jl}),F.strictObject({match:ks,priority:F.number().int().optional(),...Tl})]),OA=F.strictObject({match:ks,factor:F.number().positive().optional(),add:F.number().optional()}).refine(e=>e.factor!==void 0||e.add!==void 0),Rl={metered_feature_id:F.string(),feature_amount:F.number().optional(),dimensions:F.record(El,wA).optional(),multipliers:F.record(El,OA).optional()},js=F.union([F.strictObject({...Rl,...jl}),F.strictObject({...Rl,...Tl})]),Vo=F.number().min(-100),Nl=F.record(F.string(),F.strictObject({markup:Vo})).nullish(),Lo=F.record(F.string().regex(/.+\/.+/),F.strictObject({markup:Vo.optional(),input_cost:F.number().min(0).optional(),output_cost:F.number().min(0).optional()})).nullish(),PA=F.strictObject({default_markup:Vo.optional(),provider_markups:Nl,model_markups:Lo}),Rv=F.strictObject({schema:F.array(js).optional(),markups:PA.optional()}),CA=F.strictObject({filters:F.array(F.strictObject({property:F.string(),operator:F.string(),value:F.array(F.string())})),aggregate:F.strictObject({type:F.string(),property:F.string().nullable()}),usage_type:kl}),Dl=F.strictObject({schema:F.array(js).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:F.boolean().optional(),usage_type:kl.default("single_use").overwrite(()=>"single_use"),default_markup:Vo.optional(),provider_markups:Nl}),Ts=Dl.safeExtend({schema:F.array(js).length(0)}),Bo={id:vA,name:F.string().min(1),display:F.strictObject({singular:F.string().optional(),plural:F.string().optional()}).nullish(),event_names:F.array(F.string()).default([]),model_markups:Lo,stripe_meter:F.strictObject({id:F.string(),event_name:F.string()}).nullish(),stripe_product_id:F.string().nullish()},Ns=e=>F.discriminatedUnion("type",[F.strictObject({...Bo,...e,type:F.literal("boolean"),config:F.null()}),F.strictObject({...Bo,...e,type:F.literal("metered"),config:CA}),F.strictObject({...Bo,...e,type:F.literal("credit_system"),config:Dl}),F.strictObject({...Bo,...e,type:F.literal("ai_credit_system"),config:Ts})]),kv=Ns({}),_A=F.strictObject({id:F.boolean(),type:F.boolean(),usage_type:F.boolean()}),EA={internal_id:F.uuid(),org_id:F.uuid(),created_at:F.number(),env:F.enum(["sandbox","live"]),archived:F.boolean(),project_id:F.uuid(),environment_id:F.uuid(),revision:F.number().int().nonnegative(),update_rules:_A},Fl=Ns(EA),jv=F.strictObject({rows:F.array(Fl).max(200),nextCursor:F.uuid().nullable()}),Tv=F.strictObject({features:F.array(Fl).max(500),limited:F.boolean()}),Nv=F.union([Ns({action:F.literal("save"),internal_id:F.uuid().nullable(),revision:F.number().int().nonnegative()}),F.strictObject({action:F.enum(["archive","restore","delete"]),internal_id:F.uuid(),revision:F.number().int().nonnegative()})]);import{z as Jr}from"zod";import{z as ct}from"zod";var Qt=ct.string().regex(/^(0|[1-9]\d{0,12})(\.\d{1,12})?$/),Ae=ct.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/).transform(e=>e.includes(".")?e.replace(/0+$/,"").replace(/\.$/,""):e),Uo=ct.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}),Ds=Ae.refine(e=>/[1-9]/.test(e),"\u6570\u91CF\u5FC5\u987B\u5927\u4E8E 0"),Ml=ct.string().min(1).max(64),xr=ct.string().min(1).regex(/^[a-zA-Z0-9_-]+$/),ql=ct.string().min(1).max(64).refine(e=>!e.includes("::"),"Dimension IDs cannot contain ::"),bt=ct.record(Ml,ct.union([ct.string().max(120),ct.number().finite(),ct.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)]))),Bl=ct.record(Ml,ct.union([ct.string().max(120),ct.number().finite(),ct.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},Vl=ct.array(ct.object({upTo:Ds.nullable(),cost:Ae}).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"),RA=ct.object({key:ql,match:Bl,priority:ct.number().int().default(0),cost:Ae.optional(),tiers:Vl.optional()}).strict().refine(e=>e.cost!==void 0||e.tiers!==void 0,"\u7EF4\u5EA6\u9700\u8981\u6307\u5B9A\u5355\u4EF7\u6216\u9636\u68AF"),kA=ct.object({key:ql,match:Bl,factor:Ds.optional(),add:Uo.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"})),jA=ct.object({units:Ds.default("1"),cost:Ae,tiers:Vl.optional(),dimensions:ct.array(RA).max(12).optional(),multipliers:ct.array(kA).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((d,A)=>s&1<<A);if(c.some((d,A)=>c.slice(A+1).some(k=>Object.keys(d.match).some(g=>k.match[g]!==void 0&&k.match[g]!==d.match[g]))))continue;let u=Hr(o),l=BigInt("1"),f=BigInt("0");for(let[d,A]of r.entries())s&1<<d&&(u*=Hr(A.factor??"1"),l*=BigInt("1000000"),f+=Hr(A.add??"0"));let m=(u+f*l)*BigInt("1000000"),h=l*a;(m<BigInt("0")||m%h!==BigInt("0")||m/h>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"})}}),Mv=jA.safeExtend({featureKey:xr});import{z as Qr}from"zod";var Ll=Qr.number().int().min(0).max(1e8),Ni=Qr.strictObject({kind:Qr.enum(["graduated","volume"]),tiers:Qr.array(Qr.strictObject({upTo:Qr.number().int().min(1).max(1e4).nullable(),unitAmountMinor:Ll,flatAmountMinor:Ll.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 Fs(e,t){if(!Number.isInteger(t)||t<0||t>1e4)throw new Error("Invalid purchased pack quantity");let n=e.pricing?Ni.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 zo(e){return Fs({amountMinor:e.unitAmountMinor,...e.pricing?{pricing:e.pricing}:{}},e.quantity)}var TA=Ae.refine(e=>/[1-9]/.test(e)),$o=Jr.strictObject({units:TA,prices:Jr.array(Jr.strictObject({currency:be,amountMinor:Jr.number().int().min(0).max(1e8),pricing:Ni.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:Jr.number().int().min(0).max(1e4),maximumQuantity:Jr.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&&Fs({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 Ul(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 zl(e,t,n){if(!Number.isSafeInteger(n)||n<0||n>1e4)throw new Error("Invalid purchased quantity");let r=Ul(e)+Ul(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:"")}import{z as x}from"zod";import{z as X}from"zod";import{z as kt}from"zod";import{z as N}from"zod";function $l(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 Go(e,t,n){return n===2?$l($l(e+t)+"")%1e4/1e4:null}function NA(e){return e<=0?[]:new Array(e).fill(1/e)}function Ko(e,t){return e>=t[0]&&e<t[1]}function Gl(e,t){for(let[n,r]of t.entries())if(Ko(e,r))return n;return-1}function Kl(e,t,n){t=t===void 0?1:t,t<0?t=0:t>1&&(t=1);let r=NA(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 Hl(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 Ql(e){try{return e()}catch{return!1}}function Di(e){return typeof e=="string"?e:JSON.stringify(e)}function tn(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 DA(e){try{let t=e.replace(/([^\\])\//g,"$1\\/");return new RegExp(t)}catch{return}}function Jl(e,t){if(!t.length)return!1;let n=!1,r=!1;for(let i of t){let a=qA(e,i.type,i.pattern);if(i.include===!1){if(a)return!1}else n=!0,a&&(r=!0)}return r||!n}function FA(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 MA(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=>!FA(i[0],i[1],i[2]))}catch{return!1}}function qA(e,t,n){try{let r=new URL(e,"https://_");if(t==="regex"){let i=DA(n);return i?i.test(r.href)||i.test(r.href.substring(r.origin.length)):!1}else if(t==="simple")return MA(r,n);return!1}catch{return!1}}function Ms(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 Ho(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 Zl(e){for(let t of["overrides","groups"])if(Object.hasOwn(e,t))throw new TypeError(`Retired evaluation context field: ${t}`);Ho(e.savedGroups??{})}var BA=e=>e/2**32|0,VA=e=>e>>>0;function Wl(e,t,n,r){let i=BA(n),a=VA(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}function Yl(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var qs=e=>e?`"${e}" `:"";function LA(e,t=""){if(typeof e!="number")throw new TypeError(qs(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(qs(t)+"expected integer >= 0, got "+e);return e}function Qo(e,t,n=""){if(Yl(e)&&(t===void 0||e.length===t))return e;t!==void 0&&LA(t,"length");let r=Yl(e),i=t!==void 0?` of length ${t}`:"",a=r?`length=${e.length}`:`type=${typeof e}`,o=qs(n)+"expected Uint8Array"+i+", got "+a;throw r?new RangeError(o):new TypeError(o)}var UA=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Xl=(e,t)=>{UA(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 Bs(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function ed(e,t){Qo(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Vs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Jo(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function An(e,t){return e<<32-t|e>>>t}var zA=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",$A=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Zr(e){if(Qo(e),zA)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=$A[e[n]];return t}function GA(e,t,n="opts"){return Xl(e,"defaults"),t!==void 0&&Xl(t,n),Object.assign(Object.create(null),e,t)}function td(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=GA({},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 nd=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function rd(e,t,n){return e&t^~e&n}function id(e,t,n){return e&t^e&n^t&n}var Zo=class{constructor(t,n,r,i){Fe(this,"blockLen");Fe(this,"outputLen");Fe(this,"canXOF",!1);Fe(this,"padOffset");Fe(this,"isLE");Fe(this,"buffer");Fe(this,"view");Fe(this,"finished",!1);Fe(this,"length",0);Fe(this,"pos",0);Fe(this,"destroyed",!1);this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Jo(this.buffer)}update(t){Bs(this),Qo(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=Jo(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){Bs(this),ed(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)),Wl(r,i-8,this.length*8,a),this.process(r,0),this.roundClean();let s=t===n?r:Jo(t),c=this.outputLen,u=c/4,l=this.get();if(c%4||u>l.length)throw new Error("invalid outputLen");for(let f=0;f<u;f++)s.setUint32(4*f,l[f],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()}},od=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var KA=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),Ls=class extends Zo{constructor(n,r){super(64,n,8,!1);Fe(this,"A",0);Fe(this,"B",0);Fe(this,"C",0);Fe(this,"D",0);Fe(this,"E",0);Fe(this,"F",0);Fe(this,"G",0);Fe(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 m=0;m<16;m++,r+=4)Hn[m]=n.getUint32(r,!1);for(let m=16;m<64;m++){let h=Hn[m-15],d=Hn[m-2],A=An(h,7)^An(h,18)^h>>>3,k=An(d,17)^An(d,19)^d>>>10;Hn[m]=k+Hn[m-7]+A+Hn[m-16]|0}let{A:i,B:a,C:o,D:s,E:c,F:u,G:l,H:f}=this;for(let m=0;m<64;m++){let h=An(c,6)^An(c,11)^An(c,25),d=f+h+rd(c,u,l)+KA[m]+Hn[m]|0,k=(An(i,2)^An(i,13)^An(i,22))+id(i,a,o)|0;f=l,l=u,u=c,c=s+d|0,s=o,o=a,a=i,i=d+k|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,l=l+this.G|0,f=f+this.H|0,this.set(i,a,o,s,c,u,l,f)}roundClean(){Vs(Hn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Vs(this.buffer)}},Us=class extends Ls{constructor(){super(32,od)}};var Wr=td(()=>new Us,nd(1));var ad=new Map,zs=32,sd=new WeakMap,cd=new WeakMap;function HA(e){return Zr(Wr(new TextEncoder().encode(String(e))))}var Yo=e=>Array.isArray(e)?e.map(Yo):typeof e=="string"||typeof e=="number"?HA(e):null,Wo=e=>typeof e=="string"?e.toLowerCase():e;function md(e){let t=sd.get(e);return t||(t=new Set(e),sd.set(e,t)),t}function QA(e){let t=cd.get(e);return t||(t=new Set(e.map(Wo)),cd.set(e,t)),t}function Yr(e){Ho(e);for(let t of Object.values(e)){let n=t?.type==="list"||t?.type==="hashed"?t.values:null;n&&n.length>=zs&&md(n)}return e}function Wt(e,t,n,r){n=n||{},r||Ho(n),r=r||new Set;for(let[i,a]of Object.entries(t))switch(i){case"$or":if(!pd(e,a,n,r))return!1;break;case"$nor":if(pd(e,a,n,r))return!1;break;case"$and":if(!XA(e,a,n,r))return!1;break;case"$not":if(Wt(e,a,n,r))return!1;break;case"$savedGroup":if(!JA(e,a,n,r))return!1;break;default:if(!Fi(a,fd(e,i),n,!1,r))return!1}return!0}function JA(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=fd(e,c);return Sr(o.type==="hashed"?Yo(u):u,o.values)}return o.type==="condition"?!o.condition||typeof o.condition!="object"?!1:Wt(e,o.condition,n,s):!1}function fd(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 ud(e,t=!1){let n=`${e}${t?"/i":""}`,r=ad.get(n);return r||(r=new RegExp(e.replace(/([^\\])\//g,"$1\\/"),t?"i":void 0),ad.set(n,r)),r}function Fi(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)||!gd(e))return JSON.stringify(t)===JSON.stringify(e);let a=e;for(let o in a)if(!YA(o,t,a[o],n,i))return!1;return!0}function gd(e){let t=Object.keys(e);return t.length>0&&t.filter(n=>n[0]==="$").length===t.length}function ZA(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 WA(e,t,n,r){if(!Array.isArray(e))return!1;let i=gd(t)?a=>Fi(t,a,n,!1,r):a=>Wt(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 Sr(e,t,n=!1){if(n){let i;if(t.length>=zs){let a=QA(t);i=o=>{let s=Wo(o);return!(typeof s=="number"&&Number.isNaN(s))&&a.has(s)}}else i=a=>t.some(o=>Wo(a)===Wo(o));return Array.isArray(e)?e.some(a=>i(a)):i(e)}let r=t.length>=zs?(i=>a=>i.has(a))(md(t)):i=>t.includes(i);return Array.isArray(e)?e.some(i=>r(i)):r(e)}function ld(e){return e===void 0?[]:e&&typeof e=="object"&&(e.type==="list"||e.type==="hashed")&&Array.isArray(e.values)?e.values:null}function dd(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(Fi(t[a],e[s],n,r,i)){o=!0;break}if(!o)return!1}return!0}function YA(e,t,n,r,i=new Set){let a=t,o=n;switch(e){case"$veq":return tn(t)===tn(n);case"$vne":return tn(t)!==tn(n);case"$vgt":return tn(t)>tn(n);case"$vgte":return tn(t)>=tn(n);case"$vlt":return tn(t)<tn(n);case"$vlte":return tn(t)<=tn(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)?Sr(t,n):!1;case"$ini":return Array.isArray(n)?Sr(t,n,!0):!1;case"$inGroup":{let s=r[n],c=ld(s);return c===null?!1:Sr(s?.type==="hashed"?Yo(t):t,c)}case"$notInGroup":{let s=r[n],c=ld(s);return c===null?!1:!Sr(s?.type==="hashed"?Yo(t):t,c)}case"$nin":return Array.isArray(n)?!Sr(t,n):!1;case"$nini":return Array.isArray(n)?!Sr(t,n,!0):!1;case"$not":return!Fi(n,t,r,!1,i);case"$size":return Array.isArray(t)?Fi(n,t.length,r,!1,i):!1;case"$elemMatch":return WA(t,n,r,i);case"$all":return Array.isArray(n)?dd(t,n,r,!1,i):!1;case"$alli":return Array.isArray(n)?dd(t,n,r,!0,i):!1;case"$regex":try{return ud(n).test(t)}catch{return!1}case"$regexi":try{return ud(n,!0).test(t)}catch{return!1}case"$type":return ZA(t)===n;default:return!1}}function pd(e,t,n,r){if(!t.length)return!0;for(let i of t)if(Wt(e,i,n,r))return!0;return!1}function XA(e,t,n,r){for(let i of t)if(!Wt(e,i,n,r))return!1;return!0}function $s(e){return Zl(e),{context:e,stack:{evaluatedFeatures:new Set}}}function Gs(e){return{...e.attributes,...e.attributeOverrides}}function Qn(e,t,n){let r=t||"id",i="",a=Gs(e);return a[r]&&(i=a[r]),!i&&n&&(a[n]&&(i=a[n]),i&&(r=n)),{hashAttribute:r,hashValue:i}}function Qe(e,t,n){e.context.log?.(t,n)}function Xo(e,t){return t=t||0,`${e}__${t}`}function Ks(e,t){return`${e}||${t}`}function ey(e,t,n){let r=e.stickyBucketAssignmentDocs;if(!r)return{};let{hashAttribute:i,hashValue:a}=Qn(e,t),o=Ks(i,Di(a)),{hashAttribute:s,hashValue:c}=Qn(e,n),u=c?Ks(s,Di(c)):null,l={};return u&&r[u]&&Object.assign(l,r[u].assignments||{}),r[o]&&Object.assign(l,r[o].assignments||{}),l}function hd({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=Xo(t,n),c=ey(e,r,i);if(a>0)for(let f=0;f<a;f++){let m=Xo(t,f);if(c[m]!==void 0)return{variation:-1,versionIsBlocked:!0}}let u=c[s];if(u===void 0)return{variation:-1};let l=o.findIndex(f=>f.key===u);return l<0?{variation:-1}:{variation:l}}function Ad(e,t,n,r){let i=Ks(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 yd(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function ea(e,t){let n=$s(t),r=xd(e,null,n);return t.onExperimentEval?.(e,r),r}function Vn(e,t){return Qs(e,$s(t))}function ty(e){return e.forcedVariations||{}}function bd(e,t,n){let{context:r}=e;if(r.trackedExperiments){let i=vd(t,n);if(r.trackedExperiments.has(i))return;r.trackedExperiments.add(i)}Hs(()=>r.onExperimentViewed?.(t,n))}function ny(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}Hs(()=>r.onFeatureUsage?.(t,n))}function Hs(e){try{let t=e();t&&typeof t.catch=="function"&&t.catch(()=>{})}catch{}}function Qs(e,t){let{context:n}=t;if(t.stack.evaluatedFeatures.has(e))return Qe(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??[])Ms(a);let i=n.forcedFeatureValues;if(i&&i.has(e))return Qe(t,"Global override",{id:e,value:i.get(e)}),Jn(t,e,i.get(e),"override");if(!r)return Qe(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 l=Qs(u.id,t);if(l.source==="cyclicPrerequisite")return Jn(t,e,null,"cyclicPrerequisite");let f={value:l.value};if(!Wt(f,u.condition||{},n.savedGroups||{})){if(u.gate)return Qe(t,"Feature blocked by prerequisite",{id:e,rule:o}),Jn(t,e,null,"prerequisite");Qe(t,"Skip rule because prerequisite evaluation fails",{id:e,rule:o});continue e}}if(o.filters&&Id(o.filters,t)){Qe(t,"Skip rule because of filters",{id:e,rule:o});continue}if("force"in o){if(o.condition&&!Sd(o.condition,t)){Qe(t,"Skip rule because of condition ff",{id:e,rule:o});continue}if(!ry(t,o.seed||e,o.hashAttribute,n.saveStickyBucketAssignmentDoc&&!o.disableStickyBucketing?o.fallbackAttribute:void 0,o.range,o.coverage,o.hashVersion)){Qe(t,"Skip rule because user not included in rollout",{id:e,rule:o});continue}return Qe(t,"Force value from rule",{id:e,rule:o}),o.tracks&&o.tracks.forEach(u=>{bd(t,u.experiment,u.result)}),Jn(t,e,o.force,"force",o.id)}if(!o.variations){Qe(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=xd(s,e,t);if(n.onExperimentEval?.(s,c),c.inExperiment&&!c.passthrough)return Jn(t,e,c.value,"experiment",o.id,s,c)}}return Qe(t,"Use default value",{id:e,value:r.defaultValue}),Jn(t,e,r.defaultValue===void 0?null:r.defaultValue,"defaultValue")}function xd(e,t,n){let{context:r}=n;Ms(e);let i=e.key,a=e.variations.length;if(a<2)return Qe(n,"Invalid experiment",{id:i}),Rt(n,e,-1,!1,t);if(r.enabled===!1)return Qe(n,"Context disabled",{id:i}),Rt(n,e,-1,!1,t);if(e.urlPatterns&&!Jl(r.url||"",e.urlPatterns))return Qe(n,"Skip because of url targeting",{id:i}),Rt(n,e,-1,!1,t);let o=Hl(i,r.url||"",a);if(o!==null)return Qe(n,"Force via querystring",{id:i,variation:o}),Rt(n,e,o,!1,t);let c=ty(r)[i];if(c!==void 0)return Qe(n,"Force via dev tools",{id:i,variation:c}),Rt(n,e,c,!1,t);if(e.active===!1)return Qe(n,"Skip because inactive",{id:i}),Rt(n,e,-1,!1,t);let{hashAttribute:u,hashValue:l}=Qn(r,e.hashAttribute,r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing?e.fallbackAttribute:void 0);if(!l)return Qe(n,"Skip because missing hashAttribute",{id:i}),Rt(n,e,-1,!1,t);let f=-1,m=!1,h=!1;if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{variation:k,versionIsBlocked:g}=hd(yd({context:r,expKey:e.key,expBucketVersion:e.bucketVersion,expHashAttribute:e.hashAttribute,expFallbackAttribute:e.fallbackAttribute,expMinBucketVersion:e.minBucketVersion,expMeta:e.meta}));m=k>=0,f=k,h=!!g}if(!m){if(e.filters&&Id(e.filters,n))return Qe(n,"Skip because of filters",{id:i}),Rt(n,e,-1,!1,t);if(e.include&&!Ql(e.include))return Qe(n,"Skip because of include function",{id:i}),Rt(n,e,-1,!1,t);if(e.condition&&!Sd(e.condition,n))return Qe(n,"Skip because of condition exp",{id:i}),Rt(n,e,-1,!1,t);if(e.parentConditions){let k=new Set(n.stack.evaluatedFeatures);for(let g of e.parentConditions){n.stack.evaluatedFeatures=new Set(k);let y=Qs(g.id,n);if(y.source==="cyclicPrerequisite")return Rt(n,e,-1,!1,t);let I={value:y.value};if(!Wt(I,g.condition||{},r.savedGroups||{}))return Qe(n,"Skip because prerequisite evaluation fails",{id:i}),Rt(n,e,-1,!1,t)}}}let d=Go(e.seed||i,l,e.hashVersion??2);if(d===null)return Qe(n,"Skip because of invalid hash version",{id:i}),Rt(n,e,-1,!1,t);if(!m){let k=e.ranges||Kl(a,e.coverage===void 0?1:e.coverage,e.weights);f=Gl(d,k)}if(h)return Qe(n,"Skip because sticky bucket version is blocked",{id:i}),Rt(n,e,-1,!1,t,void 0,!0);if(f<0)return Qe(n,"Skip because of coverage",{id:i}),Rt(n,e,-1,!1,t);if("force"in e)return Qe(n,"Force variation",{id:i,variation:e.force}),Rt(n,e,e.force===void 0?-1:e.force,!1,t);if(r.qaMode)return Qe(n,"Skip because QA mode",{id:i}),Rt(n,e,-1,!1,t);let A=Rt(n,e,f,!0,t,d,m);if(r.saveStickyBucketAssignmentDoc&&!e.disableStickyBucketing){let{changed:k,key:g,doc:y}=Ad(r,u,Di(l),{[Xo(e.key,e.bucketVersion)]:A.key});if(k){r.stickyBucketAssignmentDocs=r.stickyBucketAssignmentDocs||{},r.stickyBucketAssignmentDocs[g]=y;let I=r.saveStickyBucketAssignmentDoc;Hs(()=>I(y))}}return bd(n,e,A),Qe(n,"In experiment",{id:i,variation:A.variationId}),A}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"&&ny(e,t,s),s}function Sd(e,t){return Wt(Gs(t.context),e,t.context.savedGroups||{})}function Id(e,t){return e.some(n=>{let{hashValue:r}=Qn(t.context,n.attribute);if(!r)return!0;let i=Go(n.seed,r,n.hashVersion||2);return i===null?!0:!n.ranges.some(a=>Ko(i,a))})}function ry(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=Go(t,s,o??2);return c===null?!1:i?Ko(c,i):a!==void 0?c<=a:!0}function Rt(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),l=t.meta?.[n]??{},f=t.variations[0];for(let[h,d]of t.variations.entries())if(h===n){f=d;break}let m={key:l.key||""+n,featureId:i,inExperiment:s,hashUsed:r,variationId:n,value:f,hashAttribute:c,hashValue:u,stickyBucketUsed:!!o};return l.name&&(m.name=l.name),a!==void 0&&(m.bucket=a),l.passthrough&&(m.passthrough=l.passthrough),m}function vd(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.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"})}),ht=j.record(j.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"})}),VA=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=ht.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.strictObject({id:j.uuid(),attributeKey:j.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("$")&&!VA.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)}),BA=j.discriminatedUnion("type",[j.strictObject({type:j.literal("condition"),condition:Ht}),j.strictObject({type:j.literal("list"),attributeKey:j.string().min(1).max(128),values:j.array(j.union([j.string(),j.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 Fn(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 UA=j.record(j.uuid(),BA).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"&&Fn(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Bs=j.tuple([j.number().min(0).max(1),j.number().min(0).max(1)]).refine(([e,t])=>e<=t),ld=j.strictObject({attribute:j.string().optional(),seed:j.string().min(1),hashVersion:j.literal(2),ranges:j.array(Bs).min(1).max(100)}),LA=j.strictObject({id:j.string().min(1).max(128),condition:Ht,gate:j.boolean().optional()}),Vs={id:j.string().max(128).optional(),condition:Ht.optional(),parentConditions:j.array(LA).max(50).optional(),filters:j.array(ld).max(20).optional()},zA=j.union([j.strictObject({...Vs}),j.strictObject({...Vs,force:Ae,coverage:j.number().min(0).max(1).optional(),range:Bs.optional(),seed:j.string().min(1).optional(),hashAttribute:j.string().optional(),hashVersion:j.literal(2).optional()}),j.strictObject({...Vs,type:j.literal("experiment-ref"),experimentId:j.uuid(),values:j.record(j.string().min(1),Ae),meta:j.record(j.string().min(1),j.strictObject({passthrough:j.boolean()})).optional()})]),$A=j.strictObject({defaultValue:Ae,rules:j.array(zA).max(100)}),aw=j.record(j.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),$A).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)}),GA=j.strictObject({name:j.string().max(80),reason:j.string().max(500),dateStarted:j.iso.datetime({offset:!0}),dateEnded:j.iso.datetime({offset:!0}).nullable(),coverage:j.number().min(0).max(1),variationWeights:j.array(j.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.array(j.strictObject({match:j.enum(["any","all","none"]),ids:j.array(j.uuid()).min(1)})).max(50),namespace:j.strictObject({id:j.uuid(),ranges:j.array(Bs).min(1)}).nullable(),seed:j.string().min(1).max(128)}),KA=j.strictObject({key:j.string().min(1).max(128),name:j.string().min(1).max(80),hypothesis:j.string().max(2e3),status:j.enum(["draft","running","stopped"]),hashAttribute:j.string().min(1).max(128),fallbackAttribute:j.string().max(128).nullable(),hashVersion:j.literal(2),disableStickyBucketing:j.boolean(),bucketVersion:j.number().int().min(0).max(1e3),minBucketVersion:j.number().int().min(0).max(1e3),variations:j.array(j.strictObject({id:j.string().min(1),key:j.string().min(1),name:j.string().max(80),description:j.string().max(500)})).min(2).max(20),phases:j.array(GA).min(1).max(100),releasedVariationId:j.string().nullable(),excludeFromPayload:j.boolean(),statusSchedule:j.strictObject({startAt:j.iso.datetime({offset:!0}).nullable(),stopAt:j.iso.datetime({offset:!0}).nullable(),stopAfter:j.strictObject({value:j.number().int().positive().max(36500),unit:j.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 HA=KA.safeExtend({filters:j.array(ld).optional()}),QA=j.strictObject({experiments:j.record(j.uuid(),HA),savedGroups:UA}),ki=j.strictObject({attributeName:j.string(),attributeValue:j.string(),assignments:j.record(j.string(),j.string())}),sw=j.strictObject({snapshot:QA,attributes:ht,results:ht,stickyBucketAssignmentDocs:j.record(j.string(),ki)}),cw=j.strictObject({variantKey:j.string().nullable(),bucketVersion:j.number().int().min(0),source:j.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:j.number().min(0).max(1).optional(),stickyBucketUsed:j.boolean().optional(),hashUsed:j.boolean().optional()});function Jn(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 JA=Ct.enum(["active","inactive"]),ZA=Ct.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},ht),WA=Ct.strictObject({id:Ct.string().trim().min(1).max(255),name:Ct.string().trim().min(1).max(255),status:JA,metadata:ZA}),fw=WA.extend({internal_id:Ct.uuid(),project_id:Ct.uuid(),environment_id:Ct.uuid(),created_at:Ct.iso.datetime({offset:!0}),updated_at:Ct.iso.datetime({offset:!0})}),pd=Ct.union([Ct.strictObject({id:Ct.string().trim().min(1).max(255)}),Ct.strictObject({internalId:Ct.uuid()})]),gw=Ct.enum(["customer","merchandise","context"]),hw=Ct.enum(["system","stored","request"]),Aw=Ct.enum(["customer","merchandise","mixed"]),dd=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Us(e,t={},n=new Set){if(Jn(e).some(dd))return!0;for(let r of Fn(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&dd(i.attributeKey)||i?.type==="condition"&&Us(i.condition,t,n))return!0}return!1}import{z as YA}from"zod";var XA=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,gn=YA.string().max(16).regex(XA,"\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 Ow=X.enum(["draft","active","paused","archived"]),Zn=X.discriminatedUnion("type",[X.object({type:X.literal("percent"),percentOff:X.number().min(1).max(100).multipleOf(.01)}).strict(),X.object({type:X.literal("amount"),amountOffCents:X.number().int().min(1).max(1e8),currency:he}).strict()]),en=X.discriminatedUnion("type",[X.object({type:X.literal("once")}).strict(),X.object({type:X.literal("repeating"),months:X.number().int().min(1).max(36)}).strict(),X.object({type:X.literal("forever")}).strict()]),md=[X.object({type:X.literal("all")}).strict(),X.object({type:X.literal("plans"),planIds:X.array(X.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],ey=X.discriminatedUnion("type",[...md,X.strictObject({type:X.literal("merchandise"),scope:X.discriminatedUnion("type",[X.strictObject({type:X.literal("all")}),X.strictObject({type:X.literal("selected"),merchandiseIds:X.array(X.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),X.strictObject({type:X.literal("condition"),condition:Ht})])})]),Ls=X.discriminatedUnion("type",[...md,X.strictObject({type:X.literal("merchandise"),scope:X.strictObject({type:X.enum(["all","selected","condition"])})})]),ty=X.strictObject({firstPurchaseOnly:X.boolean(),condition:Ht}),_w=X.object({name:X.string().trim().min(1).max(80),description:X.string().max(500),discount:Zn,duration:en,appliesTo:ey,eligibility:ty,selfClaimEnabled:X.boolean().default(!1),startsAt:X.iso.datetime().nullable(),endsAt:X.iso.datetime().nullable(),totalLimit:X.number().int().min(1).max(1e6).nullable(),perCustomerLimit:X.number().int().min(1).max(10),grantWindowHours:X.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=>!Us(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"]}),Cw=X.object({code:X.string().trim().transform(e=>e.toUpperCase()).pipe(X.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:X.number().int().min(1).max(1e6).nullable(),expiresAt:X.iso.datetime().nullable(),firstPurchaseOnly:X.boolean(),minimumAmountCents:X.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 ji=X.object({id:X.uuid(),couponId:X.uuid(),status:X.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:X.iso.datetime(),expiresAt:X.iso.datetime(),coupon:X.object({name:X.string(),discount:Zn,duration:en,appliesTo:Ls}).strict()}).strict(),fd=X.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var bd=h.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),zs=h.string().regex(/^(0|[1-9]\d{0,14})$/),Hr=h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),ny=h.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Ti=ny,Mn=ge.refine(e=>/[1-9]/.test(e)),Mt=h.iso.datetime({offset:!0}),Ko=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"))},ry=h.array(h.object({upTo:Mn.nullable(),unitAmountMinor:bd,flatAmountMinor:h.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&&Ko(t.upTo)>Ko(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),iy=h.discriminatedUnion("kind",[h.object({kind:h.literal("flat"),units:Mn,unitAmountMinor:bd}).strict(),h.object({kind:h.enum(["graduated","volume"]),units:Mn,tiers:ry}).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"),oy=h.strictObject({interval:h.enum(["month","year"]),count:h.number().int().min(1).max(12),anchor:h.enum(["membership","calendar"])}),Ni=h.object({currency:he,pricing:iy,billingCycle:oy.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var gd={requestId:h.uuid(),productVersionId:h.uuid(),internal_feature_id:h.uuid(),currency:he},Sd=h.strictObject({interval:h.enum(["hour","day","week","month"]),intervalCount:h.number().int().min(1).max(12),limit:h.number().int().min(1).max(1e6)}),xd=h.discriminatedUnion("kind",[h.object({...gd,kind:h.literal("auto_topup"),threshold:To,quantity:Mn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Sd.optional()}).strict(),h.object({...gd,kind:h.literal("postpaid"),maxAmountMinorPerPeriod:Ti,maxOutstandingMinor:Ti}).strict()]),hd={productVersionId:h.uuid(),internal_feature_id:h.uuid(),currency:he},Id=h.discriminatedUnion("kind",[h.object({...hd,kind:h.literal("auto_topup"),threshold:To,quantity:Mn.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Sd.optional(),purchaseAmountMinor:Ti,purchaseUnits:Mn}).strict(),h.object({...hd,kind:h.literal("postpaid"),maxAmountMinorPerPeriod:Ti,maxOutstandingMinor:Ti,cashPrice:Ni}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),Ho=h.object({id:h.uuid(),terms:Id,status:h.enum(["prepared","active","revoked","blocked"]),createdAt:Mt,acceptedAt:Mt.nullable(),effectiveAt:Mt.nullable(),revokedAt:Mt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),vd=h.object({authorizationId:h.uuid(),terms:Id,setupUrl:h.url().nullable()}).strict(),wd=h.object({authorizationId:h.uuid(),accepted:h.literal(!0)}).strict(),Od=h.object({authorizationId:h.uuid(),requestId:h.uuid()}).strict(),_d=h.object({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),interval:h.enum(["day","week","month","year"]),anchor:h.enum(["billing_cycle","utc"]).optional(),basis:h.enum(["usage","credits"]),filter:gt.optional(),limit:ge.nullable(),thresholds:h.array(h.number().positive().max(1)).max(8),includedThresholds:h.array(h.number().positive().max(1)).max(8).optional(),absoluteThresholds:h.array(Mn).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&&Ko(t)>Ko(i)}),"Notification thresholds must increase"),ay=_d.safeExtend({requestId:h.uuid()}),Ad={control:h.literal("overage"),requestId:h.uuid(),internal_feature_id:h.uuid(),entityId:h.uuid().nullable()},sy=h.discriminatedUnion("action",[h.strictObject({...Ad,action:h.literal("set"),allowed:h.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.boolean()}),h.strictObject({...Ad,action:h.literal("remove")})]),Cd=h.union([ay,sy]),cy=h.strictObject({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),allowed:h.boolean().nullable(),overageLimit:ge.nullable(),skipOverageBilling:h.boolean(),interval:h.enum(["day","week","month","year"]),startsAt:Mt,endsAt:Mt,used:h.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:h.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:h.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),uy=h.object({internal_feature_id:h.uuid(),entityId:h.uuid().nullable(),interval:h.enum(["day","week","month","year"]),anchor:h.enum(["billing_cycle","utc"]).optional(),basis:h.enum(["usage","credits"]),filter:gt.optional(),startsAt:Mt,endsAt:Mt,used:Kt,reserved:Kt,limit:ge.nullable(),thresholds:h.array(h.number().positive().max(1)).max(8),notifiedThresholds:h.array(h.number().positive().max(1)).max(1024),includedThresholds:h.array(h.number().positive().max(1)).max(8).optional(),includedAllowance:h.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:h.array(h.number().positive().max(1)).max(1024).optional(),absoluteThresholds:h.array(Mn).max(8).optional(),notifiedAbsoluteThresholds:h.array(Mn).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"),ly=h.object({authorizationId:h.uuid(),status:h.enum(["idle","pending","blocked"]),taskId:h.uuid().nullable(),invoiceId:h.uuid().nullable(),hostedInvoiceUrl:h.url().nullable(),purchaseCount:h.number().int().nonnegative(),purchaseWindowEndsAt:Mt.nullable(),attemptCount:h.number().int().nonnegative(),failedAttemptCount:h.number().int().nonnegative(),suspendedAt:Mt.nullable(),nextAttemptAt:Mt.nullable(),failureReason:h.string().min(1).max(240).nullable()}).strict(),Pd=h.object({internal_feature_id:h.uuid().optional(),entityId:h.uuid().optional()}).strict(),$s=h.object({authorizations:h.array(Ho).max(100),limits:h.array(_d).max(100),overages:h.array(cy).max(100).optional(),windows:h.array(uy).max(200),autoTopups:h.array(ly).max(100),limited:h.boolean()}).strict(),dy=h.object({id:h.uuid(),internal_feature_id:h.uuid(),productVersionId:h.uuid(),authorizationId:h.uuid(),entityId:h.uuid().nullable(),units:ge,amountMinor:Hr,cashPrice:Ni}).strict(),Di=h.object({id:h.uuid(),sourceKind:h.enum(["product","usage","manual"]),providerInvoiceId:h.string().min(1).max(240).nullable(),status:h.enum(["accruing","open","pending","paid","failed","void"]),currency:he,startsAt:Mt.nullable(),endsAt:Mt.nullable(),amountMinor:h.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:h.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:zs,paidAmountMinor:zs,refundedAmountMinor:zs,createdAt:Mt,hostedInvoiceUrl:h.url().nullable(),adjustment:h.object({originalInvoiceId:h.uuid(),amountMinor:h.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Mt.nullable(),reason:h.string().min(1).max(500).optional()}).strict().nullable(),lines:h.array(dy).max(100),linesLimited:h.boolean()}).strict(),Ed=h.object({invoiceId:h.uuid(),accepted:h.literal(!0)}).strict(),Rd=h.strictObject({requestId:h.uuid(),originalInvoiceId:h.uuid(),amountMinor:h.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.string().trim().min(1).max(500)}),kd=h.object({after:h.uuid().nullable(),limit:h.number().int().min(1).max(100)}).strict(),jd=h.object({rows:h.array(Di).max(100),nextCursor:h.uuid().nullable()}).strict(),yd=h.strictObject({id:h.string(),coupon:h.string(),start:h.number().nonnegative(),end:h.number().nullable()}),py=h.strictObject({subscriptionId:h.string(),customerId:h.string(),accountId:h.string(),sourceItems:h.array(h.strictObject({id:h.string(),price_id:h.string(),quantity:h.number().int(),discounts:h.array(yd).optional()})).max(100),items:h.array(h.strictObject({id:h.string(),price:h.string(),quantity:h.number().int(),discounts:h.array(h.strictObject({coupon:h.string().optional(),terms:h.strictObject({id:h.string(),name:h.string().optional(),percent_off:h.number().optional(),amount_off:h.number().optional(),currency:h.string().optional(),duration:h.enum(["once","forever","repeating"]),duration_in_months:h.number().optional()}).optional(),discount:h.string().optional(),receipt:yd.optional()})).max(20)})).max(100)}),Td=h.strictObject({membershipId:h.uuid(),requestId:h.uuid(),grantIds:h.array(h.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Nd=h.strictObject({membershipId:h.uuid(),operationId:h.uuid(),status:h.enum(["pending","effective"]),execution:py.nullable(),grants:h.array(h.strictObject({id:h.uuid(),couponId:h.uuid(),name:h.string(),discount:Zn,duration:en,startedAt:Mt.nullable()})).max(20)});import{z as Fi}from"zod";var Dd=Fi.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Fd=Fi.number().int().min(1).max(1e3),Qo=Fi.object({cap:ge.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Fi.number().positive().max(1e4).nullable(),cycles:Fi.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as Wn}from"zod";var Md=Wn.strictObject({itemKey:Wn.string().regex(/^paid:feature:[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/),internal_feature_id:Wn.uuid(),includedAmount:Wn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Wn.number().int().min(0).max(1e4),terms:Do,pricing:Pi.optional(),unitAmountMinor:Wn.number().int().min(0).max(1e8),productId:Wn.string().min(1).max(255).nullable(),priceId:Wn.string().min(1).max(255).nullable()}).superRefine((e,t)=>{(e.quantity<e.terms.minimumQuantity||e.quantity>e.terms.maximumQuantity||e.productId===null!=(e.priceId===null)||e.quantity>0&&(e.pricing||e.unitAmountMinor>0)&&e.priceId===null)&&t.addIssue({code:"custom",message:"Purchased quantities need their published bounds and immutable price binding"});try{El(e.includedAmount,e.terms.units,e.quantity),No({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as ee}from"zod";var Sr=ge.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),Mi=ee.string().min(1).max(120),Jo=ee.enum(["cap","overflow"]),tn=(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"))},qi=e=>{try{return e()}catch{return!1}},Vi=ee.discriminatedUnion("operation",[ee.object({operation:ee.literal("quote"),overageBehavior:Jo.optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:Sr,properties:gt}).strict(),ee.object({operation:ee.literal("consume"),overageBehavior:Jo.optional(),occurredAt:ee.iso.datetime({offset:!0}).optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:ge,properties:gt,idempotencyKey:Mi}).strict(),ee.object({operation:ee.literal("reserve"),occurredAt:ee.iso.datetime({offset:!0}).optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:Sr,properties:gt,idempotencyKey:Mi,expiresInSeconds:ee.number().int().min(1).max(86400)}).strict(),ee.object({operation:ee.literal("confirm"),operationId:ee.uuid(),quantity:Sr,properties:gt.optional(),idempotencyKey:Mi}).strict(),ee.object({operation:ee.literal("refund"),operationId:ee.uuid(),quantity:Sr,idempotencyKey:Mi}).strict(),ee.object({operation:ee.literal("release"),operationId:ee.uuid(),idempotencyKey:Mi}).strict()]),Gs=ee.object({internal_credit_feature_id:ee.uuid().nullable(),internal_metered_feature_id:ee.uuid(),dimension:ee.string().min(1).max(64),counterKey:ee.string().min(1).max(240),cycleStart:ee.iso.datetime({offset:!0}),unitCost:ge,units:Sr,amount:Kt,tier:ee.number().int().min(1).max(12).nullable()}).strict(),xr=ee.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function qd(e,t){let n=e.reduce((r,i)=>r+tn(i.units,12),0n)-tn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var Vd=ee.discriminatedUnion("funding",[ee.strictObject({funding:ee.literal("balance"),sourceId:ee.uuid(),rolloverId:ee.uuid().nullable(),units:xr.refine(e=>/[1-9]/.test(e)),amount:Kt}),ee.strictObject({funding:ee.literal("unbilled"),units:xr.refine(e=>/[1-9]/.test(e))}),ee.object({funding:ee.literal("prepaid"),sourceId:ee.uuid(),units:Sr,amount:Kt,pricing:ee.array(Gs).min(1).max(12)}).strict().refine(e=>qi(()=>e.pricing.reduce((t,n)=>t+tn(n.units,6),0n)===tn(e.units,6)&&e.pricing.reduce((t,n)=>t+tn(n.amount,12),0n)===tn(e.amount,12)&&e.pricing.every(t=>tn(t.unitCost,6)*tn(t.units,6)===tn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ee.object({funding:ee.literal("postpaid"),invoiceLineId:ee.uuid().nullable(),units:Sr,authorizationId:ee.uuid()}).strict()]),Zo=ee.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),Bd=ee.object({allowed:ee.boolean(),internal_feature_id:ee.uuid(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Jo.optional(),reason:Zo.nullable(),allocations:ee.array(Vd).max(500)}).strict().refine(e=>qi(()=>e.allowed?e.reason===null&&qd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>qi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&tn(e.requestedQuantity,6)>=tn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Bi=ee.object({id:ee.uuid(),internal_feature_id:ee.uuid(),kind:ee.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ee.uuid().nullable(),quantity:ge,requestedQuantity:ge.optional(),overageBehavior:Jo.optional(),accepted:ee.boolean(),reason:ee.enum([...Zo.options,"expired"]).nullable(),createdAt:ee.iso.datetime({offset:!0}),reservationStatus:ee.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ee.iso.datetime({offset:!0}).nullable(),allocations:ee.array(Vd).max(500)}).strict().refine(e=>qi(()=>e.accepted?e.reason===null&&qd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>qi(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&tn(e.requestedQuantity,6)>=tn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as Re}from"zod";var Ir=Re.iso.datetime({offset:!0}),Ud=ge.refine(e=>/[1-9]/.test(e)),Ld=Re.strictObject({interval:Dd.exclude(["lifetime"]),count:Fd}),my=Re.strictObject({action:Re.literal("create"),requestId:Re.uuid(),internal_feature_id:Re.uuid(),entityId:Re.uuid().nullable(),amount:Ud.nullable(),expiresAt:Ir.nullable(),reset:Ld.nullable(),rollover:Qo.nullable(),nextResetAt:Ir.nullable()}).refine(e=>e.amount!==null||e.reset===null&&e.rollover===null,"Unlimited grants cannot reset or roll over").refine(e=>!e.rollover||e.reset!==null,"Rollover requires a recurring grant").refine(e=>e.nextResetAt===null||e.reset!==null&&(e.expiresAt===null||Date.parse(e.nextResetAt)<Date.parse(e.expiresAt)),"The first reset needs a reset interval and must precede expiry"),zd=Re.discriminatedUnion("action",[my,Re.strictObject({action:Re.literal("update"),requestId:Re.uuid(),grantId:Re.uuid(),revision:Re.number().int().nonnegative(),amount:Ud.nullable(),expiresAt:Ir.nullable(),rollover:Qo.nullable(),nextResetAt:Ir.nullable()}),Re.strictObject({action:Re.enum(["add","subtract","set_remaining"]),requestId:Re.uuid(),grantId:Re.uuid(),revision:Re.number().int().nonnegative(),amount:ge}),Re.strictObject({action:Re.literal("revoke"),requestId:Re.uuid(),grantId:Re.uuid(),revision:Re.number().int().nonnegative()})]),Ks=Re.strictObject({id:Re.uuid(),internal_feature_id:Re.uuid(),entityId:Re.uuid().nullable(),amount:ge.nullable(),reset:Ld.nullable(),rollover:Qo.nullable(),nextResetAt:Ir.nullable(),startsAt:Ir,expiresAt:Ir.nullable(),revision:Re.number().int().nonnegative(),revoked:Re.boolean(),available:Kt,held:Kt,spent:Kt}),$d=Re.strictObject({customerId:Re.uuid(),after:Re.uuid().nullable(),limit:Re.number().int().min(1).max(100)}),Gd=Re.strictObject({rows:Re.array(Ks).max(100),nextCursor:Re.uuid().nullable()});import{z as ne}from"zod";var On=ne.iso.datetime({offset:!0}),Kd=ne.strictObject({invoiceId:ne.uuid(),after:ne.string().min(1).max(180).nullable(),limit:ne.number().int().min(1).max(100)}),fy=ne.strictObject({kind:ne.literal("product"),key:ne.string(),productVersionId:ne.uuid(),productName:ne.string(),itemKey:ne.string(),entityId:ne.uuid().nullable(),quantity:ne.number().positive(),subtotalMinor:ne.string().regex(/^-?\d+$/),discountMinor:ne.string().regex(/^\d+$/),taxMinor:ne.string().regex(/^-?\d+$/).nullable(),totalMinor:ne.string().regex(/^-?\d+$/),startsAt:On.nullable(),endsAt:On.nullable(),providerLineId:ne.string().nullable(),providerItemId:ne.string()}),Hd=ne.strictObject({invoice:Di,items:ne.array(ne.discriminatedUnion("kind",[fy,ne.strictObject({kind:ne.literal("invoice_credit"),key:ne.string(),internal_feature_id:ne.uuid(),internal_credit_feature_id:ne.uuid(),name:ne.string(),units:ge,reserved:ge,amountMinor:Hr,grossAmountMinor:Hr,creditsAppliedMinor:Hr,properties:gt,cashPrice:Ni,providerItemId:ne.string().nullable(),creditProviderItemId:ne.string().nullable()}),ne.strictObject({kind:ne.literal("usage"),key:ne.string(),internal_feature_id:ne.uuid(),name:ne.string(),units:ge,reserved:ge,amountMinor:Hr,cashPrice:Ni})])).max(100),nextCursor:ne.string().min(1).max(180).nullable()}),gy=ne.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),Hs=ne.strictObject({from:On,to:On,entityId:ne.uuid().optional(),snapshotAt:On.nullable(),after:ne.strictObject({at:On,id:ne.uuid(),position:ne.number().int().nonnegative()}).nullable(),limit:ne.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"),Qd=ne.strictObject({customerId:ne.uuid(),entityId:ne.uuid().nullable(),from:On,to:On,snapshotAt:On,totals:ne.array(ne.strictObject({internal_credit_feature_id:ne.uuid(),name:ne.string(),consumed:Kt,refunded:Kt,net:gy})).max(1e3),rows:ne.array(ne.strictObject({operationId:ne.uuid(),position:ne.number().int().nonnegative(),kind:ne.enum(["consume","confirm","refund"]),originalId:ne.uuid().nullable(),occurredAt:On,internal_feature_id:ne.uuid(),entitlementName:ne.string(),sourceId:ne.uuid(),internal_credit_feature_id:ne.uuid(),creditName:ne.string(),units:xr,amount:Kt,pricing:ne.array(Gs).max(12),properties:gt})).max(100),nextCursor:Hs.shape.after});import{z as T}from"zod";import{z as hn}from"zod";var hy=hn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Ay=hn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),Wo=hn.strictObject({internal_feature_id:hn.uuid(),entityId:hn.uuid().nullable()}),Jd=Wo.extend({quantity:ge,expectedRevision:hn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:hn.string().min(1).max(120),properties:gt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Ui=Wo.extend({operationId:hn.uuid().nullable(),usage:ge,capacity:hy.nullable(),remaining:Ay.nullable(),withinLimit:hn.boolean(),revision:hn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:hn.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 qt=T.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),An=T.iso.datetime({offset:!0}),yy=T.enum(["access","metered","credit"]),Li={internal_feature_id:T.uuid(),key:yr,name:T.string().min(1).max(120),kind:yy},Zd=T.object({customerId:T.uuid(),snapshotAt:An,memberships:T.array(T.object({id:T.uuid(),productId:T.string().min(1).max(255),productVersionId:T.uuid(),billingProductVersionId:T.uuid(),version:T.number().int().positive(),key:T.string().min(1).max(64),name:T.string().min(1).max(120),groupId:T.string().max(255).nullable(),membershipType:T.enum(["main","addon"]),status:T.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:T.boolean(),accessEnabled:T.boolean(),renewalChange:T.object({productVersionId:T.uuid(),name:T.string().min(1).max(120),version:T.number().int().positive(),effectiveAt:An,benefitsAppliedAt:An.nullable(),timing:T.enum(["immediate","renewal"]),changeKind:T.enum(["plan","seats","quantity"]),feature:T.strictObject({internal_feature_id:T.uuid(),name:T.string().min(1).max(80),fromQuantity:T.number().int().min(0).max(1e4),toQuantity:T.number().int().min(0).max(1e4)}).optional(),seat:T.object({key:T.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:T.number().int().min(0).max(1e4),toQuantity:T.number().int().min(0).max(1e4)}).strict().nullable(),status:T.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.object({phase:T.enum(["paid","trial"]),startsAt:An,endsAt:An.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:T.boolean(),balances:T.array(T.object({...Li,usageType:T.enum(["consumable","non_consumable"]).nullable(),accessible:T.boolean(),unlimited:T.boolean(),available:qt,held:qt,debt:qt,nextExpiresAt:An.nullable(),usage:Ui.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.boolean()}).strict(),Wd=T.enum(["source","usage","transaction","invoice","debt","settlement"]),Yo=T.object({at:An,id:T.uuid(),type:Wd}).strict(),Yd=T.object({type:Wd.nullable(),resourceKey:yr.optional(),kind:T.enum(["purchase","refund"]).optional(),topup:T.boolean().optional(),from:T.iso.date().nullable(),to:T.iso.date().nullable(),after:Yo.nullable(),limit:T.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),Qr={id:T.uuid(),occurredAt:An},by=T.discriminatedUnion("type",[T.strictObject({...Qr,type:T.literal("invoice"),status:T.string().min(1).max(80),paid:qt,refunded:qt,currency:he,externalId:T.string().nullable()}),T.object({...Qr,...Li,type:T.literal("source"),reason:T.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:qt,unlimited:T.boolean(),status:T.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:An,expiresAt:An.nullable(),orderId:T.uuid().nullable(),parentSourceId:T.uuid().nullable()}).strict(),T.object({...Qr,type:T.literal("usage"),internal_feature_id:T.uuid(),name:T.string().min(1).max(120),kind:T.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:T.uuid().nullable(),quantity:ge,accepted:T.boolean(),reason:T.enum([...Zo.options,"expired"]).nullable(),properties:gt,reservationStatus:T.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:An.nullable(),charges:T.array(T.discriminatedUnion("funding",[T.strictObject({funding:T.literal("balance"),sourceId:T.uuid(),rolloverId:T.uuid().nullable(),units:xr,amount:qt}),T.strictObject({funding:T.literal("unbilled"),units:xr}),T.object({...Li,funding:T.literal("prepaid"),amount:qt}).strict(),T.object({funding:T.literal("postpaid"),invoiceId:T.uuid(),invoiceLineId:T.uuid(),authorizationId:T.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.object({...Qr,type:T.literal("transaction"),purpose:T.enum(["product","invoice"]),productVersionId:T.uuid().nullable(),productName:T.string().min(1).max(120).nullable(),productVersion:T.number().int().positive().nullable(),invoiceId:T.uuid().nullable(),orderId:T.uuid(),originalId:T.uuid().nullable(),kind:T.enum(["purchase","refund"]),amountMinor:T.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.object({...Qr,...Li,type:T.literal("debt"),sourceId:T.uuid(),transactionId:T.uuid(),amount:qt}).strict(),T.object({...Qr,...Li,type:T.literal("settlement"),sourceId:T.uuid(),debtId:T.uuid(),kind:T.enum(["payment","usage_refund","payment_return"]),amount:qt}).strict()]),Xd=T.object({customerId:T.uuid(),rows:T.array(by).max(50),nextCursor:Yo.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as le}from"zod";var tp=le.object({customerId:le.uuid()}).strict(),np=le.discriminatedUnion("action",[le.object({customerId:le.uuid(),requestId:le.uuid(),action:le.literal("assign"),poolId:le.uuid(),memberCustomerId:le.uuid()}).strict(),le.strictObject({customerId:le.uuid(),requestId:le.uuid(),action:le.literal("assign_entity"),poolId:le.uuid(),entityId:le.uuid()}),le.object({customerId:le.uuid(),requestId:le.uuid(),action:le.literal("release"),poolId:le.uuid(),slotId:le.uuid()}).strict()]),zi=le.number().int().nonnegative(),Qs=le.iso.datetime({offset:!0}),Js=le.strictObject({internalId:le.uuid(),id:le.string(),name:le.string().nullable(),version:le.number().int().positive()}),ep=le.enum(["active","past_due"]),Zs=le.strictObject({customerId:le.uuid(),licenses:le.array(le.strictObject({id:le.uuid(),linkId:le.uuid(),parent:le.strictObject({customerProductId:le.uuid(),status:ep,product:Js}),product:Js,planLicense:le.strictObject({id:le.uuid(),prepaidOnly:le.boolean(),isCustom:le.boolean()}).nullable(),granted:zi,included:zi,paidQuantity:zi,usage:zi,remaining:zi,createdAt:Qs}).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.array(le.strictObject({id:le.uuid(),linkId:le.uuid(),status:ep,product:Js,entity:le.strictObject({internalId:le.uuid(),id:le.string().nullable(),name:le.string().nullable()}).nullable(),beneficiary:le.strictObject({internalId:le.uuid(),id:le.string().nullable(),name:le.string().nullable()}).nullable(),startedAt:Qs.nullable(),endedAt:Qs.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:le.boolean()});import{z as ue}from"zod";var $i=ue.enum(["email","sms","voice","push"]),pO=ue.enum(["resend","twilio","fcm","apns"]);var mO=ue.string().regex(/^\+[1-9]\d{1,14}$/),Sy=ue.enum(["email_recipient","sms_segment","voice_second","push_device"]);var xy=ue.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Iy=ue.strictObject({subject:xy,html:ue.string().min(1).max(131072).optional(),text:ue.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),vy=ue.strictObject({body:ue.string().min(1).max(1600).refine(e=>e.trim().length>0)}),wy=ue.strictObject({text:ue.string().trim().min(1).max(4e3),language:ue.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:ue.number().int().min(1).max(900)}),Oy=ue.record(ue.string().min(1).max(64),ue.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"),_y=ue.strictObject({title:ue.string().trim().min(1).max(200),body:ue.string().trim().min(1).max(2e3),url:ue.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:Oy.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),rp=ue.discriminatedUnion("channel",[ue.strictObject({channel:ue.literal("email"),content:Iy}),ue.strictObject({channel:ue.literal("sms"),content:vy}),ue.strictObject({channel:ue.literal("voice"),content:wy}),ue.strictObject({channel:ue.literal("push"),content:_y})]),ip=ue.strictObject({requestId:ue.uuid(),customerId:ue.uuid(),connectionId:ue.uuid().optional(),message:rp,expiresAt:ue.iso.datetime({offset:!0})}),Cy=ue.array(ue.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),Py=ue.discriminatedUnion("kind",[ue.strictObject({kind:ue.literal("all")}),ue.strictObject({kind:ue.literal("customers"),customerIds:Cy})]),fO=ue.strictObject({name:ue.string().trim().min(1).max(120),connectionId:ue.uuid().optional(),message:rp,audience:Py,frequencyLimit:ue.number().int().min(1).max(100)}),op=ue.strictObject({requestId:ue.uuid(),channel:$i,state:ue.enum(["allowed","denied"]),expectedRevision:ue.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),ap=ue.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),sp=ue.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),gO=ue.strictObject({meter:Sy,estimatedUnits:ue.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:ue.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as ve}from"zod";import{z as te}from"zod";import{z as Jr}from"zod";var Gi=Jr.strictObject({internalFeatureId:Jr.uuid(),name:Jr.string().min(1).max(120),includedAmount:Jr.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:Jr.enum(["hour","day","week","month","year","lifetime"]),resetCount:Jr.number().int().min(1).max(100),terms:Do});import{z as nt}from"zod";import{z as Ey}from"zod";import{z as Zr}from"zod";var cp=Zr.enum(["stripe","apple","google","merchant"]),up=Zr.enum(["membership","credit_pack","lifetime"]),xO=Zr.enum(["active","grace","suspended","inactive","revoked"]),IO=Zr.strictObject({currency:Zr.string().regex(/^[A-Z]{3}$/),micros:Zr.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var Wr=Ey.object({provider:cp,currency:he}).strict();var Yn=nt.strictObject({internal_feature_id:nt.uuid(),quantity:ge.refine(e=>/[1-9]/.test(e)),properties:gt,entityId:nt.uuid().optional()}),lp=nt.strictObject({requirement:Yn,commerce:Wr.optional(),paywallId:nt.uuid().optional()}),Ry=nt.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),Ws=nt.strictObject({productId:nt.string().min(1),productVersionId:nt.string().min(1),name:nt.string().min(1).max(120),action:nt.enum(["purchase","upgrade","addon","topup"]),membershipId:nt.string().min(1).nullable(),currency:he,amountMinor:nt.string().regex(/^(0|[1-9]\d{0,8})$/),interval:nt.enum(["free","week","month","year","one_time"]),intervalCount:nt.number().int().min(1).max(156)}),vr=nt.strictObject({internal_feature_id:nt.string().min(1),name:nt.string().min(1).max(120),kind:nt.enum(["access","metered","credit"]),quantity:ge,allowed:nt.boolean(),reason:Ry.nullable(),preview:nt.strictObject({scenario:nt.enum(["feature_flag","usage_limit"]),candidates:nt.array(Ws).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"})}),jO=nt.strictObject({paywallId:nt.uuid(),requirement:Yn});var ea=te.object({plan:te.string().min(1).max(200).optional(),coupon:te.uuid().optional(),promotionCode:te.uuid().optional(),picker:te.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),Xo=te.object({text:te.string().optional(),label:te.string().optional(),alt:te.string().optional(),html:te.string().max(32768).optional(),price:te.object({current:te.string(),original:te.string().nullable(),period:te.string()}).optional(),code:te.string().optional(),countdownAt:te.iso.datetime().optional(),planId:te.string().min(1).max(200).optional(),planVersionId:te.string().min(1).max(200).optional(),currency:he.optional(),couponId:te.uuid().optional(),offerId:te.uuid().optional(),unavailable:te.boolean().optional(),unavailableReason:te.string().optional(),missing:te.array(te.string()).optional()}).strict(),Yr=te.object({paywall:vr.optional(),nodes:te.record(te.string(),te.object({base:Xo,picker:te.string().optional(),byPlan:te.record(te.string(),Xo).optional()}).strict()),plans:te.record(te.string(),te.object({id:te.string().min(1).max(200),versionId:te.string().min(1).max(200),available:te.boolean(),name:te.string(),price:te.string(),period:te.string(),currency:he.optional(),amountMinor:te.number().int().nonnegative().optional(),interval:te.enum(["free","week","month","year","one_time"]).optional(),intervalCount:te.number().int().positive().optional(),prepaid:te.array(Gi).max(100).optional()}).strict()),pickers:te.record(te.string(),te.object({options:te.array(te.string().min(1).max(200)).max(20),selected:te.string().min(1).max(200).nullable()}).strict()),quantities:te.record(te.string(),te.strictObject({minimum:te.number().int().nonnegative(),maximum:te.number().int().nonnegative(),step:te.number().int().positive(),value:te.number().int().nonnegative(),label:te.string(),available:te.boolean()})).optional(),diagnostics:te.array(te.object({nodeId:te.string(),message:te.string()}).strict())}).strict();function dp(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as x}from"zod";function ky(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function pp(e){let t={};function n(r){var i;if(ky(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}import{z as qn}from"zod";var mp=qn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ta=qn.strictObject({tiers:qn.array(qn.strictObject({id:mp,name:qn.string().trim().min(1).max(80)})).min(1).max(8),assignments:qn.array(qn.strictObject({productVersionId:qn.string().min(1).max(200),tierId:mp,period:qn.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 na(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as oe}from"zod";var jy=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],fp=oe.enum(jy),gp=oe.object({source:fp,layout:oe.enum(["full","compact"]),resourceKey:yr.optional(),pageSize:oe.number().int().min(1).max(50),showSources:oe.boolean(),allowPurchase:oe.boolean(),outputs:oe.object({billing_adjustment:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:oe.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"})}),vt=oe.string().max(2e3),hp=oe.object({id:oe.string().max(100),label:vt,detail:oe.array(vt).max(12),value:vt.optional(),status:vt.optional(),facts:oe.array(oe.object({label:vt,value:vt}).strict()).max(1e3),purchaseId:oe.uuid().optional(),invoiceUrl:oe.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:oe.array(oe.strictObject({action:oe.literal("invoice_open"),label:vt})).max(1).optional(),membershipActions:oe.array(oe.object({value:oe.string().max(100),label:vt}).strict()).max(3).optional()}).strict(),Ty=oe.object({key:yr,name:vt,spendable:vt,reserved:vt,available:vt,expiry:vt.nullable(),sources:oe.array(hp).max(50),sourceCount:oe.number().int().nonnegative(),sourcePage:oe.number().int().positive(),hasNextSources:oe.boolean(),hasPreviousSources:oe.boolean()}).strict(),Ny=oe.object({source:fp,status:oe.enum(["idle","loading","ready","error"]),stale:oe.boolean(),preview:oe.boolean(),errorCode:oe.string().max(80).optional(),errorMessage:vt.optional(),resources:oe.array(Ty).max(500),rows:oe.array(hp).max(50),hasNext:oe.boolean(),hasPrevious:oe.boolean(),page:oe.number().int().positive(),filter:oe.string().max(40),updatedAt:oe.iso.datetime().optional(),buyingId:oe.uuid().optional(),membershipBusy:oe.boolean().optional(),billingBusy:oe.boolean().optional(),membershipReview:oe.object({title:vt,note:vt,facts:oe.array(oe.object({label:vt,value:vt}).strict()).max(100)}).strict().optional(),membershipResult:vt.optional()}).strict(),Ap=oe.object({nodes:oe.record(oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Ny)}).strict(),$O=oe.object({nodeId:oe.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:oe.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.string().max(100).optional()}).strict();var Fy=4,bn={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Hi=x.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Te=x.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),My=x.enum(["none","xs","sm","md","lg","xl"]),qy=x.enum(["none","sm","md","lg","full"]),Ys=x.string().regex(/^#[0-9a-fA-F]{6}$/),Sp=x.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"),Xs=x.union([Sp,x.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),x.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),x.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),yp=x.object({primary:Ys,background:Ys,text:Ys,radius:qy,font:x.enum(["system","serif","rounded","mono"])}).strict(),Qi=x.union([x.enum(["primary","text","muted","background","surface"]),x.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),je=(e,t)=>x.number().int().min(e).max(t),bp=x.union([x.enum(["fit","fill"]),je(1,1200)]),Vy=x.object({top:je(0,200),right:je(0,200),bottom:je(0,200),left:je(0,200)}).strict(),By=x.object({top:je(-100,200),right:je(-100,200),bottom:je(-100,200),left:je(-100,200)}).strict(),xp=x.object({x:je(0,100),y:je(0,100)}).strict(),Uy=x.discriminatedUnion("type",[x.object({type:x.literal("color"),color:Qi}).strict(),x.object({type:x.literal("linear"),angle:je(0,360),stops:x.array(x.object({color:Qi,at:je(0,100)}).strict()).min(2).max(4)}).strict(),x.object({type:x.literal("image"),src:Xs,fit:x.enum(["cover","contain"]),position:xp.optional()}).strict()]),Ly=x.discriminatedUnion("type",[x.object({type:x.literal("rect"),radius:x.union([je(0,200),x.object({topLeft:je(0,200),topRight:je(0,200),bottomRight:je(0,200),bottomLeft:je(0,200)}).strict()])}).strict(),x.object({type:x.literal("pill")}).strict()]),zy=x.object({width:je(0,12),color:Qi,style:x.enum(["solid","dashed"])}).strict(),$y=x.object({x:je(-40,40),y:je(-40,40),blur:je(0,80),spread:je(-20,40),color:Qi}).strict(),Gy=x.object({font:x.enum(["system","serif","rounded","mono"]),size:je(8,96),weight:x.number().int().min(100).max(900).multipleOf(100),lineHeight:x.number().min(.8).max(3),letterSpacing:x.number().min(-5).max(20),color:Qi,align:x.enum(["start","center","end"]),italic:x.boolean(),decoration:x.enum(["none","underline","line-through"]),transform:x.enum(["none","uppercase"])}).strict().partial(),wr=x.object({width:bp,height:bp,padding:Vy,margin:By,gap:je(0,120),grow:x.union([x.boolean(),x.number().min(0).max(12)]),background:Uy,opacity:x.number().min(0).max(1),clipContent:x.boolean(),shape:Ly,border:zy,shadow:$y,text:Gy}).strict().partial(),Jt={id:Hi,name:x.string().trim().min(1).max(60).optional(),hidden:x.boolean().optional(),style:wr.optional(),fallback:Te.optional()},Ky=x.object({...Jt,type:x.literal("text"),productField:x.enum(["name","price","trial","period"]).optional(),feature:x.object({id:x.uuid(),field:x.enum(["name","allowance"])}).strict().optional(),text:Te,variant:x.enum(["title","heading","body","caption"])}).strict(),Hy=x.object({...Jt,type:x.literal("image"),src:Xs,localizedSrc:x.record(gn,Xs).optional(),alt:Te,aspect:x.enum(["auto","1:1","4:3","16:9","3:1"]),fit:x.enum(["cover","contain"]),position:xp.optional()}).strict(),Qy=x.object({...Jt,type:x.literal("button"),label:Te,variant:x.enum(["primary","secondary","link"]),action:Te,purpose:x.enum(["purchase","navigation","close"]).optional(),bind:ea.optional()}).strict(),Jy=x.object({...Jt,type:x.literal("divider")}).strict(),Zy=x.object({...Jt,type:x.literal("customer_data"),title:Te,data:gp}).strict(),Wy=x.object({...Jt,type:x.literal("spacer"),size:My}).strict(),Yy=x.object({...Jt,type:x.literal("custom_html"),html:x.record(gn,x.string().max(bn.customHtml)),css:x.string().max(bn.customCss)}).strict(),Xy=x.object({...Jt,type:x.literal("price"),fallback:Te,parts:x.object({current:wr.optional(),original:wr.optional(),period:wr.optional()}).strict().optional()}).strict(),eb=x.object({...Jt,type:x.literal("coupon_code"),label:Te,fallback:Te}).strict(),tb=x.object({...Jt,type:x.literal("countdown"),source:x.enum(["offer.ends_at","offer.expires_at","fixed"]),at:x.iso.datetime().optional(),granularity:x.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"),nb=x.object({...Jt,type:x.literal("plan_picker"),label:Te,fallback:Te,planIds:x.array(x.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:x.string().min(1).max(200).optional(),grouping:ta.safeExtend({monthLabel:Te,yearLabel:Te,unavailableLabel:Te}).optional(),states:x.object({selected:wr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!na(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),rb=x.object({...Jt,type:x.literal("quantity_picker"),bind:ea.optional(),label:Te,fallback:Te,internalFeatureId:x.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"),ib=x.discriminatedUnion("type",[x.object({type:x.literal("input"),label:Te,keyboard:x.enum(["text","email","tel","url"]),maxLength:je(1,500)}).strict(),x.object({type:x.literal("multiselect"),label:Te,min:je(0,50),max:je(1,50)}).strict(),x.object({type:x.literal("select"),label:Te,defaultIndex:je(0,49),purpose:x.enum(["option","product","tier"]).optional(),pickerId:Hi.optional(),selectedStyle:wr.optional()}).strict(),x.object({type:x.literal("tabs"),label:Te,defaultIndex:je(0,49),purpose:x.literal("tier").optional()}).strict(),x.object({type:x.literal("toggle"),label:Te,defaultEnabled:x.boolean()}).strict(),x.object({type:x.literal("carousel"),label:Te}).strict()]),yn={...Jt,type:x.literal("stack"),direction:x.enum(["vertical","horizontal","overlay"]),align:x.enum(["start","center","end","stretch"]),justify:x.enum(["start","center","end","between"]),productSlot:x.object({index:je(0,19),period:x.enum(["month","year"]).optional(),requireBinding:x.boolean().optional()}).strict().optional(),interaction:ib.optional(),states:x.object({selected:wr.optional()}).strict().optional(),purpose:x.literal("benefits").optional(),purchaseAction:Te.optional(),buttonVariant:x.enum(["primary","secondary","link"]).optional(),bind:ea.optional()},Ip=x.lazy(()=>x.object({...Jt,type:yn.type,direction:yn.direction,align:yn.align,justify:yn.justify,children:x.array(ob).max(bn.children),productSlot:yn.productSlot,interaction:yn.interaction,states:yn.states,purpose:yn.purpose,purchaseAction:yn.purchaseAction,buttonVariant:yn.buttonVariant,bind:yn.bind}).strict()),ob=x.lazy(()=>x.union([Ip,Ky,Hy,Qy,Jy,Wy,Yy,Xy,eb,tb,nb,rb,Zy])),ab=x.union([x.string().max(500),x.number().finite(),x.boolean(),x.null()]),Ki={id:Te,event:Te,properties:x.record(Te,ab).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},sb=x.discriminatedUnion("type",[x.object({...Ki,type:x.literal("navigate"),close:x.literal(!1),pageId:Hi}).strict(),x.object({...Ki,type:x.literal("event"),close:x.boolean()}).strict(),x.object({...Ki,type:x.literal("close"),close:x.literal(!0)}).strict(),x.object({...Ki,type:x.literal("open_url"),close:x.boolean(),url:Sp}).strict(),x.object({...Ki,type:x.literal("claim_offer"),close:x.boolean(),couponId:x.uuid()}).strict()]),cb=x.object({defaultLocale:gn,locales:x.record(gn,x.record(Te,x.string().max(bn.stringLength)))}).strict(),ub=x.enum(["popup","paywall","onboarding","page","banner"]);var lb=x.discriminatedUnion("type",[x.object({type:x.literal("modal"),size:x.enum(["sm","md","lg"])}).strict(),x.object({type:x.literal("sheet"),size:x.enum(["sm","md","lg"])}).strict(),x.object({type:x.literal("fullscreen")}).strict(),x.object({type:x.literal("inline")}).strict()]);var db=x.object({kind:x.literal("screen"),schemaVersion:x.literal(Fy),name:x.string().trim().min(1).max(80),surface:ub,initialPageId:Hi.optional(),presentation:lb,theme:yp,pages:x.array(x.object({id:Hi,name:x.string().trim().min(1).max(60),root:Ip,theme:yp.optional(),editorPosition:x.object({x:x.number().finite().min(-1e5).max(1e5),y:x.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(bn.pages),strings:cb,actions:x.array(sb).max(bn.actions)}).strict();function Vt(e,t){for(let n of e.pages)Vn(n.root,t)}var nn=db.superRefine((e,t)=>{let n=bn;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(m=>m.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>bn.locales&&r(`\u6700\u591A ${bn.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Vt(e,(l,m)=>{if(c++,m>bn.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let S of Object.keys(l.html))i.includes(S)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${S}`);if(l.type==="image")for(let S of Object.keys(l.localizedSrc??{}))i.includes(S)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${S}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${bn.depth} \u5C42`)});function Vn(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)Vn(i,t,n+1,e)}function ra(e){let t=[],n=new Set;return Vt(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 pb(e,t,n){if(t.field==="html"){let r;return Vt(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=Ji(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 Xn(e){let t=ra(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=>!pb(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 mb(e,t){let n=null;return Vn(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function Ji(e,t){for(let n of e.pages){let r=mb(n.root,t);if(r)return r}return null}import{z as jt}from"zod";var ft=jt.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"),ec=jt.strictObject({type:jt.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:jt.boolean(),enum:jt.array(jt.string().max(255)).min(1).max(100).optional()}),Xr=ec.extend({type:jt.enum([...ec.shape.type.options,"array"]),items:ec.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"})}),ei=Xr.safeExtend({source:jt.discriminatedUnion("type",[jt.strictObject({type:jt.literal("input")}),jt.strictObject({type:jt.literal("node")}),jt.strictObject({type:jt.enum(["parameter","attribute"]),key:ft})])}),t_=jt.record(ft,ei),tc=jt.record(ft,ft).refine(e=>Object.keys(e).length<=20);function un(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=>un(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&&jt.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 nc(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&&nc(e.items,t.items)}function ia(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 l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!un(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function ti(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 vp(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"||!un(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as Or}from"zod";var Sn=Or.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"),_n=Or.discriminatedUnion("source",[Or.strictObject({source:Or.literal("literal"),value:Ae}),Or.strictObject({source:Or.literal("variable"),key:Or.string().min(1).max(255),path:Sn.optional()})]);function wp(e,t){if(!t)return e;for(let n of Sn.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 rc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ia(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Ae.parse(wp(n[e.key],e.path)))}function ic(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&&!Sn.safeParse(r).success?null:{key:n,path:r}}function oc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Vt(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(dp))]}function oa(e){return oc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function rn(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),m=l.replace(".","").length,S=(l.includes(".")?l.indexOf("."):m)+Number(u),y=S<=0?2-S+m:S>=m?S:m+1;n+=y+(c.startsWith("-")?1:0)-s.length}}return n}var er=ve.enum(["page","popup","banner"]),fb=3e5,Op=ve.strictObject({type:ve.enum(["string","number","boolean","strings","json"]),nullable:ve.boolean()}),gb=ve.strictObject({inputs:ve.record(Te,Op.extend({required:ve.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:ve.record(Te,Op).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),hb=ve.strictObject({kind:er,schemaVersion:ve.literal(1),name:ve.string().trim().min(1).max(80),screen:nn,contract:gb}),aa=hb.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"]),rn(e)>fb&&n("Content document exceeds its byte budget",[])});function Ab(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 yb=aa.superRefine((e,t)=>{for(let n of oa(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&&!Ab(i,r)&&t.addIssue({code:"custom",path:["contract","outputs",n.id],message:"Action value differs from its declared type"})}Xn(e.screen).some(n=>!n.complete)&&t.addIssue({code:"custom",path:["screen","strings"],message:"Content needs complete localized copy"})}),_p=ve.strictObject({id:ve.uuid(),kind:er,projectId:ve.uuid(),environmentId:ve.uuid(),name:ve.string(),revision:ve.number().int().nonnegative(),status:ve.enum(["draft","published","archived"]),publishedVersionId:ve.uuid().nullable(),createdAt:ve.iso.datetime({offset:!0}),updatedAt:ve.iso.datetime({offset:!0})}),A_=_p.extend({draft:aa}),y_=ve.strictObject({rows:ve.array(_p).max(200),nextCursor:ve.uuid().nullable()}),ac=ve.strictObject({id:ve.uuid(),kind:er,resourceId:ve.uuid(),projectId:ve.uuid(),environmentId:ve.uuid(),version:ve.number().int().positive(),sourceRevision:ve.number().int().nonnegative(),document:yb,createdAt:ve.iso.datetime({offset:!0})}),b_=ac.omit({document:!0}),S_=ve.discriminatedUnion("action",[ve.strictObject({action:ve.literal("create"),kind:er,id:ve.uuid(),document:aa}),ve.strictObject({action:ve.literal("save"),kind:er,id:ve.uuid(),revision:ve.number().int().nonnegative(),document:aa}),ve.strictObject({action:ve.enum(["publish","archive"]),kind:er,id:ve.uuid(),revision:ve.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as Cp}from"zod";var ni={funnelId:Cp.uuid().optional(),funnelVersionId:Cp.uuid().optional()};import{z as et}from"zod";import{z as Me}from"zod";import{z as Ze}from"zod";var O_=Ze.discriminatedUnion("action",[Ze.strictObject({action:Ze.literal("create"),couponId:Ze.uuid(),productBindingId:Ze.uuid(),storeOfferId:Ze.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ze.enum(["introductory","promotional"])}),Ze.strictObject({action:Ze.literal("set_enabled"),id:Ze.uuid(),revision:Ze.number().int().nonnegative(),enabled:Ze.boolean()})]),__=Ze.array(Ze.strictObject({id:Ze.uuid(),couponId:Ze.uuid(),productBindingId:Ze.uuid(),storeOfferId:Ze.string().min(1).max(255).nullable(),storeOfferType:Ze.enum(["introductory","promotional"]),enabled:Ze.boolean(),revision:Ze.number().int().nonnegative()})).max(500),ri=Ze.strictObject({offerKind:Ze.enum(["none","introductory","promotional"]),offerId:Ze.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ze.number().int().min(0).max(1e8),trialDays:Ze.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"})}),C_=Ze.record(Ze.uuid(),ri).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var sc=Me.object({type:Me.literal("native_purchase"),receiptId:Me.uuid(),orderId:Me.uuid(),productVersionId:Me.uuid(),provider:Me.enum(["apple","google"]),productId:Me.string().min(1).max(255),productKind:up,replacement:Me.strictObject({sourceOrderId:Me.uuid(),sourceProductId:Me.string().min(1).max(255),policy:Me.enum(["apple_store","google_full_price"]),sourceAccountTokens:Me.array(Me.uuid()).max(50)}).nullable(),appAccountToken:Me.uuid().optional(),obfuscatedAccountId:Me.string().min(1).max(64).optional(),obfuscatedProfileId:Me.uuid().optional(),basePlanId:Me.string().min(1).max(255).optional(),offerId:Me.string().min(1).max(255).optional(),offerKind:Me.enum(["none","introductory","promotional"]),currency:he,catalogAmountMinor:Me.number().int().nonnegative().max(1e8),discountMinor:Me.number().int().nonnegative().max(1e8),trialDays:Me.number().int().min(1).max(730).nullable(),seatBundle:Me.array(Me.strictObject({key:Me.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:Me.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:Me.strictObject({offerId:Me.string().min(1).max(255),keyId:Me.string().min(1).max(255),nonce:Me.uuid(),signature:Me.string().min(1).max(1024),timestamp:Me.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as d}from"zod";import{z as we}from"zod/v4";import{z as bb}from"zod/v4";var Sb=bb.registry(),{BillingInterval:Pp}=(()=>{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:xb}=(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),{withSpecDefault:Ib}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Sb),{COMMON:Ep}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:vb}={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:wb}=(e=>({COMMON_SET:new Set(e)}))(Ep),{hasNoDuplicateCurrencies:Rp}={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:kp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:Ob}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(we),{Infinite:_b}={Infinite:"inf"},{TierBehavior:Cb}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:jp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Pb}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Eb}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Rb}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:kb}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(we),{ApiCreditTierSchema:Tp}=(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),{VIOLATION_MESSAGES:jb}={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:Np}=(e=>({MarkupEntrySchema:e.object({markup:e.number().min(-100)})}))(we),{ModelMarkupsSchema:Tb}=((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,Np),{InvoiceUsageEntrySchema:Nb}=(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),{AttachDiscountSchema:Dp}=(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),{CustomLineItemSchema:Db}=(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),{UnixMsTimestampSchema:Fb}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(we),{CreateInvoicePreviewLineSchema:Mb}=(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),{ReissueInvoiceParamsSchema:Fp}=(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),{InvoiceModeParamsSchema:_r}=(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),{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),{BasePriceSchema:Vb}=((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,Pp,xb),{CURRENCY_CODES:Bb}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(Ep,vb,wb),{ApiPriceProcessorsSchema:Mp}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(we,Ob),{AllocatedBillingFieldSchema:Ub}=((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,Pb),{CreditDimensionNameSchema:Lb}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(we,Eb,Rb),{ApiCreditMatchSchema:qp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(kb),{findCreditTierViolations:zb}=(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}}))(jb),{ApiCreditMultiplierSchema:$b}=((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,qp),{ProviderMarkupsSchema:Gb}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(we,Np),{InvoiceFeatureQuantitySchema:Vp}=((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,jp,Nb),{CreateInvoicePreviewSchema:cc}=((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,Mb),{SUPPORTED_SET:Kb}=(e=>({SUPPORTED_SET:new Set(e)}))(Bb),{ApiCreditDimensionBaseSchema:Hb}=((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,qp),{refineGraduatedTiers:Bp}=(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"]})}}))(zb),{ApiFeatureMarkupsOverrideSchema:Qb}=((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,Gb,Tb),{isValidCurrencyCode:Jb}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(Kb),{ApiCreditDimensionSchema:Zb}=((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,Hb,Tp,Bp),{CurrencyCodeSchema:Up}=((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,Jb),{AdditionalCurrencyTierSchema:Wb}=((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,Up),{ApiCreditSchemaItemBaseSchema:Lp}=((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,Lb,Zb,$b),{ApiFlatCreditSchemaItemSchema:Yb}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(Lp,we),{AdditionalCurrencyPriceSchema:Xb}=((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,Up),{AdditionalCurrencyTierArraySchema:eS}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(we,Wb,Rp,kp),{ApiGraduatedCreditSchemaItemSchema:tS}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(Lp,we,Tp,Bp),{AdditionalCurrencyPriceArraySchema:zp}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(we,Xb,Rp,kp),{ApiUsageTierWithCurrenciesSchema:nS}=((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,_b,eS),{ApiCreditSchemaItemSchema:rS}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(we,tS,Yb),{BasePriceParamsSchema:iS}=((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."})}))(Vb,Ib,we,zp),{PlanItemPriceParamsSchema:oS}=((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,zp,nS,Cb,Pp,jp,Ub),{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,rS,Qb),{InvoiceBasePriceParamsSchema:$p}=((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()}))(iS,Mp),{InvoiceItemPriceParamsSchema:sS}=((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()}))(oS,Mp),{InvoiceLicenseQuantitySchema:cS}=((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,$p,Vp),{InvoiceCustomizeItemSchema:uS}=((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,sS,aS),{InvoiceCustomizeSchema:lS}=((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,$p,uS),{InvoicePlanParamsSchema:dS}=((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,lS,Vp,cS,Dp),{CreateInvoiceParamsSchema:ii}=((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,dS,Db,Dp,Fb);var Hp=d.strictObject({requestId:d.uuid(),predecessorOperationId:d.uuid().optional(),invoiceMode:_r.optional(),entityId:d.uuid().optional(),billingSubscriptionId:d.uuid().optional(),newBillingSubscription:d.literal(!0).optional(),offerId:d.uuid().optional(),nativeOffer:ri.optional(),plans:d.array(d.strictObject({productVersionId:d.uuid(),seatQuantities:d.record(Eo,d.number().int().min(0).max(1e4)).optional(),featureQuantities:d.record(d.uuid(),d.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:d.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"),Pr=d.strictObject({operationId:d.uuid()}),Pt=d.number().int().min(0).max(1e8),pS=d.strictObject({lineId:d.uuid(),productVersionId:d.uuid(),productName:d.string().min(1).max(80),interval:d.enum(["free","week","month","year","one_time"]),intervalCount:d.number().int().min(1).max(156).optional(),baseAmountMinor:Pt,seats:d.array(d.strictObject({key:Eo,quantity:d.number().int().min(0).max(1e4),includedQuantity:d.number().int().min(0).max(1e4),maximumQuantity:d.number().int().min(0).max(1e4),unitAmountMinor:Pt})).max(20),prepaid:d.array(Md).max(100).optional(),catalogAmountMinor:Pt,trial:d.strictObject({days:d.number().int().min(1).max(730),cardRequired:d.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+No({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"),Qp=d.string().regex(/^[A-Za-z0-9_-]{1,200}$/),mS=d.strictObject({id:Qp,name:d.string().min(1).max(40),percent_off:d.number().gt(0).max(100).optional(),amount_off:d.number().int().positive().optional(),currency:d.string().regex(/^[a-z]{3}$/).optional(),duration:d.enum(["once","repeating","forever"]),duration_in_months:d.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"),fS=d.strictObject({subscriptionId:d.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:d.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:d.array(d.strictObject({id:d.string(),price_id:d.string(),quantity:d.number().int().nonnegative(),discounts:d.array(d.strictObject({id:d.string(),coupon:d.string(),start:d.number(),end:d.number().nullable()})).optional()})).min(1).max(100),prorationDate:d.number().int().nonnegative(),amountMinor:d.number().int().positive(),periodStartMs:d.number(),periodEndMs:d.number()}),Jp=d.strictObject({invoiceMode:_r.optional(),append:fS.optional(),provider:d.literal("stripe"),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),mode:d.enum(["payment","subscription"]),lineItems:d.array(d.strictObject({price:d.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:d.number().int().min(1).max(1e4),priceId:d.uuid(),productName:d.string().min(1).max(80),amountMinor:d.number().int().min(0).max(1e8),currency:d.string().regex(/^[a-z]{3}$/),interval:d.enum(["week","month","year","one_off"]),intervalCount:d.number().int().min(1).max(52),slot:d.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:d.strictObject({mode:d.enum(["graduated","volume"]),tiers:d.array(d.strictObject({upTo:d.number().int().min(1).max(1e6).nullable(),unitAmountMinor:d.number().int().min(0).max(1e8),flatAmountMinor:d.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:d.array(d.strictObject({coupon:Qp,terms:mS})).max(1),trialPeriodDays:d.number().int().min(1).max(730).nullable(),metadata:d.strictObject({grooveCheckoutId:d.uuid(),grooveCustomerId:d.uuid()}),expiresAt:d.iso.datetime({offset:!0})}),oi=d.strictObject({operationId:d.uuid(),entityId:d.uuid().nullable(),billingSubscriptionId:d.uuid().nullable(),discount:d.strictObject({offerId:d.uuid(),couponId:d.uuid(),discount:Zn,duration:en,amountMinor:Pt,allocations:d.array(d.strictObject({productVersionId:d.uuid(),amountMinor:Pt})).min(1).max(20),expiresAt:d.iso.datetime({offset:!0})}).nullable(),charge:d.strictObject({effectiveAt:d.iso.datetime({offset:!0}),periodEndsAt:d.iso.datetime({offset:!0}),debitMinor:Pt,discountMinor:Pt,taxMinor:Pt,totalMinor:Pt}).nullable(),expiresAt:d.iso.datetime({offset:!0}),provider:d.enum(["stripe","apple","google","merchant"]),nativeOffer:ri.optional(),currency:he,lines:d.array(pS).min(1).max(20),catalogAmountMinor:Pt,automaticTax:d.boolean(),execution:d.union([Jp,wo]).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"),ai=d.strictObject({operationId:d.uuid(),orderId:d.uuid(),append:d.boolean().optional(),invoiceMode:d.boolean().optional(),status:d.enum(["pending","complete","cancelled","failed"]),executor:d.enum(["indiana","merchant"]),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:d.union([Jp,wo]).nullable(),currency:he,catalogAmountMinor:Pt,taxMinor:Pt,totalMinor:d.number().int().min(0).max(2e8).nullable(),quoteFinalized:d.boolean(),nativePurchase:sc.nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),quote:oi.optional(),merchantExecution:hr.nullable().optional(),problem:_i.nullable().optional(),authority:Po.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"),ca=d.strictObject({enabled:d.literal(!0),featureIds:d.array(d.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),Zp=d.strictObject({requestId:d.uuid(),invoiceMode:_r.optional(),membershipId:d.uuid(),carryOverBalances:ca.optional(),carryOverUsages:ca.optional(),membershipIds:d.array(d.uuid()).min(1).max(20).optional(),prorationBehavior:d.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:d.enum(["immediate","renewal","store"]),change:d.discriminatedUnion("type",[d.strictObject({type:d.literal("plan"),productVersionId:d.uuid()}),d.strictObject({type:d.literal("seats"),licenseKey:Eo,quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("quantity"),internal_feature_id:d.uuid(),quantity:d.number().int().min(0).max(1e4)}),d.strictObject({type:d.literal("cancel")}),d.strictObject({type:d.literal("uncancel")}),d.strictObject({type:d.literal("billing_cycle"),billingCycleAnchor:d.union([d.literal("now"),d.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"),sa=d.string().regex(/^price_[A-Za-z0-9]+$/),Gp=d.strictObject({grooveUpdateId:d.uuid(),grooveCustomerId:d.uuid()}),Kp=d.strictObject({price:sa.nullable(),priceId:d.uuid().optional(),quantity:d.number().int().min(0).max(1e4)}),Wp=d.strictObject({provider:d.literal("stripe"),invoiceMode:_r.optional(),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:d.string().regex(/^sub_[A-Za-z0-9]+$/),action:d.enum(["update","cancel","schedule","release"]),update:d.strictObject({items:d.array(Kp).max(20),remove:d.array(sa).max(20),restoreItems:d.array(d.strictObject({price:sa,quantity:d.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:d.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:d.number().int().positive().optional(),paymentBehavior:d.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:d.boolean().optional(),clearCancelAt:d.literal(!0).optional(),billingCycleAnchorNow:d.literal(!0).optional(),metadata:Gp}).nullable(),cancel:d.strictObject({prorate:d.literal(!1),invoiceNow:d.literal(!1)}).nullable(),schedule:d.strictObject({currentItems:d.array(d.strictObject({price:sa,quantity:d.number().int().min(0).max(1e4)})).max(20),nextItems:d.array(Kp).min(1).max(20),switchAt:d.number().int().positive(),interval:d.enum(["week","month","year"]),intervalCount:d.number().int().min(1).max(52),resetBillingCycleAnchor:d.literal(!0).optional(),metadata:Gp}).nullable(),release:d.strictObject({schedule:d.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:d.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"),ua=d.strictObject({carryOverBalances:ca.optional(),carryOverUsages:ca.optional(),operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),expiresAt:d.iso.datetime({offset:!0}),currency:he,creditMinor:Pt,debitMinor:Pt,discountMinor:Pt,taxMinor:Pt,totalMinor:Pt,retainedProductVersionIds:d.array(d.uuid()).max(19),execution:d.union([Wp,Oo])}),gS=d.strictObject({operationId:d.uuid(),invoiceMode:d.boolean().optional(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:d.enum(["immediate","renewal"]),effectiveAt:d.iso.datetime({offset:!0}),checkoutUrl:d.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:d.enum(["indiana","merchant"]),execution:d.union([Wp,Oo]).nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:hr.nullable().optional(),problem:_i.nullable().optional(),quote:ua.optional(),authority:Po.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),hS=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),timing:d.literal("store"),effectiveAt:d.null(),expiresAt:d.iso.datetime({offset:!0}),currency:he,creditMinor:d.null(),debitMinor:d.null(),discountMinor:d.null(),taxMinor:d.null(),totalMinor:d.null(),retainedProductVersionIds:d.array(d.uuid()).max(19),store:d.strictObject({provider:d.enum(["apple","google"]),productId:d.string().min(1).max(255),catalogAmountMinor:Pt,policy:d.enum(["apple_store","google_full_price"])})}),AS=d.strictObject({operationId:d.uuid(),membershipId:d.uuid(),productVersionId:d.uuid(),status:d.enum(["prepared","pending","effective","cancelled","failed"]),timing:d.literal("store"),effectiveAt:d.iso.datetime({offset:!0}).nullable(),checkoutUrl:d.null(),nativePurchase:sc.nullable()}),Yp=d.union([ua,hS]),uc=d.union([gS,AS]),Zi=d.number().int().positive().max(2e8),Cr=d.number().int().min(0).max(2e8),Xp=d.strictObject({requestId:d.uuid(),invoiceId:d.uuid(),mode:d.enum(["full","partial"]),amountMinor:Zi.optional(),entitlementAction:d.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),em=d.strictObject({provider:d.literal("stripe"),executor:d.enum(["indiana","merchant"]),accountId:d.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:d.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:Zi,currency:d.string().regex(/^[a-z]{3}$/),metadata:d.strictObject({indianaRefundId:d.uuid()}),idempotencyKey:d.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:d.array(d.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),lc=d.strictObject({operationId:d.uuid(),invoiceId:d.uuid(),providerInvoiceId:d.string().min(1).max(200),currency:he,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,amountMinor:Zi,mode:d.enum(["full","partial"]),entitlementAction:d.enum(["retain","revoke"]),revokes:d.strictObject({customerProductIds:d.array(d.uuid()).max(100),subscriptionIds:d.array(d.string().min(1).max(200)).max(20)}),execution:d.union([em,_o]),expiresAt:d.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"),la=d.strictObject({operationId:d.uuid(),invoiceId:d.uuid(),providerInvoiceId:d.string().min(1).max(200),status:d.enum(["quoted","pending","succeeded","failed","expired"]),executor:d.enum(["indiana","merchant"]),currency:he,amountMinor:Zi,mode:d.enum(["full","partial"]),entitlementAction:d.enum(["retain","revoke"]),refundId:d.string().min(1).max(200).nullable(),quote:lc.optional(),execution:d.union([em,_o]).nullable(),confirmedAt:d.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:hr.nullable().optional(),problem:_i.nullable().optional(),authority:Po.optional(),failureReason:d.string().min(1).max(200).nullable(),createdAt:d.iso.datetime({offset:!0}),completedAt:d.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"),H_=d.strictObject({invoiceId:d.uuid(),currency:he,paidMinor:Cr,refundedMinor:Cr,pendingMinor:Cr,refundableMinor:Cr,executor:d.enum(["indiana","merchant"]).nullable(),canRefund:d.boolean(),operations:d.array(la).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),Q_=d.strictObject({requestId:d.uuid(),mode:d.enum(["full","partial"]),amountMinor:Zi.optional(),entitlementAction:d.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 tm=et.strictObject({requestId:et.uuid(),targets:et.array(et.strictObject({membershipId:et.uuid(),action:et.enum(["cancel","uncancel"]),timing:et.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"),da=et.strictObject({batchId:et.uuid()}),yS=et.strictObject({operationId:et.uuid(),membershipIds:et.array(et.uuid()).min(1).max(20),provider:et.enum(["stripe","apple","google"]),action:et.enum(["cancel","uncancel"]),timing:et.enum(["immediate","renewal"]),status:et.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:ua.nullable(),managementUrl:et.url().nullable(),failureCode:et.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),Wi=et.strictObject({batchId:et.uuid(),ready:et.boolean(),status:et.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:et.iso.datetime({offset:!0}),acceptedAt:et.iso.datetime({offset:!0}).nullable(),groups:et.array(yS).min(1).max(100)});import{z as Pe}from"zod";var bS=Pe.string().trim().min(1).max(240),dc={requestId:Pe.uuid(),reason:bS},pa=Pe.discriminatedUnion("action",[Pe.strictObject({...dc,action:Pe.literal("start"),productVersionId:Pe.uuid(),entityId:Pe.uuid().optional(),days:Pe.number().int().min(1).max(730).optional()}),Pe.strictObject({...dc,action:Pe.literal("extend"),membershipId:Pe.uuid(),days:Pe.number().int().min(1).max(730)}),Pe.strictObject({...dc,action:Pe.literal("end"),membershipId:Pe.uuid()})]),nm=Pe.strictObject({operationId:Pe.uuid()}),rm=Pe.iso.datetime({offset:!0}),SS=Pe.strictObject({provider:Pe.literal("stripe"),executor:Pe.enum(["indiana","merchant"]),accountId:Pe.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Pe.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Pe.union([Pe.literal("now"),rm]),prorationBehavior:Pe.literal("none")}),pc=Pe.strictObject({operationId:Pe.uuid(),action:Pe.enum(["start","extend","end"]),status:Pe.enum(["pending","effective"]),managedBy:Pe.enum(["indiana","stripe"]),membershipIds:Pe.array(Pe.uuid()).min(1).max(20),endsAt:rm.nullable(),execution:SS.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"),e1=Pe.strictObject({groupId:Pe.uuid(),productVersionId:Pe.uuid(),enabled:Pe.boolean()});import{z as Qe}from"zod";var im=Qe.strictObject({requestId:Qe.uuid(),currency:he,makeDefault:Qe.boolean()}),om=Qe.strictObject({setupId:Qe.uuid()}),xS=Qe.strictObject({provider:Qe.literal("stripe"),executor:Qe.literal("merchant"),accountId:Qe.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Qe.literal("setup"),currency:Qe.string().regex(/^[a-z]{3}$/),customer:Qe.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Qe.uuid(),metadata:Qe.strictObject({grooveProjectId:Qe.uuid(),grooveEnvironmentId:Qe.uuid(),grooveCustomerId:Qe.uuid(),groovePaymentSetupId:Qe.uuid()}),setDefaultPaymentMethod:Qe.boolean(),expiresAt:Qe.iso.datetime({offset:!0})}),mc=Qe.strictObject({id:Qe.uuid(),provider:Qe.literal("stripe"),status:Qe.enum(["prepared","complete","expired"]),currency:he,makeDefault:Qe.boolean(),url:Qe.url().nullable(),createdAt:Qe.iso.datetime({offset:!0}),expiresAt:Qe.iso.datetime({offset:!0}),completedAt:Qe.iso.datetime({offset:!0}).nullable(),execution:xS.nullable()});import{z as Et}from"zod";var am=Et.union([Et.string(),Et.number(),Et.boolean(),Et.null()]),sm=Et.strictObject({customerId:Et.uuid()}),cm=Et.strictObject({customerId:Et.uuid(),provider:Et.literal("stripe"),checkedAt:Et.iso.datetime({offset:!0}),status:Et.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Et.number().int().nonnegative(),differences:Et.array(Et.strictObject({subscriptionId:Et.string().startsWith("sub_"),itemId:Et.string().nullable(),field:Et.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:am,actual:am})).max(1e4)});import{z as ye}from"zod";var ma=ye.iso.datetime({offset:!0}),fa=ye.strictObject({createdAt:ma,id:ye.uuid()}),ga=ye.strictObject({customerId:ye.uuid().optional(),entityId:ye.uuid().optional(),productId:ye.string().min(1).max(256).optional(),provider:ye.enum(["stripe","apple","google","merchant","free"]).optional(),status:ye.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:fa.optional(),limit:ye.number().int().min(1).max(100).optional()}),fc={id:ye.uuid(),customerId:ye.uuid(),entityId:ye.uuid().nullable(),productId:ye.string().min(1).max(256),productVersionId:ye.uuid(),name:ye.string().min(1).max(120),provider:ye.enum(["stripe","apple","google","merchant","free"]),createdAt:ma},IS=ye.strictObject({...fc,status:ye.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:ye.boolean(),billingSubscriptionId:ye.uuid().nullable()}),vS=ye.strictObject({...fc,status:ye.enum(["active","ended","refunded"]),orderId:ye.uuid().nullable(),transactionId:ye.uuid().nullable(),currency:he.nullable(),amountMinor:ye.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),wS=ye.strictObject({...fc,status:ye.enum(["blocked","resolved"]),conflict:ye.strictObject({detectedAt:ma,blockingMembershipIds:ye.array(ye.uuid()).min(1).max(100),transactionId:ye.uuid()}),resolvedAt:ma.nullable()}),um=ga.extend({status:ye.enum(["blocked","resolved"]).optional()}),lm=ye.strictObject({customerId:ye.uuid(),orderId:ye.uuid()}),dm=ye.strictObject({orderId:ye.uuid(),status:ye.enum(["blocked","resolved"])}),pm=ye.strictObject({items:ye.array(IS).max(100),nextCursor:fa.nullable()}),mm=ye.strictObject({items:ye.array(vS).max(100),nextCursor:fa.nullable()}),fm=ye.strictObject({items:ye.array(wS).max(100),nextCursor:fa.nullable()});import{z as Ye}from"zod";var gm=Ye.union([Ye.strictObject({intent:Ye.literal("read"),requestId:Ye.uuid(),purchaseIntentId:Ye.uuid()}),Ye.strictObject({requestId:Ye.uuid(),provider:Ye.literal("apple"),purchaseIntentId:Ye.uuid(),productId:Ye.string().min(1).max(255).optional(),signedTransaction:Ye.string().min(1).max(131072)}),Ye.strictObject({requestId:Ye.uuid(),provider:Ye.literal("google"),purchaseIntentId:Ye.uuid(),productId:Ye.string().min(1).max(255).optional(),purchaseToken:Ye.string().min(1).max(16384)})]),hm=Ye.strictObject({requestId:Ye.uuid(),orderId:Ye.uuid(),purchaseIntentId:Ye.uuid(),status:Ye.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:he,refunded:Ye.boolean(),completion:Ye.strictObject({transactionIds:Ye.array(Ye.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:Ye.boolean()}).nullable()});import{z as L}from"zod";var hc=L.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),OS=L.record(L.string(),L.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),_S=3,Yi=20,CS=_S*Yi,gc=L.strictObject({type:L.literal("product"),productId:hc}),Am={type:L.literal("group"),key:L.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:L.string().trim().min(1).max(80)},PS=L.discriminatedUnion("type",[gc,L.strictObject({...Am,items:L.array(gc).max(Yi)})]),ES=L.discriminatedUnion("type",[gc,L.strictObject({...Am,items:L.array(PS).max(Yi)})]),RS=L.array(ES).max(Yi).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>Yi||i>CS)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Ac(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Ac(t))}var si=L.strictObject({lookupKey:L.string().trim().min(1).max(200),displayName:L.string().trim().min(1).max(1500),items:RS,metadata:OS}),kS=L.strictObject({product:L.record(L.string(),L.json()),prices:L.array(L.record(L.string(),L.json())),entitlements:L.array(L.record(L.string(),L.json())),freeTrials:L.array(L.record(L.string(),L.json())),licenses:L.array(L.record(L.string(),L.json()))}),ym=si.extend({id:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),state:L.enum(["active","archived"]),isCurrent:L.boolean(),revision:L.number().int().nonnegative(),publishedVersionId:L.uuid().nullable(),createdAt:L.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"})}),bm=L.strictObject({id:L.uuid(),offeringId:L.uuid(),projectId:L.uuid(),environmentId:L.uuid(),version:L.number().int().positive(),document:si,productEvidence:L.record(hc,kS),createdAt:L.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Ac(e.document);(!n.length||NS(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"})}),jS=L.strictObject({rows:L.array(ym).max(200),versions:L.array(bm).max(500)}),f1=L.discriminatedUnion("action",[L.strictObject({action:L.literal("create"),document:si}),L.strictObject({action:L.literal("save"),id:L.uuid(),revision:L.number().int().nonnegative(),document:si}),L.strictObject({action:L.enum(["publish","set_current","archive","restore"]),id:L.uuid(),revision:L.number().int().nonnegative()})]),g1=L.strictObject({record:ym,version:bm.nullable()}),Sm=L.discriminatedUnion("type",[L.strictObject({type:L.literal("current")}),L.strictObject({type:L.literal("id"),id:L.uuid()}),L.strictObject({type:L.literal("lookup_key"),lookupKey:L.string().min(1).max(200)}),L.strictObject({type:L.literal("version"),versionId:L.uuid()})]),TS=L.strictObject({internalId:hc,id:L.string(),name:L.string().nullable(),version:L.number().int().positive(),archived:L.boolean()}),h1=jS.extend({products:L.array(TS).max(500),pagination:L.strictObject({rows:L.string().nullable(),versions:L.string().nullable(),products:L.string().nullable()}).optional()});function NS(e){let t=[];Ac(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as ha}from"zod";var xm=ha.strictObject({id:ha.uuid(),offeringId:ha.uuid(),version:ha.number().int().positive(),document:si});import{z as bt}from"zod";import{z as de}from"zod";import{z as ci}from"zod";var Aa=ci.strictObject({items:ci.array(ci.strictObject({productVersionId:ci.string().min(1).max(200),label:ci.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:ci.string().min(1).max(200).nullable(),grouping:ta.optional()});function Im(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as At}from"zod";var DS=At.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),ya=At.discriminatedUnion("type",[At.object({type:At.literal("fixed"),productVersionId:At.string().min(1).max(200)}).strict(),At.object({type:At.literal("picker"),pickerId:DS,allowedProductVersionIds:At.array(At.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=At.discriminatedUnion("type",[At.object({type:At.literal("modal"),size:At.enum(["sm","md","lg"])}).strict(),At.object({type:At.literal("sheet"),size:At.enum(["sm","md","lg"])}).strict(),At.object({type:At.literal("fullscreen")}).strict(),At.object({type:At.literal("inline")}).strict()]);var yc=de.discriminatedUnion("type",[de.strictObject({type:de.literal("event"),event:de.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),de.strictObject({type:de.literal("open_url"),url:de.url().refine(e=>new URL(e).protocol==="https:")})]),FS=nn,MS=de.discriminatedUnion("type",[de.object({type:de.literal("checkout"),product:ya}).strict(),de.object({type:de.literal("close")}).strict(),de.object({type:de.literal("action"),action:yc}).strict()]),ui=de.object({schemaVersion:de.literal(3),kind:de.literal("paywall"),name:de.string().trim().min(1).max(80),presentation:Bn,requirement:Yn.optional(),products:Aa,offeringVersionId:de.uuid().nullable(),offeringId:de.uuid(),screen:FS,buttons:de.record(de.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),MS)}).strict(),T1=ui.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 VS(e))t.addIssue({code:"custom",message:r});for(let r of qS(e))t.addIssue({code:"custom",message:r});Xn(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=pp(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&&(!na(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")),Vt(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Vt(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 VS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),Vn(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(S=>S.id===u);l?.type==="navigate"&&r.get(s.id).push(l.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 vm=de.object({id:de.uuid(),projectId:de.uuid(),environmentId:de.uuid(),revision:de.number().int().nonnegative(),state:de.enum(["active","archived"]),publishedVersionId:de.uuid().nullable(),updatedAt:de.iso.datetime({offset:!0}),draft:ui}).strict(),N1=de.object({rows:de.array(vm).max(200),nextCursor:de.uuid().nullable()}).strict(),D1=vm.omit({draft:!0}).extend({name:de.string(),productCount:de.number().int().nonnegative()}).strict(),F1=de.discriminatedUnion("action",[de.object({action:de.literal("save"),id:de.uuid().nullable(),revision:de.number().int().nonnegative(),document:ui}).strict(),de.object({action:de.enum(["publish","archive"]),id:de.uuid(),revision:de.number().int().nonnegative()}).strict()]),M1=de.object({paywalls:de.array(de.object({id:de.uuid(),paywallId:de.uuid(),version:de.number().int().positive(),name:de.string().min(1).max(80),presentation:Bn,buttons:ui.shape.buttons}).strict()).max(500),limited:de.boolean()}).strict();import{z as Oe}from"zod";import{z as Bt}from"zod";var li=Bt.string().regex(/^[a-f0-9]{64}$/),BS=Xo.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),wm=Bt.strictObject({couponDigests:Bt.record(Bt.uuid(),li),variables:Bt.record(gn,Bt.record(Bt.uuid(),Bt.partialRecord(Bt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),Bt.string()))),locales:Bt.record(gn,Yr.extend({nodes:Bt.record(Bt.string(),Bt.strictObject({base:BS})),plans:Bt.object({}).strict(),pickers:Bt.object({}).strict()}).omit({paywall:!0}))});import{z as qe}from"zod";import{z as ba}from"zod";var bc=ba.strictObject({eventsEnabled:ba.boolean(),experimentViewsEnabled:ba.boolean(),featureUsageEnabled:ba.boolean()}),$1=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Om(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var Sc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),US=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(Sc).max(100)}),LS=$.strictObject({id:$.string().min(1).max(255),condition:Ht,gate:$.boolean().optional()}),zS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),_m={condition:Ht.optional(),parentConditions:$.array(LS).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(US).max(100).optional(),ranges:$.array(Sc).max(20).optional(),meta:$.array(zS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},di=$.strictObject({..._m,key:$.string().min(1).max(255),variations:$.tuple([Ae,Ae]).rest(Ae).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),xc=$.strictObject({value:Ae,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),$S=$.strictObject({..._m,id:$.string().max(255).optional(),force:Ae.optional(),variations:$.array(Ae).min(2).max(20).optional(),key:$.string().optional(),range:Sc.optional(),tracks:$.array($.strictObject({experiment:di,result:xc})).max(100).optional()}),GS=$.strictObject({defaultValue:Ae.optional(),rules:$.array($S).max(500).optional()}),Xi=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:Ht})])),ln=$.strictObject({scope:Ue,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),GS),savedGroups:Xi,experiments:$.record($.uuid(),di)});var eo=ln.extend({analyticsConfig:bc,remoteFeatures:qe.array(qe.string().min(1).max(255)).max(500)}),Ic=eo.omit({evaluatedAt:!0,expiresAt:!0}).superRefine((e,t)=>{for(let n of e.remoteFeatures)Object.hasOwn(e.features,n)&&t.addIssue({code:"custom",path:["features",n],message:"Remote Feature definitions cannot be public"});for(let[n,r]of Object.entries(e.savedGroups))r.type==="list"&&t.addIssue({code:"custom",path:["savedGroups",n],message:"Raw Saved Group lists cannot be public"})}),Cm=qe.strictObject({attributes:ht,features:qe.array(qe.string().min(1).max(255)).max(500).optional(),customerId:qe.uuid().optional()}),KS=qe.strictObject({value:Ae,source:qe.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:qe.boolean(),off:qe.boolean(),ruleId:qe.string(),experimentResult:xc.optional()}),Sa=qe.strictObject({generation:ln.shape.generation,evaluatedAt:ln.shape.evaluatedAt,expiresAt:ln.shape.expiresAt,features:qe.record(qe.string(),KS),merchandiseContext:qe.strictObject({merchandiseId:qe.uuid(),merchandise:ht}).optional()}),Pm=qe.strictObject({customerId:qe.uuid().optional(),events:qe.array(qe.strictObject({eventUuid:qe.uuid(),timestamp:qe.iso.datetime({offset:!0}),name:qe.string().min(1).max(255),merchandise:pd.optional(),properties:qe.record(qe.string(),Ae).default({}),deviceId:qe.string().min(1).max(255).optional(),sessionId:qe.string().min(1).max(255).optional()})).min(1).max(100)}),Em=qe.strictObject({inserted:qe.number().int().nonnegative(),duplicates:qe.number().int().nonnegative(),rejected:qe.number().int().nonnegative(),skipped:qe.number().int().nonnegative(),analyticsConfig:bc});import{z}from"zod";function vc(e,t=[]){let n=[];Vt(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(ra(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 Rm(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Rm(t)??[])}}function HS(e){let t=e.pages.map(i=>{let a=Rm(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(ra({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 km(e,t=[]){let n=nn.parse(structuredClone(HS(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=vc(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as Q}from"zod";import{z as F}from"zod";import{z as st}from"zod";var xa=st.strictObject({schemaVersion:st.literal(1),renderKey:st.string().min(1).max(256),routeTemplate:st.string().startsWith("/").max(2048),selectors:st.array(st.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:st.array(st.number().int().min(0)).min(1),absent:st.array(st.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"})}),jm=st.strictObject({renderKey:st.string().min(1).max(256),routeKey:st.string().min(1).max(256),stateKey:st.string().min(1).max(256),documentKey:st.string().min(1).max(256),documentHash:st.string().regex(/^[a-f0-9]{64}$/),compositionKey:st.string().min(1).max(256),entryMode:st.enum(["hard","soft"]),match:st.strictObject({present:st.array(st.number().int().min(0)),absent:st.array(st.number().int().min(0))})});import{z as Er}from"zod";var QS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],wc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",JS=Er.string().regex(new RegExp(`^${wc}/${wc}/${wc}/manifest\\.json$`)),Tm=Er.strictObject({kind:Er.literal("gcs-resumable"),url:Er.url(),bucket:Er.enum(QS),objectKey:JS,byteLength:Er.number().int().positive(),expiresAt:Er.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 lt=F.string().min(1).max(256),on=F.string().regex(/^[a-f0-9]{64}$/),Ia=F.strictObject({versionId:F.uuid(),manifestDigest:on,sourceGraphDigest:on,pageKey:lt,stateKey:lt,documentKey:lt,documentHash:on,elementKey:lt.optional(),nodeId:lt.optional(),contentHash:on.optional(),renderKey:lt.optional()}),Nm=F.strictObject({pageKey:lt,documentKey:lt,expectedDocumentHash:on,renderKey:lt.optional(),nodeId:lt,elementKey:lt,expectedContentHash:on,property:F.enum(["text","fontSize","color"]),value:F.union([F.string().max(4e3),F.number().finite()])}),Dm=F.strictObject({versionId:F.uuid(),manifestDigest:on,sourceGraphDigest:on,pageKey:lt,stateKey:lt,documentKey:lt,documentHash:on,renderKey:lt.optional(),patches:F.array(Nm.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),ZS=/^[a-z][a-z0-9-]{0,39}$/,to=F.string().regex(ZS),_c=F.enum(["web","ios","android"]),dC=F.discriminatedUnion("action",[F.strictObject({action:F.literal("register"),requestId:F.uuid(),client:to,platform:_c,label:F.string().trim().min(1).max(100),sha256:on,bytes:F.number().int().min(1),transferBytes:F.number().int().min(1)}),F.strictObject({action:F.literal("complete"),versionId:F.uuid()}),F.strictObject({action:F.literal("current"),versionId:F.uuid(),expectedCurrent:F.uuid().nullable()}),F.strictObject({action:F.literal("delivery"),enabled:F.boolean()}),F.strictObject({action:F.literal("changes"),versionId:F.uuid(),experimentId:F.uuid(),variationId:lt,changesetId:F.uuid().nullable(),expectedRevision:on.nullable(),editorUrl:F.string().url().max(2048),patches:F.array(Nm).max(200)})]),Cc=F.strictObject({id:F.uuid(),projectId:F.uuid(),environmentId:F.uuid(),clientKey:to,platform:_c,label:F.string(),sha256:on,bytes:F.number().int().positive(),objectKey:F.string(),state:F.enum(["uploading","ready","rejected"]),isCurrent:F.boolean(),revision:F.number().int().nonnegative(),createdAt:F.string(),expiresAt:F.string(),readyAt:F.string().nullable(),summary:F.record(F.string(),F.json()),routeTree:F.json().nullable(),validation:F.record(F.string(),F.json())}),WS=F.strictObject({key:to,platform:_c,currentId:F.uuid().nullable()}),pC=F.strictObject({rows:F.array(Cc).max(100),nextCursor:F.uuid().nullable(),clients:F.array(WS).max(20)}),Oc=F.strictObject({storedBytes:F.number().int().nonnegative(),reservedBytes:F.number().int().nonnegative(),chargedBytes:F.number().int().nonnegative(),versions:F.number().int().nonnegative(),objects:F.number().int().nonnegative(),orphanObjects:F.number().int().nonnegative(),missingReadyObjects:F.number().int().nonnegative(),unknownObjectSizes:F.number().int().nonnegative(),byteLimit:F.number().int().positive(),versionLimit:F.number().int().positive(),remainingBytes:F.number().int().nonnegative()}),mC=F.strictObject({asOf:F.iso.datetime({offset:!0}),reclamation:F.literal("manual-review-required"),buckets:F.strictObject({source:Oc,runtime:Oc,previews:Oc})}),fC=F.strictObject({version:Cc,actorId:F.uuid(),claims:F.record(F.string(),F.json())}),gC=F.strictObject({version:Cc,upload:Tm.nullable()}),hC=F.object({format:F.literal("indiana-route-state-index"),schemaVersion:F.literal(3),routes:F.array(F.object({routeKey:lt,path:F.string(),documentKey:lt,documentHash:on,initialStateKey:lt,initialRenderKey:lt})),renders:F.array(jm)}).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"})}),AC=F.strictObject({rows:F.array(F.object({id:F.uuid(),name:F.string(),status:F.string(),variations:F.array(F.object({id:lt,key:lt,name:F.string().optional()}).loose())}).loose()),limited:F.boolean()}),yC=F.strictObject({enabled:F.boolean(),allowedOrigins:F.array(F.string())});import{z as pi}from"zod";var Fm=pi.strictObject({id:pi.uuid(),name:pi.string().trim().min(1).max(80),client:to,source:Ia,event:pi.enum(["screen_enter","button_click"]),cooldownSeconds:pi.number().int().min(0).max(2592e3),behavior:pi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as ze}from"zod";var Pc=Ae,YS=["parameters","answers","results","variables"];function Ec(e){return YS.some(t=>e===t||e.startsWith(t+"."))}function Rc(e){let t={};for(let[r,i]of Object.entries(ia(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])=>!Ec(r))),variables:t}}import{z as dt}from"zod";var va=dt.discriminatedUnion("kind",[dt.object({kind:dt.literal("ledger"),cursor:Yo}).strict(),dt.object({kind:dt.literal("billing"),cursor:dt.uuid()}).strict()]),XS=dt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),tr=dt.record(dt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),dt.union([dt.string().max(500),dt.boolean(),dt.array(dt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),ex=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function kc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>kc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||ex.test(n)||kc(r,t+1)))}var tx=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,nr=dt.record(XS,Ae).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!kc(e)&&!tx.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var Mm=dt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),wa=dt.array(dt.object({variable:Mm,componentId:Mm,required:dt.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"),RC=dt.object({bindings:wa,answers:tr,values:dt.record(dt.string(),Ae).optional()}).strict();import{z as nx}from"zod";var Oa=nx.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var jc=ze.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),qm=ze.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),Vm=nr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),Tc=ze.record(jc,ze.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),rx=_n,Bm=ze.strictObject({type:ze.literal("external_task"),endpointId:ze.uuid(),taskKey:jc,inputs:ze.record(jc,rx).refine(e=>Object.keys(e).length<=20),outputs:Tc}),Um=ze.strictObject({maxAttempts:ze.number().int().min(1).max(5),retryDelaySeconds:ze.number().int().min(1).max(30),backoff:ze.enum(["fixed","exponential"]),requestTimeoutSeconds:ze.number().int().min(1).max(10),timeoutSeconds:ze.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var BC=ze.strictObject({outcome:ze.enum(["success","failure"]),data:Vm});var UC=ze.discriminatedUnion("operation",[ze.strictObject({operation:ze.literal("signal"),runId:ze.uuid(),nodeId:qm,eventName:Oa,eventId:ze.uuid(),data:Vm}),ze.strictObject({operation:ze.literal("read_results"),runId:ze.uuid()})]),LC=ze.strictObject({scope:Ue,runId:ze.uuid(),eventId:ze.uuid(),accepted:ze.boolean()}),ix=ze.record(qm,Pc),zC=ze.strictObject({scope:Ue,runId:ze.uuid(),results:ix});var xn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},Lm="00000000-0000-0000-0000-000000000000";import{z as J}from"zod";import{z as Je}from"zod";var JC=Je.enum(["local","remote"]),Nc=Je.strictObject({port:Je.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Ae.optional(),sticky:Je.array(Je.strictObject({expected:ki.nullable(),next:ki})).max(100),exposures:Je.array(Ae).max(100),features:Je.array(Ae).max(100)}),zm=Je.strictObject({type:Je.literal("evaluate"),receiptId:Je.uuid(),environmentId:Je.uuid(),policyRevision:Je.number().int().nonnegative(),attributes:ht,sticky:Je.record(Je.string(),ki)}),$m=zm.extend({runId:Je.uuid(),versionId:Je.uuid(),nodeId:Je.string().min(1).max(64),visit:Je.number().int().nonnegative(),revision:Je.number().int().nonnegative()}),Dc=zm.omit({type:!0,receiptId:!0}).extend({type:Je.literal("evaluate_segment")}),Gm=Je.strictObject({nodeId:Je.string().min(1).max(64),result:Nc}),Km=Dc.extend({runId:Je.uuid(),versionId:Je.uuid(),nodeId:Je.string().min(1).max(64),visit:Je.number().int().nonnegative(),revision:Je.number().int().nonnegative(),parameters:nr,answers:tr,variables:Je.record(Je.string(),Ae)});import{z as ae}from"zod";var Fc=ae.array(ae.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"),_a=ae.intersection(ht,ae.looseObject({tags:Fc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),Ca=ae.string().trim().max(80),Pa=ae.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Ea=ae.union([ae.email().max(254),ae.literal("")]),Ra=ae.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),Hm=ae.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),Qm=ae.object({externalUserId:Hm.optional(),name:Ca.default(""),email:Ea.default(""),phone:Pa.optional(),attributes:_a.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),ka=ae.discriminatedUnion("type",[ae.strictObject({type:ae.literal("id"),value:ae.uuid()}),ae.strictObject({type:ae.literal("externalUserId"),value:Hm})]),ja=ae.strictObject({name:Ca.optional(),email:Ea.optional(),phone:Pa.optional(),attributes:_a.optional(),fingerprint:Ra.optional()}),Ta=e=>!e.customerData||e.customer?.type==="externalUserId",Na="customerData requires an externalUserId customer",mi=ae.object({id:ae.uuid(),externalUserId:ae.string().min(1).max(255).nullable(),name:Ca,email:Ea,phone:Pa.optional(),attributes:_a,createdAt:ae.iso.datetime()}).strict(),Jm=ae.object({customer:mi,changed:ae.boolean(),replayed:ae.boolean()}).strict(),ox=ae.discriminatedUnion("type",[ae.object({type:ae.literal("id"),value:ae.uuid()}).strict(),ae.object({type:ae.literal("externalUserId"),value:ae.string().trim().min(1).max(255)}).strict()]),ax=ae.object({name:Ca.optional(),email:Ea.optional(),phone:Pa.optional(),attributes:_a.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ae.array(ae.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ae.strictObject({add:Fc,remove:Fc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Mc=ae.object({lookup:ox}).strict(),Zm=Mc.extend({requestId:ae.uuid(),patch:ax}).strict(),Wm=ae.object({search:ae.string().trim().max(200).default(""),tag:ae.string().trim().max(40).default(""),planId:ae.string().max(200).default(""),versionId:ae.string().max(200).default(""),holdingStatus:ae.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ae.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ae.union([ae.iso.datetime(),ae.literal("")]).default(""),createdUntil:ae.union([ae.iso.datetime(),ae.literal("")]).default(""),offset:ae.coerce.number().int().min(0).max(1e5).default(0),limit:ae.coerce.number().int().min(1).max(100).default(50)}).strict(),Ym=ae.object({customers:mi.array(),hasMore:ae.boolean(),total:ae.number().int().nonnegative().nullable(),evaluatedAt:ae.iso.datetime()}).strict();var no=J.discriminatedUnion("type",[J.strictObject({type:J.literal("literal"),value:Ae}),J.strictObject({type:J.literal("variable"),key:ft,path:Sn.optional()}),J.strictObject({type:J.literal("feature"),featureKey:J.string().min(1).max(128)})]),sx=J.strictObject({requestId:J.uuid(),decisionId:J.uuid(),customerId:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),versionId:J.uuid(),receiptId:J.uuid(),value:Ae}),cx={funnelId:J.uuid(),requestId:J.uuid(),customer:ka,customerData:ja.optional(),attributes:ht.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},sP=J.discriminatedUnion("operation",[J.strictObject({operation:J.literal("decide"),...cx}).refine(Ta,Na),J.strictObject({operation:J.literal("read_decision"),decisionId:J.uuid()}),J.strictObject({operation:J.literal("evaluate_decision"),decisionId:J.uuid(),requestId:J.uuid(),nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative(),revision:J.number().int().nonnegative(),receiptId:J.uuid(),policyRevision:J.number().int().nonnegative(),generation:J.string().min(1).max(256),result:Nc}),J.strictObject({operation:J.literal("feature_config"),funnelId:J.uuid()}),J.strictObject({operation:J.literal("commit_decision_segment"),decisionId:J.uuid(),requestId:J.uuid(),nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative(),revision:J.number().int().nonnegative(),policyRevision:J.number().int().nonnegative(),generation:J.string().min(1).max(256),steps:J.array(Gm).max(32),boundary:J.strictObject({nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative()}).optional()}),J.strictObject({operation:J.literal("segment_configuration"),funnelId:J.uuid(),versionId:J.uuid()}),J.strictObject({operation:J.literal("configuration"),funnelId:J.uuid(),versionId:J.uuid().optional()}),J.strictObject({operation:J.literal("local_configuration"),funnelId:J.uuid()}),J.strictObject({operation:J.literal("report_used"),decisionId:J.uuid(),eventId:J.uuid(),occurredAt:J.iso.datetime({offset:!0}),reference:J.string().min(1).max(128).optional()})]),cP=J.strictObject({scope:Ue,decisionId:J.uuid(),requestId:J.uuid(),status:J.enum(["pending","completed","failed"]),decision:sx.nullable(),evaluation:J.discriminatedUnion("type",[$m,Km]).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"),uP=J.strictObject({scope:Ue,decisionId:J.uuid(),eventId:J.uuid(),source:J.literal("caller_reported")});import{z as Rt}from"zod";var Xm=Rt.strictObject({type:Rt.literal("bundle"),paywall:_n.optional(),offering:_n.optional(),coupons:_n,data:_n}),ux=e=>Rt.strictObject({type:Rt.literal(e),id:Rt.uuid()}),gP=Rt.strictObject({type:Rt.literal("bundle"),paywallVersionId:Rt.uuid().optional(),offeringVersionId:Rt.uuid().optional(),couponIds:Rt.array(Rt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Ae});var hP=Rt.strictObject({type:Rt.literal("bundle"),offering:ux("offering_version").nullable(),paywall:Rt.strictObject({versionId:Rt.uuid(),paywallId:Rt.uuid(),offeringVersionId:Rt.uuid()}).nullable(),coupons:Rt.array(ji).max(20),data:Ae});import{z as In}from"zod";import{z as dn}from"zod";var ef=dn.union([dn.string(),dn.number().finite(),dn.boolean(),dn.null()]),lx=dn.union([ef,dn.array(ef).min(1).max(20)]),dx=dn.record(Sn,lx).refine(e=>Object.keys(e).length<=10),tf=dn.strictObject({path:Sn,type:dn.enum(["string","number","boolean","strings"]),nullable:dn.boolean().optional(),aggregation:dn.enum(["count","exists"]).optional(),where:dx.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 px=["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"],nf=In.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),mx=_n,rf=In.discriminatedUnion("type",[Bm,In.strictObject({type:In.literal("claim_offer"),coupon:_n}),In.strictObject({type:In.literal("event"),event:nf}),In.strictObject({type:In.literal("api"),operation:In.enum(px),inputs:In.record(Sn,mx).refine(e=>Object.keys(e).length<=40),outputs:In.record(nf,tf).refine(e=>Object.keys(e).length<=20)})]);var rt=Oa,fx=Q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),an={id:rt,name:Q.string().trim().min(1).max(80),position:Q.strictObject({x:Q.number().finite(),y:Q.number().finite()}).optional()},gx={success:rt,cancel:rt,unavailable:rt,failure:rt},qc=Q.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Vc=Q.enum(["same_window","new_window"]),hx=Q.discriminatedUnion("type",[Q.strictObject({...an,type:Q.literal("entry"),next:rt,triggers:Q.array(Fm).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),Q.strictObject({...an,type:Q.literal("screen"),screenId:rt,presentation:Bn,outputs:Q.record(rt,rt),offering:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("variable"),key:ft}),Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()})]).optional()}),Q.strictObject({...an,type:Q.literal("offering"),configuration:Q.discriminatedUnion("source",[Q.strictObject({source:Q.literal("fixed"),versionId:Q.uuid()}),Q.strictObject({source:Q.literal("feature"),featureKey:Q.string().min(1).max(128)})]),writes:Q.strictObject({value:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("coupon"),couponId:Q.uuid(),writes:Q.strictObject({value:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("coupons"),couponIds:Q.array(Q.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:Q.strictObject({value:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("output"),value:Q.discriminatedUnion("type",[...no.options,Xm,Q.strictObject({type:Q.literal("selection"),screenId:rt,offeringKey:ft})])}),Q.strictObject({...an,type:Q.literal("condition"),cases:Q.array(Q.strictObject({condition:Ht,target:rt})).min(1).max(50),default:rt}),Q.strictObject({...an,type:Q.literal("feature"),featureKey:Q.string().min(1).max(128),writes:Q.strictObject({value:ft}),next:rt}),Q.strictObject({...an,type:Q.literal("split"),experimentId:Q.uuid(),applyPageExperiment:Q.literal(!0).optional(),routes:Q.record(fx,rt).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:rt}),Q.strictObject({...an,type:Q.literal("action"),...gx,execution:Um,action:rf,writes:tc.optional()}),Q.strictObject({...an,type:Q.literal("external_page"),appManifest:Ia.optional(),url:qc,openIn:Vc,opened:rt,failed:rt}),Q.strictObject({...an,type:Q.literal("end"),outcome:Q.enum(["completed","closed","ineligible","failed"]),output:no.optional()}),Q.strictObject({...an,type:Q.literal("wait"),writes:tc.optional(),wait:Q.discriminatedUnion("type",[Q.strictObject({type:Q.literal("duration"),delaySeconds:Q.number().int().min(1).max(2592e3),elapsed:rt}),Q.strictObject({type:Q.literal("event"),eventName:rt,outputs:Tc,timeoutSeconds:Q.number().int().min(1).max(2592e3),received:rt,timeout:rt})])})]),Bc=Q.strictObject({version:Q.literal(5),entry:rt,nodes:Q.array(hx).min(1).max(xn.flowNodes)}),Uc=Bc.superRefine((e,t)=>{Ax(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function Da(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 Ax(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,m,S)=>{n.push(l),t?.({message:l,reason:m,path:S?["nodes",e.nodes.indexOf(S)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>xn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>xn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let m of Da(l))m===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(m)||i(`Missing target ${m}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let m of Da(r.get(l)))u(m);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var Lc={maxTransitions:1e4,runTimeoutSeconds:2592e3};function of(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of Jn(c.condition))u.startsWith("variables.")&&a(u.slice(10),!0)}if(e.type==="screen"&&e.offering?.source==="variable"&&a(e.offering.key),e.type==="action"&&(e.action.type==="api"||e.action.type==="external_task"))for(let s of Object.values(e.action.inputs))s.source==="variable"&&a(s.key);e.type==="action"&&e.action.type==="claim_offer"&&e.action.coupon.source==="variable"&&a(e.action.coupon.key);let o=e.type==="output"?e.value:e.type==="end"?e.output:null;if(o?.type==="variable"&&a(o.key),o?.type==="bundle")for(let s of[o.paywall,o.offering,o.coupons,o.data])s?.source==="variable"&&a(s.key);return o?.type==="selection"&&a(o.offeringKey),[...i]}import{z as M}from"zod";var fi=M.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Fa=e=>M.record(M.string(),Ae).refine(t=>rn(t)<=e,"Funnel evidence exceeds its byte budget"),HP=M.enum(["local_segment","evaluation","presentation","timer","event","operation"]),$c=M.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),Gc=M.discriminatedUnion("type",[M.strictObject({type:M.literal("flag"),key:M.string().min(1).max(128)}),M.strictObject({type:M.literal("experiment"),id:M.uuid()}),M.strictObject({type:M.literal("saved_group"),id:M.uuid()}),M.strictObject({type:M.literal("config"),key:M.string().min(1).max(128)}),M.strictObject({type:M.literal("constant"),key:M.string().min(1).max(128)}),M.strictObject({type:M.literal("paywall_version"),id:M.uuid()}),M.strictObject({type:M.literal("offering_version"),id:M.uuid()}),M.strictObject({type:M.literal("reward"),id:M.uuid()})]),ro=M.strictObject({schemaVersion:M.literal(1),kind:$c,selector:Gc.nullable(),context:Fa(131072),contract:M.strictObject({version:M.number().int().positive(),evaluator:M.string().min(1).max(128),policyRevision:M.number().int().nonnegative()})}).refine(e=>rn(e)<=131072,"Node input exceeds its byte budget"),af=M.strictObject({schemaVersion:M.literal(1),kind:$c,outcome:M.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Fa(131072),route:M.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Fa(131072)}).refine(e=>rn(e)<=131072,"Node result exceeds its byte budget"),QP=M.strictObject({schemaVersion:M.literal(1),operations:M.record(fi,M.strictObject({attempts:M.number().int().nonnegative(),maxAttempts:M.number().int().min(1).max(5),deadlineAt:M.iso.datetime({offset:!0}),retryAt:M.iso.datetime({offset:!0}).nullable(),error:M.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:M.strictObject({type:fi,id:M.uuid()}).nullable()}))}).refine(e=>rn(e)<=65536,"Execution state exceeds its byte budget"),Rr={receiptId:M.uuid()},zc=M.iso.datetime({offset:!0}),JP=M.discriminatedUnion("type",[M.strictObject({type:M.literal("node_entered"),details:M.strictObject({kind:$c})}),M.strictObject({type:M.literal("presentation_shown"),details:M.strictObject({...Rr,source:M.literal("client"),occurredAt:zc.optional()})}),M.strictObject({type:M.literal("decision_accepted"),details:M.strictObject(Rr)}),M.strictObject({type:M.literal("signal_received"),details:M.strictObject({signalId:M.uuid(),nodeId:fi,eventName:fi,data:Fa(8192),source:M.literal("server"),occurredAt:zc})}),M.strictObject({type:M.literal("signal_consumed"),details:M.strictObject({...Rr,signalId:M.uuid()})}),M.strictObject({type:M.literal("wait_elapsed"),details:M.strictObject(Rr)}),M.strictObject({type:M.literal("wait_timeout"),details:M.strictObject(Rr)}),M.strictObject({type:M.literal("operation_completed"),details:M.strictObject({...Rr,operation:fi,reference:M.strictObject({type:fi,id:M.uuid()}).nullable()})}),M.strictObject({type:M.literal("execution_recovered"),details:M.strictObject({generation:M.number().int().positive(),reason:M.enum(["interrupted","expired_lease","delivery_failed"])})}),M.strictObject({type:M.literal("execution_failed"),details:M.strictObject({generation:M.number().int().positive(),code:M.string().regex(/^[a-z_]{1,64}$/)})}),M.strictObject({type:M.literal("run_completed"),details:M.strictObject({outcome:M.enum(["completed","ineligible","failed"])})}),M.strictObject({type:M.literal("run_closed"),details:M.strictObject({source:M.enum(["client","server","expiry"])})}),M.strictObject({type:M.literal("treatment_used"),details:M.strictObject({...Rr,source:M.enum(["client","server"]),occurredAt:zc,reference:M.string().min(1).max(128).optional()})})]);var pn=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yx=z.discriminatedUnion("type",[z.strictObject({id:pn,type:z.literal("owned"),publicData:wm.optional(),document:nn.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")}),z.strictObject({id:pn,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),Kc={kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(yx).max(xn.pages),references:z.record(pn,Gc).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:pn,screenId:pn,componentId:pn,required:z.boolean()})).max(xn.questions),variables:z.record(ft,ei).refine(e=>Object.keys(e).length<=xn.logicNodes),outputSchema:Xr,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(Lc.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(Lc.maxTransitions)})},fE=z.strictObject({...Kc,graph:Bc});function bx(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 qa(e){return Array.isArray(e)?e.some(qa):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===Lm:qa(n))}function Sx(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=km(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&&!Ji(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}),bx(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"&&qa(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&qa(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function sf(e,t){for(let{message:n,reason:r,path:i}of Sx(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function cf(e,t){let n=(y,p,g=[])=>t.addIssue({code:"custom",message:y,path:g,params:{reason:p}}),r=Object.values(e.references),i=new Map(e.screens.map(y=>[y.id,y])),a=(y,p)=>r.some(g=>g.type===y&&("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(y=>y.type==="screen");(o.length!==i.size||o.some(y=>!i.has(y.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(y=>c.some(p=>y!==p&&p.startsWith(y+".")))&&n("Variable paths must not overlap","variable");function u(y,p){Object.hasOwn(e.variables,y)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(p)]);let g=s.get(y)??new Set;g.add(p.id),s.set(y,g)}for(let[y,p]of e.graph.nodes.entries()){let g=["graph","nodes",y],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 I=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??{}:{};(I.length!==Object.keys(A).length||I.some(w=>!Object.hasOwn(A,w))||new Set(Object.values(A)).size!==Object.values(A).length)&&n("Node writes must map every named output exactly once","variable",g);for(let[w,R]of Object.entries(A)){u(R,p);let N=e.variables[R],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[w]:p.type==="wait"&&p.wait.type==="event"?p.wait.outputs[w]: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 w=e.variables[p.writes.value];(w?.type!=="array"||w.items?.type!=="reward"||w.items.nullable||w.nullable)&&n("Coupons output requires a non-null Reward array","variable",g);for(let R of p.couponIds)a("reward",R)||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 w=p.action.coupon.value;(!w||typeof w!="object"||Array.isArray(w)||w.type!=="reward"||typeof w.id!="string"||Object.keys(w).length!==2||!a("reward",w.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 w=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),w?.type==="paywall"&&p.offering&&n("Paywall owns its fixed Offering Version","offering",g),w?.type==="paywall"&&!a("paywall_version",w.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",g),w?.type==="owned"){let R=w.document.pages[0];if(!R){n("Owned screen requires a page","screen",g);continue}Xn(w.document).some(B=>!B.complete)&&n("Owned screens require complete local content","translations",g);let N=new Set(w.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),Vn(R.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(me=>me!==void 0&&!N.has(me))&&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"&&!un(e.outputSchema,p.output.value)&&n("Terminal output does not match outputSchema","output",g),p.type==="output"&&p.value.type==="literal"&&!un(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 w=e.variables[P.key];w&&!nc(w,e.outputSchema)&&n("Variable output does not match outputSchema","output",g)}if(p.type==="screen"){let w=i.get(p.screenId);if(w?.type==="owned")for(let R of oc(w.document))(/^(input|params)\./.test(R)||R.startsWith("variables.")&&!ic(R.slice(10),c))&&n("Screen values must reference registered variables","variable",g)}if(p.type==="condition")for(let w of p.cases){for(let R of Fn(w.condition))a("saved_group",R)||n("Conditions require explicit Saved Group references","savedGroup",g);for(let R of Jn(w.condition))R.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[w,R]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let N=p.value[w];if(N)if(N.source==="literal"){let B=w==="coupons"?N.value:[N.value];(!Array.isArray(B)||B.length>20||B.some(me=>!un({type:R,nullable:!1},me)||!a(R,me.id))||w==="coupons"&&new Set(B.map(me=>me.id)).size!==B.length)&&n("Bundle requires distinct scoped resource references",w==="coupons"?"coupon":w==="paywall"?"paywall":"offering",[...g,"value",w])}else{let B=e.variables[N.key];(N.path||!B||B.nullable||(w==="coupons"?B.type!=="array"||B.items?.type!=="reward"||B.items.nullable:B.type!==R))&&n("Bundle binding type does not match its slot","output",g)}}}}for(let[y,p]of e.graph.nodes.entries()){let g=p.type==="screen"?i.get(p.screenId):void 0,f=[...of(p,c),...g?.type==="owned"?oa(g.document).map(I=>ic(I,c)?.key??I):[]];for(let I of new Set(f)){let R=function(N){if(N===p.id)return!0;if(w.has(N))return!1;w.add(N);let B=e.graph.nodes.find(xe=>xe.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]:[]:Da(B)).some(R):!1};var S=R;if(!Object.hasOwn(e.variables,I)){n("Consumed variable is undeclared","variable",["graph","nodes",y]);continue}let A=e.variables[I];if(p.type==="screen"&&A.source.type==="input"&&e.inputs.some(N=>N.screenId===p.screenId&&N.variable===I)||A.source.type==="parameter"||A.source.type==="attribute")continue;let P=A.source.type==="input"?new Set(e.inputs.filter(N=>N.variable===I&&N.required).flatMap(N=>o.filter(B=>B.screenId===N.screenId).map(B=>B.id))):s.get(I)??new Set,w=new Set;(!P.size||R(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",y])}}(new Set(e.inputs.map(y=>y.variable)).size!==e.inputs.length||new Set(e.inputs.map(y=>`${y.screenId}:${y.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[y,p]of e.inputs.entries()){e.variables[p.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",y]);let g=i.get(p.screenId),f=g?.type==="owned"?Ji(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",y]),f?.type==="stack"&&f.interaction){let I=f.interaction.type==="toggle"?"boolean":f.interaction.type==="multiselect"?"strings":"string";e.variables[p.variable]?.type!==I&&n("Input variable type does not match component","inputBinding",["inputs",y]);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",y])}}for(let[y,p]of Object.entries(e.variables))p.enum&&p.type!=="string"&&n("Only string variables support enum","variable",["variables",y]),p.source.type==="input"&&!e.inputs.some(g=>g.variable===y)&&n("Input variable requires a component binding","inputBinding",["variables",y]);let l=0,m=0;for(let y of e.screens)if(y.type==="owned"){for(let p of y.document.pages)Vn(p.root,()=>{l++});m+=y.document.actions.length}(l>xn.components||m>xn.actions||rn(e)>xn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var xx=z.strictObject({...Kc,graph:Uc}).superRefine(cf),gi=z.strictObject({...Kc,graph:Uc,displayName:z.string().trim().min(1).max(80)}).superRefine(cf),gE=gi.superRefine(sf),hE=xx.superRefine(sf),Ma=z.string().regex(Ft),io={requestId:z.uuid(),nodeId:pn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Ma.optional()},Ix=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:pn,answers:tr,selection:z.record(pn,z.union([z.string().max(200),z.boolean(),z.number().int().min(0).max(1e4)])).optional()}),z.strictObject({type:z.literal("paywall_quote"),featureQuantities:z.record(z.uuid(),z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:pn,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:ri.optional(),predecessor:z.strictObject({operationId:z.uuid().nullable(),generation:z.number().int().positive()}).optional()}),z.strictObject({type:z.literal("paywall_confirm"),operationId:z.uuid()}),z.strictObject({type:z.literal("paywall_cancel"),operationId:z.uuid()}),z.strictObject({type:z.literal("client_action"),receiptId:z.uuid(),outcome:z.enum(["success","cancel","failure","opened","failed"])})]),vx=z.object({nodeId:pn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(pn,z.object({resourceKey:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.number().int().min(1).max(1e5),after:va.nullable(),filter:z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),Un=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:ka.optional(),customerData:ja.optional(),locale:z.string().min(1).max(35),parameters:nr}).refine(Ta,Na),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:vx.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Ma.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Ma.optional()}),z.strictObject({operation:z.literal("submit"),...io,input:Ix}),z.strictObject({operation:z.literal("back"),...io}),z.strictObject({operation:z.literal("shown"),...io}),z.strictObject({operation:z.literal("close"),...io}),z.strictObject({operation:z.literal("commit_segment"),...io,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Ma.optional()})]);function Va(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 Fn(p))l(g)}function l(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&&Ec(p[g]))throw new Error(`Funnel GB ${g} uses a reserved flow namespace`);u(p.condition);for(let g of p.parentConditions??[])S(g.id),u(g.condition)}function S(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 I of f.rules??[]){m(I);for(let A of I.tracks??[])m(A.experiment)}}))}function y(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"&&S(p.featureKey,!0),p.type==="split"&&y(p.experimentId),p.type==="condition"&&p.cases.forEach(f=>u(f.condition)),p.type==="offering"&&p.configuration.source==="feature"&&S(p.configuration.featureKey,!0);let g=p.type==="output"?p.value:p.type==="end"?p.output:null;g?.type==="feature"&&S(g.featureKey,!0)}for(let p of a)p();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ie}from"zod";function uf(e,t){let n=[],r={};Vt(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Vt(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 lf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Vt(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(l=>l.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}import{z as oo}from"zod";var df=oo.object({defaultLocale:gn,locales:oo.record(gn,oo.object({name:oo.string().max(80),description:oo.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 wx=["customer_data","coupon_code"],Ox=ie.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),pf=ie.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Ba=(e,t)=>new Set(e.map(t)).size===e.length,_x=ie.strictObject({currency:he,amountMinor:ie.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),Cx=ie.strictObject({featureId:ie.uuid(),name:ie.string().trim().min(1).max(120),allowance:ie.string().max(40).nullable(),access:ie.boolean()}),Px=ie.strictObject({stripe:ie.strictObject({prices:ie.array(_x).min(1).max(50)}).optional(),apple:ie.strictObject({productIds:ie.array(Ox).min(1).max(10)}).optional(),google:ie.strictObject({products:ie.array(ie.strictObject({productId:pf,basePlanId:pf.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Ba(e.stripe.prices,n=>n.currency)||e.apple&&!Ba(e.apple.productIds,n=>n)||e.google&&!Ba(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),Ex=ie.strictObject({name:ie.string().trim().min(1).max(80),interval:ie.enum(["free","week","month","year","one_time"]),intervalCount:ie.number().int().min(1).max(100),trial:ie.strictObject({days:ie.number().int().min(1).max(730),cardRequired:ie.boolean()}).nullable(),benefits:ie.array(Cx).max(50).refine(e=>Ba(e,t=>t.featureId),"Duplicate benefit"),channels:Px,prepaid:ie.array(Gi).max(100).optional()}),Rx=ie.strictObject({digest:li,content:ie.strictObject({discount:Zn,duration:en,appliesTo:Ls,displayCopy:df.nullable(),firstPurchaseOnly:ie.boolean(),qualificationRequired:ie.boolean(),startsAt:ie.iso.datetime().nullable(),endsAt:ie.iso.datetime().nullable(),grantWindowHours:ie.number().int().positive(),perCustomerLimit:ie.number().int().positive()})}),kx=ie.discriminatedUnion("type",[ie.strictObject({type:ie.literal("checkout"),product:ya}),ie.strictObject({type:ie.literal("close")}),ie.strictObject({type:ie.literal("action"),action:yc})]),Ua=ie.strictObject({kind:ie.literal("paywall"),formatVersion:ie.literal(1),name:ie.string().trim().min(1).max(80),offeringVersionId:ie.uuid(),presentation:Bn,screen:nn,products:Aa,catalog:ie.record(ie.uuid(),Ex),buttons:ie.record(Te,kx),coupons:ie.record(ie.uuid(),Rx)}).superRefine((e,t)=>{let n=g=>t.addIssue({code:"custom",message:g}),{screen:r}=e;uf(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),vc(r,wx).forEach(n),Xn(r).some(g=>!g.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Vt(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(I=>i.add(I)),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 l=new Set(Object.values(e.catalog).flatMap(g=>g.benefits.map(f=>f.featureId)));for(let g of o)l.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 y=!1;for(let g of Object.values(e.buttons)){if(g.type!=="checkout")continue;y=!0,(g.product.type==="fixed"?[g.product.productVersionId]:g.product.allowedProductVersionIds).some(I=>!u.has(I))&&n("Checkout may only sell displayed Products")}y||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")}),mf=ie.strictObject({state:ie.enum(["published","archived"]),controlRevision:ie.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ie.uuid(),versions:ie.record(ie.uuid(),ie.strictObject({version:ie.number().int().positive(),artifact:ie.string().min(1),sourceDigest:ie.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},Hc=Oe.string().regex(/^[a-f0-9]{64}$/),Qc=Oe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),Zc=Ue.extend({environmentId:Oe.uuid()}),ff=Oe.strictObject({features:Oe.array(Oe.string()).max(500),experiments:Oe.record(Oe.uuid(),Oe.array(Oe.string()).max(20)),savedGroups:Oe.array(Oe.string()).max(1e3)}),Wc=Oe.strictObject({kind:Oe.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:Oe.number().int().positive(),url:Oe.string().min(1).max(2048),sha256:Hc,byteLength:Oe.number().int().positive().max(Zt.maxArtifactBytes),generation:Hc.optional()}),jx=Oe.strictObject({state:Oe.enum(["active","paused","archived"]),controlRevision:Qc,evaluationMode:Oe.enum(["local","remote"]),evaluationRevision:Qc,currentVersionId:Oe.uuid(),versions:Oe.record(Oe.uuid(),Oe.strictObject({artifact:Oe.string(),dependencies:ff,definitionDigest:li.optional(),couponDigests:Oe.record(Oe.uuid(),li).optional()}))}),Yc=Oe.strictObject({kind:Oe.literal("sdk_configuration"),schemaVersion:Oe.literal(1),scope:Zc,revision:Qc,generation:Hc,policy:Oe.strictObject({refreshIntervalSeconds:Oe.number().positive().max(15),maxControlAgeSeconds:Oe.number().positive().max(60)}),gb:Oe.strictObject({features:Oe.string().nullable(),pageExperiments:Oe.string().nullable()}),artifacts:Oe.record(Oe.string(),Wc),funnels:Oe.record(Oe.uuid(),jx),paywalls:Oe.record(Oe.uuid(),mf).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 yt(e){if(Array.isArray(e))return`[${e.map(yt).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)}:${yt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function Xc(e){return $r(Gr(typeof e=="string"?new TextEncoder().encode(e):e))}function gf(e){return Xc(yt(e))}var Jc=class extends Error{constructor(n,r){super(n);De(this,"dependency",r)}};function hf(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,m)=>e.graph.nodes.find(S=>l==="experiment"?S.type==="split"&&S.experimentId===m:l==="feature"&&n(S)===m)?.name,i=(l,m,S=r(m.type,m.resource))=>new Jc(l,{...m,...S?{step:S}:{}});for(let l of Object.values(e.references)){let m=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(m)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...m})}let a=Va(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let m=n(l);if(!m)continue;let S=a.features[m],y=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,p={type:"feature",resource:m};if(!S||!y)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...p},l.name);if([S.defaultValue,...(S.rules??[]).flatMap(f=>[...Object.hasOwn(f,"force")?[f.force]:[],...f.variations??[],...(f.tracks??[]).flatMap(I=>I.experiment.variations)])].some(f=>f===void 0||!un(y,f)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...p},l.name)}let s=new Set,c=(l,m)=>{for(let S of Fn(l)){if(s.has(S))continue;let y=t.savedGroups[S];if(!y)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:S},m);s.add(S),!Array.isArray(y)&&y.type==="condition"&&c(y.condition,m)}},u=(l,m)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},m)};for(let l of e.graph.nodes)if(l.type==="condition")for(let m of l.cases)c(m.condition,l.name);for(let[l,m]of Object.entries(a.features)){let S=r("feature",l);for(let y of m.rules??[]){c(y.condition,S);for(let p of[...y.parentConditions??[],...(y.tracks??[]).flatMap(g=>g.experiment.parentConditions??[])])u(p.id,S),c(p.condition,S);for(let p of y.tracks??[])c(p.experiment.condition,S)}}for(let[l,m]of Object.entries(a.experiments)){let S=r("experiment",l);c(m.condition,S);for(let y of m.parentConditions??[])u(y.id,S),c(y.condition,S)}for(let l of e.graph.nodes)if(l.type==="split"){let m=a.experiments[l.experimentId],S={type:"experiment",resource:l.experimentId};if(!m)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...S},l.name);for(let y of m.variations)if(typeof y!="string"||!Object.hasOwn(l.routes,y))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...S},l.name)}return ff.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,m])=>[l,m.variations.map(String)])),savedGroups:[...s].sort()})}function Af(e){return gi.parse(e)}var yf=bt.strictObject({...ni,selector:bt.discriminatedUnion("type",[bt.strictObject({type:bt.literal("paywall"),paywallId:bt.uuid()}),bt.strictObject({type:bt.literal("version"),versionId:bt.uuid()})]),customerId:bt.uuid().optional(),commerce:Wr,locale:bt.string().min(1).max(35),requirement:Yn.optional()}),ao=bt.strictObject({id:bt.uuid(),paywallId:bt.uuid(),version:bt.number().int().positive(),document:ui.omit({requirement:!0,offeringId:!0}),offering:bt.strictObject({id:bt.uuid()}),content:bt.strictObject({environmentId:bt.uuid(),offeringVersionId:bt.uuid(),artifact:Wc.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:Yr,check:vr.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"})}),kr=bt.strictObject(ao.shape).omit({document:!0,offering:!0}).extend({content:ao.shape.content.unwrap()});function bf(e,t){let n=Ua.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 ao.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as Ut}from"zod";var Sf={requestId:Ut.uuid(),sourceId:Ut.uuid(),expectedAvailable:qt},xf=Ut.discriminatedUnion("action",[Ut.strictObject({...Sf,action:Ut.enum(["add","subtract","set_remaining"]),amount:ge}),Ut.strictObject({...Sf,action:Ut.literal("edit"),granted:ge,expiresAt:Ut.iso.datetime({offset:!0}).nullable(),nextResetAt:Ut.iso.datetime({offset:!0}).nullable(),expectedRevision:Ut.number().int().nonnegative()})]),eu=Ut.strictObject({sourceId:Ut.uuid(),available:qt,held:qt,spent:qt,adjustmentGrantId:Ut.uuid().nullable()}),If=eu.extend({granted:qt,expiresAt:Ut.iso.datetime({offset:!0}).nullable(),nextResetAt:Ut.iso.datetime({offset:!0}).nullable(),revision:Ut.number().int().nonnegative()});import{z as sn}from"zod";var vf=sn.discriminatedUnion("action",[sn.object({action:sn.literal("upsert"),externalId:sn.string().min(1).max(128),name:sn.string().trim().min(1).max(80)}).strict(),sn.object({action:sn.literal("archive"),entityId:sn.uuid()}).strict()]),wf=sn.object({id:sn.uuid(),externalId:sn.string().min(1).max(128),name:sn.string().min(1).max(80),archived:sn.boolean()}).strict();import{z as Tt}from"zod";import{z as Tr}from"zod";var _f=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Of=Tr.string().regex(/.+\/.+/),tu=Tr.number().min(-100),jr=Tr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),Tx=Tr.strictObject({input:jr,output:jr,cache_read:jr.optional(),cache_write:jr.optional(),reasoning:jr.optional(),input_audio:jr.optional(),output_audio:jr.optional()}),nu=(e,t)=>Tr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),fR=Tr.strictObject({defaultMarkup:tu,providerMarkups:nu(Tr.string().min(1),tu),modelMarkups:nu(Of,tu),customModels:nu(Of,Tx.partial())});import{z as fe}from"zod";var Nr=fe.iso.datetime({offset:!0}),rr=fe.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),Nx=fe.discriminatedUnion("kind",[fe.object({kind:fe.literal("absolute"),from:Nr,to:Nr}).strict(),fe.object({kind:fe.literal("last_days"),days:fe.union([fe.literal(1),fe.literal(7),fe.literal(30),fe.literal(90)])}).strict(),fe.object({kind:fe.literal("billing_cycles"),membershipId:fe.uuid(),count:fe.number().int().min(1).max(12),includeCurrent:fe.boolean()}).strict()]),Cf=fe.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"),Dx=fe.object({key:fe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:fe.array(fe.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),Dr=fe.object({range:Nx,timezone:Cf,filterBy:fe.array(Dx).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:fe.enum(["hour","day","week","month"]),internal_feature_id:fe.uuid().nullable(),entityId:fe.uuid().nullable(),topN:fe.number().int().min(1).max(50).nullable(),groupBy:fe.union([fe.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),fe.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:fe.object({bucket:Nr,group:fe.string().max(240),isOther:fe.boolean(),internal_feature_id:fe.uuid(),resourceId:fe.uuid()}).strict().nullable(),limit:fe.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)"})}),Pf=fe.object({from:Nr,to:Nr,interval:fe.enum(["hour","day","week","month"]),timezone:Cf,rows:fe.array(fe.object({bucket:Nr,group:fe.string().max(240),isOther:fe.boolean(),internal_feature_id:fe.uuid(),resourceId:fe.uuid(),consumedUnits:rr,refundedUnits:rr,reservedUnits:rr,charged:rr,refunded:rr,reserved:rr,netUnits:rr,netCharged:rr}).strict()).max(100),nextCursor:fe.object({bucket:Nr,group:fe.string().max(240),isOther:fe.boolean(),internal_feature_id:fe.uuid(),resourceId:fe.uuid()}).strict().nullable()}).strict();var hi=Tt.string().regex(/^(0|[1-9]\d{0,29})$/),Ef=Tt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),ru=Tt.strictObject({bucket:Tt.iso.datetime({offset:!0}),group:Tt.string().max(240),isOther:Tt.boolean(),internal_feature_id:Tt.uuid()}),Rf=Tt.strictObject({...Dr.shape,groupBy:Tt.union([Tt.enum(["customer","entity","entitlement"]),Tt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:ru.nullable()}).superRefine((e,t)=>{let n=Dr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),kf=Tt.strictObject({from:Tt.iso.datetime({offset:!0}),to:Tt.iso.datetime({offset:!0}),interval:Dr.shape.interval,timezone:Dr.shape.timezone,rows:Tt.array(Tt.strictObject({...ru.shape,eventCount:hi,units:Ef,tokenEventCount:hi,tokens:Tt.strictObject(Object.fromEntries(_f.map(e=>[e,hi]))),totalTokens:hi,providerCostEventCount:hi,providerCostUsd:Ef,invalidTelemetryEventCount:hi})).max(100),nextCursor:ru.nullable()});import{z as pt}from"zod";var jf=pt.object({requestId:pt.uuid(),items:pt.array(pt.object({customerId:pt.uuid(),command:Vi.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"),Tf=pt.object({batchId:pt.uuid(),after:pt.number().int().min(-1).max(999),limit:pt.number().int().min(1).max(100)}).strict(),Nf=pt.object({batchId:pt.uuid(),status:pt.enum(["queued","complete"]),total:pt.number().int().min(1).max(1e3),processed:pt.number().int().min(0).max(1e3),items:pt.array(pt.object({position:pt.number().int().min(0).max(999),customerId:pt.uuid(),idempotencyKey:pt.string().min(1).max(120),status:pt.enum(["queued","accepted","rejected","failed"]),receipt:Bi.nullable(),errorCode:pt.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:pt.number().int().min(0).max(999).nullable()}).strict();import{z as E}from"zod";var Fx=E.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Df=E.enum(["draft","active","paused","archived"]),Ff=E.string().min(1).max(256),Mf=E.array(Ff).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),Mx=E.strictObject({duration:E.enum(["day","week","month","year"]),length:E.number().int().min(1).max(3660)}),qx=E.strictObject({internal_feature_id:E.uuid(),allowance:E.number().nonnegative().max(1e15).nullable(),expiry:Mx.nullable()}),Vx=E.discriminatedUnion("type",[E.strictObject({type:E.literal("feature_grant"),grants:E.array(qx).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),E.strictObject({type:E.literal("free_product"),productId:Ff,duration:en}),E.strictObject({type:E.literal("invoice_credits"),amount:E.number().positive().max(1e8),duration:en,rollover:E.boolean(),productIds:Mf})]),Bx=E.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),qf=E.object({key:Bx,name:E.string().trim().min(1).max(80),configuration:Vx}).strict(),Vf=E.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),iu=E.object({code:Vf,maxUses:E.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:E.boolean()}).strict(),Bf=E.object({key:E.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:E.string().trim().min(1).max(80),rewardId:E.uuid(),redeemOn:E.enum(["customer_creation","checkout"]),receivedBy:E.enum(["referrer","all"]),maxRedemptions:E.number().int().min(1).max(1e6).nullable(),productIds:Mf,excludeTrial:E.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),Uf={id:E.uuid(),projectId:E.uuid(),environmentId:E.uuid(),revision:E.number().int().nonnegative(),status:Df,createdAt:E.iso.datetime({offset:!0}),updatedAt:E.iso.datetime({offset:!0})},Ux=qf.extend(Uf).strict(),Lx=Bf.safeExtend(Uf).strict(),PR=E.strictObject({id:E.uuid(),key:E.string(),name:E.string(),type:Fx,status:Df}),ER=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:qf}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),RR=E.discriminatedUnion("action",[E.object({action:E.literal("save"),id:E.uuid().nullable(),revision:E.number().int().nonnegative(),input:Bf}).strict(),E.object({action:E.enum(["activate","pause","resume","archive","delete"]),id:E.uuid(),revision:E.number().int().nonnegative()}).strict()]),Lf=E.object({id:E.uuid(),rewardId:E.uuid(),programId:E.uuid().nullable(),customerId:E.uuid(),referrerId:E.uuid().nullable(),status:E.enum(["pending","applied","unavailable"]),result:E.record(E.string(),E.unknown()).nullable(),createdAt:E.iso.datetime({offset:!0})}).strict(),zf=E.object({code:Vf,requestId:E.uuid()}).strict(),$f=E.strictObject({redemptionId:E.uuid(),currency:he,requestId:E.uuid(),accepted:E.literal(!0)}),zx=E.strictObject({type:E.literal("checkout"),orderId:E.uuid(),productVersionId:E.uuid(),currency:he,duration:en,renewalAmountMinor:E.number().int().positive().max(1e8),status:E.enum(["created","pending","trialing","paid","cancelled","failed"]),url:E.url().nullable()}),Gf=E.discriminatedUnion("type",[zx,E.strictObject({type:E.literal("subscription"),operationId:E.uuid(),membershipId:E.uuid(),productVersionId:E.uuid(),currency:he,duration:en,renewalAmountMinor:E.number().int().positive().max(1e8),status:E.enum(["pending","running","applied","failed"])})]),Kf=E.object({programId:E.uuid(),requestId:E.uuid()}).strict(),Hf=E.object({id:E.uuid(),programId:E.uuid(),code:iu.shape.code,createdAt:E.iso.datetime({offset:!0})}).strict(),kR=E.object({rows:E.array(Ux).max(100),nextCursor:E.uuid().nullable()}).strict(),jR=E.object({rows:E.array(Lx).max(100),nextCursor:E.uuid().nullable()}).strict(),$x=iu.extend({id:E.uuid(),redemptions:E.number().int().nonnegative()}).strict(),Gx=E.strictObject({id:E.uuid(),programId:E.uuid().nullable(),customerId:E.uuid().nullable(),referrerId:E.uuid().nullable(),code:E.string().nullable(),status:E.enum(["pending","triggered","applied"]),createdAt:E.iso.datetime({offset:!0})}),TR=E.object({codes:E.array($x).max(100),redemptions:E.array(Gx).max(100),customers:E.record(E.uuid(),E.string()),codesCursor:E.uuid().nullable(),redemptionsCursor:E.uuid().nullable()}).strict(),NR=E.discriminatedUnion("action",[E.object({action:E.literal("create"),rewardId:E.uuid(),revision:E.number().int().nonnegative(),input:iu}).strict(),E.object({action:E.literal("remove"),rewardId:E.uuid(),revision:E.number().int().nonnegative(),codeId:E.uuid()}).strict()]);import{z as v}from"zod";import{z as Z}from"zod";var Cn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},so=e=>new Set(e).size===e.length,ou=Z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),Kx=Z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),co=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"))),Hx=Z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),Qf=Z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var Jf=Z.strictObject({id:Z.uuid(),repo:Kx,platform:Z.enum(["github","gitlab","bitbucket"]),branches:Z.array(co).min(1).max(4).refine(so),workflow:Z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.array(Z.uuid()).min(1).max(4).refine(so),include:Z.array(Qf).min(1).max(16),exclude:Z.array(Qf).max(16),methods:Z.array(Z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(so),maxAgeHours:Z.number().int().min(1).max(720)}),Zf=Jf.extend({revision:Z.number().int().positive()}),MR=Z.strictObject({repository:Jf,expectedRevision:Z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),Wf=Z.strictObject({repositoryId:Z.uuid(),branch:co}),Qx=Z.array(ou).max(Cn.keys).refine(so),Yf=Z.strictObject({repository:Zf.omit({keyIds:!0}),branch:co,keys:Qx,keySetHash:Z.string().regex(/^[a-f0-9]{64}$/)}),Jx=Z.strictObject({filePath:Hx,startingLineNumber:Z.number().int().min(1).max(1e7)}),au=Z.strictObject({protocol:Z.literal(1),repositoryId:Z.uuid(),branch:co,workflow:Z.string().max(200),configurationRevision:Z.number().int().positive(),keySetHash:Z.string().regex(/^[a-f0-9]{64}$/),commit:Z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.uuid(),runNumber:Z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.number().int().min(1).max(1e4),scannerVersion:Z.literal("1"),scannedAt:Z.iso.datetime({offset:!0}),coverage:Z.strictObject({complete:Z.literal(!0),files:Z.number().int().min(0).max(Cn.files),sourceBytes:Z.number().int().min(0).max(Cn.sourceBytes),unresolvedCalls:Z.number().int().min(0).max(1e6),unsupportedFiles:Z.number().int().min(0).max(Cn.files)}),features:Z.array(Z.strictObject({key:ou,refs:Z.array(Jx).max(Cn.referencesPerKey)})).max(Cn.keys)}).superRefine((e,t)=>{so(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)>Cn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),su=Z.strictObject({scanId:Z.uuid(),commit:Z.string(),receivedAt:Z.string(),references:Z.number().int().nonnegative(),removedReferences:Z.number().int().nonnegative()}),Zx=su.extend({repositoryId:Z.uuid(),branch:co,workflow:Z.string(),digest:Z.string(),configurationRevision:Z.number().int().positive(),runNumber:Z.number().int().positive(),runAttempt:Z.number().int().positive(),scannedAt:Z.string(),keySetHash:Z.string(),coverage:au.shape.coverage}),Wx=Z.strictObject({repositories:Z.array(Zf).max(Cn.repositories),scans:Z.array(Zx).max(Cn.repositories*Cn.branches)}),Yx=Z.strictObject({key:ou,references:Z.number().int().nonnegative(),coveredTargets:Z.number().int().nonnegative(),expiredTargets:Z.number().int().nonnegative(),uncertainTargets:Z.number().int().nonnegative()}),qR=Z.strictObject({available:Z.boolean().default(!0),settings:Wx,expectedTargets:Z.number().int().min(0).max(80),features:Z.array(Yx).max(2001),truncated:Z.boolean()});import{z as St}from"zod";var Xx=St.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"]),e0=St.strictObject({provider:St.literal("stripe"),accountId:St.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:St.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:Xx,occurredAt:St.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:St.record(St.string(),St.unknown()).and(St.object({id:St.string().min(1).max(255),object:St.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:St.boolean()}))}),Xf=St.union([e0,ul]),eg=St.strictObject({id:St.uuid(),eventId:St.string().min(1).max(200),source:St.literal("merchant"),providerVerified:St.literal(!1),outcome:St.string().min(1).max(100)});import{z as Lt}from"zod";var ng={customerId:Lt.uuid(),eventId:Lt.string().trim().min(1).max(200),grantId:Lt.uuid(),occurredAt:Lt.iso.datetime({offset:!0})},rg=Lt.strictObject({...ng,productVersionId:Lt.uuid(),subscriptionId:Lt.string().trim().min(1).max(255)}),ig=Lt.strictObject({...ng,merchandiseId:Lt.uuid()}),og=Lt.union([rg,ig]),tg={id:Lt.uuid(),couponId:Lt.uuid(),status:Lt.literal("redeemed"),source:Lt.literal("merchant"),recordedAt:Lt.iso.datetime({offset:!0})},ag=Lt.union([rg.extend(tg),ig.extend(tg)]);import{z as re}from"zod";var sg=Fp,t0=sg.extend({invoice_id:sg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),cu=re.strictObject({name:re.string().trim().min(1).max(255),memo:re.string().max(1e4).nullable().optional(),footer:re.string().max(1e4).nullable().optional(),net_terms_days:re.number().int().positive().nullable().optional()}),n0=cu.extend({id:re.string().min(1).max(255),created_at:re.number().nullable()}),cg=re.strictObject({items:re.array(n0).max(50),nextCursor:re.uuid().nullable()}),HR=re.discriminatedUnion("action",[re.strictObject({action:re.literal("create"),requestId:re.uuid(),values:cu}),re.strictObject({action:re.literal("update"),id:re.string().min(1).max(255),values:cu}),re.strictObject({action:re.literal("delete"),id:re.string().min(1).max(255)})]),ug=re.discriminatedUnion("action",[re.strictObject({action:re.literal("create"),requestId:re.uuid(),params:ii}),re.strictObject({action:re.enum(["finalize","send","pay","void"]),requestId:re.uuid(),invoiceId:re.uuid()}),re.strictObject({action:re.literal("reissue"),requestId:re.uuid(),invoiceId:re.uuid(),params:t0})]),uu=re.strictObject({id:re.uuid(),customerId:re.uuid(),providerInvoiceId:re.string().nullable(),status:re.enum(["draft","open","paid","void","uncollectible"]),currency:re.string(),totalMinor:re.string().regex(/^-?\d+$/),paidMinor:re.string().regex(/^\d+$/),refundedMinor:re.string().regex(/^\d+$/),hostedInvoiceUrl:re.url().nullable(),createdAt:re.number(),collectionMethod:re.enum(["send_invoice","charge_automatically"]).nullable()}),lg=uu.extend({lines:re.array(re.strictObject({id:re.uuid(),description:re.string(),amountMinor:re.string().regex(/^-?\d+$/),netAmountMinor:re.string().regex(/^-?\d+$/),quantity:re.number().nullable(),periodStart:re.number().nullable(),periodEnd:re.number().nullable()})).max(1e3)}),Ai=re.strictObject({taskId:re.uuid(),status:re.enum(["ready","running","done","dead"]),invoice:uu.nullable(),errorCode:re.string().nullable()}),dg=re.strictObject({items:re.array(uu).max(50),nextCursor:re.uuid().nullable(),operations:re.array(Ai).max(50),operationsLimited:re.boolean()});var r0=v.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"]),pg={scope:Ue,permissions:v.array(r0),expiresAt:v.iso.datetime().nullable()},qk=v.discriminatedUnion("kind",[v.object({...pg,kind:v.literal("server"),keyId:v.string().min(1)}),v.object({...pg,kind:v.literal("customer"),customerId:v.string().min(1),identityKind:v.enum(["identified","guest"]),expiresAt:v.iso.datetime()})]),U=v.object({requestId:v.uuid(),scope:Ue}).strict(),i0=Qm.safeExtend({fingerprint:Ra.optional()}).strict(),o0=U.extend({customer:mi,created:v.boolean()});function mg(){return U.extend({offer:ji.nullable(),reason:fd.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:ip,response:U.extend({message:v.object({messageId:v.uuid(),channel:$i,acceptedAt:v.iso.datetime({offset:!0}),status:v.enum(["accepted","sending","completed","canceled"]),replayed:v.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:v.strictObject({messageId:v.uuid()}),response:U.extend({message:v.object({id:v.uuid(),channel:$i,status:v.enum(["accepted","sending","completed","canceled"]),deliveries:v.array(v.object({id:v.uuid(),status:ap,attempts:v.number().int().nonnegative(),receipts:v.array(v.object({kind:sp,occurredAt:v.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:Hu,response:U.extend({installation:gr})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:Qu,response:U.extend({installation:gr})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:xo,response:U.extend({installation:gr})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:v.strictObject({channel:$i}),response:U.extend({preference:cs})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:op,response:U.extend({preference:cs})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:v.strictObject({cursor:v.uuid().optional()}),response:U.extend({templates:cg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),params:ii}),response:U.extend({preview:cc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),requestId:v.uuid(),params:ii}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:U.extend({operation:Ai})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),command:ug}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:U.extend({operation:Ai})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),taskId:v.uuid()}),response:U.extend({operation:Ai})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),cursor:v.uuid().optional()}),response:U.extend({invoices:dg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),invoiceId:v.uuid()}),response:U.extend({invoice:lg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:Wf,response:U.extend({config:Yf})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:au,response:U.extend({receipt:su})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:v.strictObject({}),response:U.extend({payload:eo})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Cm,response:U.merge(Sa)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Pm,response:U.merge(Em)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),sourceId:v.uuid()}),response:U.extend({balance:If})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:xf}),response:U.extend({balance:eu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:v.strictObject({internal_feature_id:v.uuid(),customerId:v.uuid().optional(),entityId:v.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:U.extend({internal_feature_id:v.uuid(),config:vs,model_markups:jo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),query:Wo}),response:U.extend({usage:Ui})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:Jd}),response:U.extend({usage:Ui})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:zd}),response:U.extend({grant:Ks})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:$d,response:U.extend({grants:Gd})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:v.union(gm.options.map(e=>e.extend({customerId:v.uuid().optional(),customerToken:v.string().regex(Ft).optional()}))),response:U.extend({operation:hm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:im.extend({customerId:v.uuid().optional()}),response:U.extend({setup:mc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:om.extend({customerId:v.uuid().optional()}),response:U.extend({setup:mc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:tm.safeExtend({customerId:v.uuid()}),response:U.extend({batch:Wi})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:da.extend({customerId:v.uuid()}),response:U.extend({batch:Wi})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:da.extend({customerId:v.uuid()}),response:U.extend({batch:Wi})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:da.extend({customerId:v.uuid()}),response:U.extend({batch:Wi})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:v.discriminatedUnion("action",[pa.options[0].extend({customerId:v.uuid()}),pa.options[1].extend({customerId:v.uuid()}),pa.options[2].extend({customerId:v.uuid()})]),response:U.extend({trial:pc})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:nm.extend({customerId:v.uuid()}),response:U.extend({trial:pc})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:ga,response:U.extend({subscriptions:pm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:ga,response:U.extend({purchases:mm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:um,response:U.extend({conflicts:fm})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:lm,response:U.extend({resolution:dm})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:sm,response:U.extend({verification:cm})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:Hp.safeExtend({...ni,customerId:v.uuid().optional()}),response:U.extend({quote:oi})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:Xf,response:U.extend({record:eg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:U.extend({operation:ai})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional()}),response:U.extend({operation:ai})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:Zp.safeExtend({customerId:v.uuid().optional()}),response:U.extend({quote:Yp})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:U.extend({operation:uc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Pr.extend({customerId:v.uuid().optional()}),response:U.extend({operation:uc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:Xp.safeExtend({customerId:v.uuid()}),response:U.extend({quote:lc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Pr.extend({customerId:v.uuid()}),response:U.extend({operation:la})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Pr.extend({customerId:v.uuid()}),response:U.extend({operation:la})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Pd,response:U.extend({controls:$s})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:xd,response:U.extend({prepared:vd})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:wd,response:U.extend({authorization:Ho})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Td,response:U.extend({coupons:Nd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Od,response:U.extend({authorization:Ho})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:kd,response:U.extend({invoices:jd})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:Rd.extend({customerId:v.uuid()}),response:U.extend({operation:Ai})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:Ed,response:U.extend({invoice:Di})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:v.object({customerId:v.uuid(),command:Cd}).strict(),response:U.extend({controls:$s})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:v.object({customerId:v.uuid(),command:vf}).strict(),response:U.extend({entity:wf})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid().nullable(),query:Rf}),response:U.extend({analytics:kf})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:v.object({customerId:v.uuid().nullable(),query:Dr}).strict(),response:U.extend({analytics:Pf})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:jf,response:U.extend({batchId:v.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Tf,response:U.extend({batch:Nf})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:lp.extend({customerId:v.string().min(1).optional()}),response:U.extend({check:vr})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:v.strictObject({kind:er,selector:v.discriminatedUnion("type",[v.strictObject({type:v.literal("resource"),id:v.uuid()}),v.strictObject({type:v.literal("version"),id:v.uuid()})]),customerId:v.string().min(1).optional()}),response:U.extend({content:ac})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:yf,response:U.extend({paywall:kr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:v.strictObject({...ni,selector:Sm,customerId:v.string().min(1).optional(),commerce:Wr,requirement:Yn.optional()}),response:U.extend({offering:xm,candidates:v.array(Ws).max(20),availability:v.array(v.strictObject({productVersionId:v.uuid(),available:v.boolean(),reason:v.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:vr.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),entityId:v.uuid().optional()}).strict(),response:U.extend({holdings:Zd})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),query:Yd}).strict(),response:U.extend({ledger:Xd})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:Kd.extend({customerId:v.uuid().optional()}),response:U.extend({detail:Hd})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:Hs.safeExtend({customerId:v.uuid().optional()}),response:U.extend({statement:Qd})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),command:Vi.options[0]}).strict(),response:U.extend({quote:Bd})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:v.strictObject({customerId:v.uuid(),command:v.union([v.strictObject({eventName:v.string().min(1),quantity:ge.optional(),properties:gt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)}),v.strictObject({internal_feature_id:v.uuid(),quantity:ge.optional(),properties:gt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)})])}),response:U.extend({receipts:v.array(Bi).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:v.object({customerId:v.uuid(),command:Vi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:U.extend({receipt:Bi})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:zf,response:U.extend({redemption:Lf})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:Kf,response:U.extend({referralCode:Hf})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:$f,response:U.extend({checkout:Gf})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:tp,response:U.extend({seats:Zs})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:np,response:U.extend({seats:Zs})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:i0,response:o0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Mc,response:U.extend({customer:mi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:Wm,response:U.extend(Ym.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:Zm,response:U.extend(Jm.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:v.object({customerId:v.uuid()}).strict(),response:U.extend(Gn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:v.strictObject({}),response:U.extend(Gn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:v.strictObject({customerId:v.uuid(),sessionId:v.uuid().optional()}),response:U.extend({revoked:v.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:Ra.optional()}),response:U.extend({customerId:v.uuid(),guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:v.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:U.extend(Gn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:v.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:v.uuid()}),response:U.extend({customer:mi,switched:v.boolean(),replayed:v.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:v.strictObject({code:v.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:v.uuid()}),response:mg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:v.object({}).strict(),response:U.extend({offers:v.array(ji)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:v.object({customerId:v.string().min(1).max(255).optional(),couponId:v.uuid(),...ni,requestId:v.uuid(),couponContentDigest:v.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:mg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:og,response:U.extend({receipt:ag})}},Vk={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};import{z as lu}from"zod";var uo=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function du(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>Qt(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new uo("Required GB Feature is unavailable");i=Dn(e.featureKey,t),o=i.value,Object.assign(r,ti(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new uo("Required GB Experiment is unavailable");if(a=Go(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 uo("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Dn(e.configuration.featureKey,t).value;o={type:"offering_version",id:lu.uuid().parse(u)},Object.assign(r,ti(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,ti(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 fg(e,t,n){lu.uuid().parse(e),lu.number().int().nonnegative().parse(t);let r=$r(Gr(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as K}from"zod";var ir=K.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),a0=K.enum(["running","waiting","completed","closed","ineligible","failed"]),s0=K.discriminatedUnion("type",[Dc,K.strictObject({type:K.literal("wait"),receiptId:K.uuid(),kind:K.enum(["timer","event","operation"]),deadline:K.iso.datetime({offset:!0}).nullable(),eventName:ir.optional()}),K.strictObject({type:K.literal("open_url"),receiptId:K.uuid(),url:qc,openIn:Vc}),K.strictObject({type:K.literal("event"),receiptId:K.uuid(),event:ir})]),La=K.strictObject({type:K.literal("funnel"),id:K.uuid(),versionId:K.uuid()}),c0={id:ir,presentation:Bn,outputs:K.array(ir).max(250),inputs:wa,values:K.record(K.string(),Ae).optional(),offeringKey:ft.optional(),capabilities:Yr,customerData:Ap,dataCursors:K.record(ir,va.nullable())},u0=K.strictObject({...c0,content:K.strictObject({type:K.literal("document"),document:nn})}),pu=K.strictObject({id:K.uuid(),source:La,revision:K.number().int().nonnegative(),visit:K.number().int().nonnegative(),nodeId:ir,nodeType:K.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:a0,stopped:K.boolean(),canBack:K.boolean(),authenticated:K.boolean(),locale:K.string().min(1).max(35),answers:tr,parameters:nr,variables:K.record(K.string(),Ae),output:Ae.nullable(),screen:u0.nullable(),paywall:K.strictObject({receiptId:K.uuid(),resolution:K.union([ao,kr]),quote:oi.nullable(),operation:ai.nullable(),purchaseRequestId:K.uuid().nullable(),selectionGeneration:K.number().int().nonnegative().optional(),canReselect:K.boolean().optional()}).nullable(),instruction:s0.nullable(),pendingRequest:K.strictObject({requestId:K.uuid(),authenticationRequired:K.boolean()}).nullable(),runExpiresAt:K.iso.datetime({offset:!0}),credentialExpiresAt:K.iso.datetime({offset:!0}).nullable()}),lo=K.strictObject({scope:Ue,run:pu,settlement:K.strictObject({requestId:K.uuid(),state:K.enum(["pending","unknown","settled"]),operationId:K.uuid().nullable(),receiptId:K.uuid().nullable().optional()}).optional(),purchase:K.strictObject({receiptId:K.uuid(),quote:oi.nullable(),operation:ai.nullable(),canReselect:K.boolean().optional()}).optional(),review:K.strictObject({activeOperationId:K.uuid().nullable(),pages:K.array(K.strictObject({receiptId:K.uuid(),nodeId:ir,visit:K.number().int().nonnegative()})).max(100),page:K.strictObject({receiptId:K.uuid(),nodeId:ir,visit:K.number().int().nonnegative(),document:nn,answers:tr,inputs:wa,values:K.record(K.string(),Ae).optional()}).nullable(),coupons:K.array(K.strictObject({grantId:K.uuid(),status:K.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:K.string().nullable()})).max(100),purchases:K.array(K.strictObject({receiptId:K.uuid(),operationId:K.uuid(),status:K.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:K.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:K.uuid().optional()}),gg=lo.extend({run:pu.extend({paywall:pu.shape.paywall.unwrap().extend({resolution:kr}).nullable()})});var hg="X-Indiana-Server-Key";import{z as ke}from"zod";var yi=ke.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),yg=ke.strictObject({entry:yi,nodes:ke.array(ke.strictObject({id:yi,type:ke.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:ke.record(ke.string(),yi),writes:ke.record(ft,ft),resources:ke.strictObject({screenId:yi.optional(),paywallVersionId:ke.uuid().optional(),couponId:ke.uuid().optional(),couponIds:ke.array(ke.uuid()).max(20).optional(),experimentId:ke.uuid().optional(),featureKey:ke.string().optional(),offeringVersionId:ke.uuid().optional()})})).min(1).max(500)}),Ag={scope:Ue,funnelId:ke.uuid(),versionId:ke.uuid(),evaluationRevision:ke.number().int().nonnegative(),expiresAt:ke.iso.datetime({offset:!0}).nullable(),topology:yg},za=ke.discriminatedUnion("evaluationMode",[ke.strictObject({...Ag,evaluationMode:ke.literal("local"),growth:ln,conditions:ke.record(yi,ke.array(ke.strictObject({condition:Ht,port:ke.string()})))}),ke.strictObject({...Ag,evaluationMode:ke.literal("remote")})]),l0=za.options[0].extend({evaluation:ke.strictObject({maxTransitions:ke.number().int().min(1).max(1e4),variables:ke.record(ft,ei),outputSchema:Xr,terminals:ke.record(yi,ke.strictObject({outcome:ke.enum(["completed","closed","ineligible","failed"]),output:no.nullable()}))})});function d0(e){return yg.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=ke.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 mu(e){let t=gi.parse(e.document),n=e.evaluationMode==="local"?ln.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:d0(t)};return za.parse(e.evaluationMode==="remote"?r:{...r,growth:Va(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 bg(e){let t=mu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=gi.parse(e.document);return l0.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as Xe}from"zod";var Sg=Xe.string().regex(/^[a-f0-9]{64}$/),p0=di.omit({variations:!0,active:!0}).extend({changeId:Sg,variations:Xe.array(Xe.strictObject({urlRedirect:Xe.string().max(2048)})).min(2).max(20)}),xg=Xe.strictObject({environmentId:Xe.uuid(),trackExposures:Xe.boolean(),generation:Sg,experiments:Xe.array(p0).max(100),savedGroups:Xi}),m0=Xe.strictObject({eventUuid:Xe.uuid(),timestamp:Xe.iso.datetime({offset:!0}).optional(),deviceId:Xe.string().min(1).max(128),sessionId:Xe.string().min(1).max(128).optional(),url:Xe.url().max(2048),pageTitle:Xe.string().max(512).optional(),experimentKey:Xe.string().min(1).max(255),variationKey:Xe.string().min(1).max(64)}),Sj=Xe.strictObject({events:Xe.array(m0).min(1).max(20)}),xj=Xe.strictObject({inserted:Xe.number().int().nonnegative(),duplicates:Xe.number().int().nonnegative(),skipped:Xe.number().int().nonnegative(),rejected:Xe.array(Xe.strictObject({index:Xe.number().int().nonnegative(),reason:Xe.string()}))});import{z as xt}from"zod";var f0=xt.strictObject({selector:xt.string().min(1).max(2048),action:xt.enum(["set","append","remove"]),attribute:xt.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:xt.string().max(5e4).optional(),parentSelector:xt.string().max(2048).optional(),insertBeforeSelector:xt.string().max(2048).optional()}),g0=xt.strictObject({variation:xt.string().min(1).max(128),description:xt.string().max(2e3).default(""),css:xt.string().max(1e5).default(""),js:xt.string().max(1e5).default(""),domMutations:xt.array(f0).max(200).default([]),iam:Dm.optional(),renderGuard:xa.optional()}),fu=g0.omit({variation:!0,description:!0,iam:!0}),h0=di.omit({variations:!0,active:!0}).extend({changeId:xt.string().regex(/^[a-f0-9]{64}$/),variations:xt.tuple([fu,fu]).rest(fu).refine(e=>e.length<=20)}),Ig=xt.strictObject({trackExposures:xt.boolean(),environmentId:xt.uuid(),generation:xt.string().regex(/^[a-f0-9]{64}$/),experiments:xt.array(h0).max(100),savedGroups:Xi});import{z as it}from"zod";var hu=32,A0=522240;function Au(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 y0=it.strictObject({nodeId:it.string().min(1).max(64),visit:it.number().int().nonnegative(),revision:it.number().int().nonnegative()}),gu=it.record(it.string(),Ae),b0=it.strictObject({id:it.uuid(),nodeId:it.string().min(1).max(64),visit:it.number().int().nonnegative(),input:it.strictObject({schemaVersion:ro.shape.schemaVersion,kind:ro.shape.kind,selector:ro.shape.selector,contract:ro.shape.contract}),context:gu,removed:it.array(it.string()).max(100),attributes:gu,removedAttributes:it.array(it.string()).max(100),result:af,offeringVersionId:it.uuid().nullable(),events:it.strictObject({entered:it.string().regex(/^[1-9][0-9]{0,18}$/),decision:it.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),jj=it.strictObject({schemaVersion:it.literal(1),mode:it.enum(["local","remote"]),versionId:it.uuid(),generation:it.number().int().positive(),base:y0,context:gu,steps:it.array(b0).min(1).max(hu)}).refine(e=>rn(e)<=A0,"Segment exceeds its byte budget");var yu=class extends Error{constructor(n,r){super(r);De(this,"code",n);this.name="FunnelLocalCalculationError"}},vg=(e,t)=>new yu(e,t),S0=e=>({experiments:e.experiments,features:e.features});function x0(e,t=vg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Kr(e.growth.savedGroups),i=S0(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Dn(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,l;if(c.type==="condition"){let S=e.conditions[c.id];if(!S)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=du({id:c.id,name:c.id,type:"condition",cases:S.map(y=>({condition:y.condition,target:c.outputs[y.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");l=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 y=du({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=y.value,u=y.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=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,...l===void 0?{}:{value:l}}}}}function I0(e,t){let n=za.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=x0(n,t);return(o,s)=>(i(),v0(a,o,s))}function v0(e,t,n){let r=ht.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 w0(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,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},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 wg(e,t,n,r=vg){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,l=n.visit,m=!1,S,y=g=>(S??(S=I0(e,r)),w0(S,g,{attributes:Rc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let g=0;g<hu;g++){let f=a.get(u);if(!f||!Au(f))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||f.type!=="end"&&f.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let I,A;if(["condition","feature","split"].includes(f.type)||f.type==="offering"&&f.configuration.source==="feature")I=y(f.id),f.type==="offering"&&(I.value={type:"offering_version",id:String(I.value)}),f.type==="condition"?A=I.port==="default"?f.default:f.cases[Number(I.port.slice(5))]?.target:f.type==="split"?A=I.port==="notParticipating"?f.notParticipating:f.routes[I.port]:(f.type==="feature"||f.type==="offering")&&(A=f.next);else if(I={port:"next",sticky:[],exposures:[],features:[]},(f.type==="entry"||f.type==="coupon"||f.type==="coupons")&&(A=f.next),f.type==="offering"&&f.configuration.source==="fixed"&&(I.value={type:"offering_version",id:f.configuration.versionId},A=f.next),f.type==="end"||f.type==="output"){let w=f.type==="end"?f.output:f.value;if(I=w?.type==="feature"?y(f.id):{...I,port:"value",value:w?.type==="literal"?w.value:w?.type==="variable"?rc({source:"variable",key:w.key,...w.path?{path:w.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},w&&(I.value===void 0||!un(t.outputSchema,I.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let P=[...c,{nodeId:u,result:I}];if(rn({steps:P})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:I}),f.type==="feature"||f.type==="offering"||f.type==="coupon"||f.type==="coupons"){let w=f.type==="coupons"?f.couponIds.map(N=>({type:"reward",id:N})):f.type==="coupon"?{type:"reward",id:f.couponId}:I.value;if(w===void 0)throw r("INVALID_RESPONSE","Node output is missing");let R=ti(f,{value:w});vp(t.variables,f,R),Object.assign(o,R)}for(let w of I.sticky)s[`${w.next.attributeName}||${w.next.attributeValue}`]=structuredClone(w.next);if(f.type==="end"||f.type==="output"){m=!0;break}if(!A)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=A,l++}let p=a.get(u);return{steps:c,...!m&&p&&!Au(p)?{boundary:{nodeId:u,visit:l}}:{}}}import{z as be}from"zod";var $a=be.string().regex(/^[a-f0-9]{64}$/),O0=be.strictObject({release:$a,render:xa,button:be.strictObject({selector:be.string().min(1).max(512),elementKey:be.string().min(1).max(256),tag:be.enum(["button","a","input"])}).nullable()}),Zj=be.strictObject({scope:Ue.extend({environmentId:be.uuid()}),release:$a,validatedAt:be.iso.datetime({offset:!0}),validUntil:be.iso.datetime({offset:!0}),entries:be.array(be.strictObject({id:be.uuid(),funnelId:be.uuid(),versionId:be.uuid(),event:be.enum(["screen_enter","button_click"]),target:O0})).max(4e3)}),Wj=be.strictObject({operation:be.literal("entry_start"),funnelId:be.uuid(),versionId:be.uuid(),entryId:be.uuid(),release:$a,requestId:be.uuid(),locale:be.string().min(1).max(35).default("en")}),Yj=be.strictObject({scope:Ue,suppressed:be.literal(!0),reason:be.enum(["frequency","in_progress"]),retryAt:be.iso.datetime({offset:!0}).nullable()}),Xj=be.strictObject({experimentId:be.uuid(),splitNodeId:be.string().min(1).max(128)}),_0=be.strictObject({experimentId:be.uuid(),experimentKey:be.string().min(1).max(128),variationKey:be.string().min(1).max(128),inExperiment:be.boolean(),generation:be.string().min(1).max(256)}),Og=be.strictObject({operation:be.literal("page_experiments"),release:$a,usedReceiptIds:be.array(be.uuid()).max(20).default([]),customerToken:be.string().regex(Ft).optional()}),_g=be.strictObject({scope:Ue,runId:be.uuid(),assignments:be.array(_0.extend({receiptId:be.uuid()})).max(100),payload:Ig});var b=class extends Error{constructor(n,r,i,a,o){super(r);De(this,"code",n);De(this,"status",i);De(this,"requestId",a);De(this,"retryable");De(this,"recovery");De(this,"retryAfterSeconds");De(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=Io(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 po=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},C0=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 b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function Cg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve();if(e&&(!n||Ue.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let c=()=>{if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},u=A=>{if(A!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function l(A){let P=c();if(!P.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let w=P.sha256?await P.sha256(Uint8Array.from(A,R=>R.charCodeAt(0))):await C0(A);if(!/^[a-f0-9]{64}$/.test(w))throw new b("INVALID_STATE","Push credential digest is invalid");return w}function m(A){let P=gr.parse(A);if(P.installationId.toLowerCase()!==c().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return P}async function S(A,P){let w=c(),R={installationId:w.installationId,publicKey:w.publicKey,issuedAt:new Date().toISOString(),...P},N=await w.sign(Yu(A,w.scope,R));return{...R,signature:N}}let y=(A,P,w)=>t.requestWithCredential?t.requestWithCredential(A,P,w):t.request(A,P);async function p(){let A=c(),P=i,w=r?await(t.session?.access()??r):null,R=Ln(A,Ie=>Ie),N;if(R.detachSeq!==null){let Ie=R.detachSeq,Fe=Ju.parse(await S("detach",{sequence:Ie,platform:A.platform}));try{let Ee=await t.request("push/installations/detach",{...A.scope,...Fe},"POST",{installationDetach:!0});if(!Ee||typeof Ee!="object"||!("installation"in Ee))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let zt=m(Ee.installation);if(zt.bound||zt.identitySeq!==Ie)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(Ee){if(Ee instanceof b&&Ee.status===404)N=Ee;else if(!(Ee instanceof b)||Ee.status!==412)throw Ee}N||Ln(A,Ee=>({...Ee,detachSeq:Ee.detachSeq===Ie?null:Ee.detachSeq}))}if(u(P),!w){if(N)throw N;return null}let B=O.bindPushInstallation,me=B.request.parse(await S("bind",{sequence:o,platform:A.platform,credentialDigest:await l(w)}));u(P);let xe=B.response.parse(await y(B.path,me,w));u(P);let Ce=m(xe.installation);if(!Ce.bound||Ce.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return N&&R.detachSeq!==null&&o>R.detachSeq&&Ln(A,Ie=>({...Ie,detachSeq:Ie.detachSeq===R.detachSeq?null:Ie.detachSeq})),Ce}async function g(){c();let A=i,P=r?await(t.session?.access()??r):null;if(!P)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let w=O.readPushInstallation,R=w.request.parse(await S("read",{credentialDigest:await l(P)}));u(A);let N=w.response.parse(await y(w.path,R,P));return u(A),m(N.installation)}function f(A=p){let P=s.catch(()=>{}).then(A);return s=P,P.catch(w=>{try{e?.onError?.(w instanceof Error?w:new Error("Push synchronization failed"))}catch{}}),P}async function I(A,P,w){let R=c(),N=P.identity,B=P.observation,me=r?await(t.session?.access()??r):null;if(u(N),B!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!me)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!A.connectionId||!A.kind||!A.token||!["granted","provisional"].includes(A.permission))throw new b("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 b("INVALID_STATE","Push observation changed during recovery");let xe=Ln(R,zt=>w?zt:{...zt,addressSeq:po(zt.addressSeq)}),Ie=await S(w?"recovery_confirm":"recovery_request",{...A,sequence:xe.addressSeq,credentialDigest:await l(me),...w?{challenge:w}:{}}),Fe=w?Wu.parse(Ie):Zu.parse(Ie);if(u(N),B!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Ee=await y(`push/installations/recovery/${w?"confirm":"request"}`,Fe,me);if(u(N),B!==a||Ln(R,zt=>zt).addressSeq!==xe.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(w){let zt=O.updatePushAddress.response.parse(Ee),We=m(zt.installation);if(!We.bound||We.identitySeq!==o||We.addressSeq!==xe.addressSeq||We.connectionId!==A.connectionId||We.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return We}if(!Ee||typeof Ee!="object"||!("recovery"in Ee))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return ss.parse(Ee.recovery)})}return{recoveryObserver(){c();let A={identity:i,observation:++a};return{async request(P){return ss.parse(await I(P,A))},async confirm(P,w){return gr.parse(await I(w,A,P))}}},identify(A){if(!e)return;o=Ln(e,w=>({...w,identitySeq:po(w.identitySeq)})).identitySeq,r=A,i++,a++},reset(){if(e)try{Ln(e,A=>{let P=po(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,w=o;return a++,await f(async()=>{u(P);let R=await g();return u(P),o=Ln(A,B=>{if(B.identitySeq!==w)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...B,identitySeq:po(Math.max(B.identitySeq,R.identitySeq)),addressSeq:Math.max(B.addressSeq,R.addressSeq)}}).identitySeq,await p()})},tokenObserver(){c();let A=++a,P=i;return async w=>{if(A!==a||P!==i)return null;let R=c(),N=r?await(t.session?.access()??r):null;if(!N)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await f(),u(P),A!==a)return null;let B=Ln(R,Ie=>({...Ie,addressSeq:po(Ie.addressSeq)})),me=O.updatePushAddress,xe=me.request.parse(await S("address",{...w,sequence:B.addressSeq,credentialDigest:await l(N)}));if(u(P),A!==a)return null;let Ce=me.response.parse(await y(me.path,xe,N));return u(P),m(Ce.installation)}}}}function Pg(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 Eg={name:"@tinkerlandai/longplay-sdk",version:"0.10.8",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 E0=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function R0(e){return e.replace(E0,"$1\uFFFD")}function Iu(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 qg(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 Rg(e){let t;if(Array.isArray(e)){let n=e.map(Ge);if(n.length===2)return n}else if((t=qg(e))!=null){let n=Iu(t.next()),r=Iu(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 kg="0123456789ABCDEF",k0=/(?:%[0-9A-Fa-f]{2})+/g;function Pn(e){return`%${kg[e>>4&15]}${kg[15&e]}`}function Vg(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Pn(e):String.fromCharCode(e):e<=2047?Pn(192|e>>6)+Pn(128|63&e):e<=65535?Pn(224|e>>12)+Pn(128|e>>6&63)+Pn(128|63&e):Pn(240|e>>18)+Pn(128|e>>12&63)+Pn(128|e>>6&63)+Pn(128|63&e)}function vu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function wu(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(k0,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function go(e){return e<=31||e>126}function j0(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return go(e)}}function ku(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return go(e)}}function T0(e){return ku(e)||e===39}function Ou(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return ku(e)}}function Ja(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 Ou(e)}}function jg(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 Ja(n)}})(e)}}function Bg(e,t){return Vg(e=e||0,t)}function En(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+=Vg(o,t,n)}return i}function ju(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([wu(i.slice(0,a),!0),wu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function _u(e){let t="";for(let n=0;n<e.length;n++){let r=En(e[n][0],jg,!0),i=En(e[n][1],jg,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var N0=[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],D0=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],F0=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],M0=[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[V0,B0,U0,Tg]=[[[],"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 L0(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 Ug(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function mo(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 z0(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&&Ug(M0,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&mo(Tg,t[i]);)i--;let a=n+1;for(;a<t.length&&mo(Tg,t[a]);)a++;if(!(i>=0&&a<t.length&&mo(B0,t[i])&&mo(U0,t[a])))return!1}return!0}var $0=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,G0=/\p{Script=Latin}/u;function K0(e){return!$0.test(e)||!G0.test(e)}var or=36,Ka=1,Cu=26,H0=38,Q0=700,J0=72,Z0=128,W0=2147483647;function Ng(e){return String.fromCharCode(e+22+75*+(e<26))}function Y0(e,t,n){let r=0;for(e=n?Math.floor(e/Q0):e>>1,e+=Math.floor(e/t);e>(or-Ka)*Cu>>1;r+=or)e=Math.floor(e/(or-Ka));return Math.floor(r+(or-Ka+1)*e/(e+H0))}function X0(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=Z0,o=0,s=J0;for(;r<t.length;){let c=W0;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let m=o;for(let S=or;;S+=or){let y=S<=s?Ka:S>=s+Cu?Cu:S-s;if(m<y)break;n+=Ng(y+(m-y)%(or-y)),m=Math.floor((m-y)/(or-y))}n+=Ng(m),s=Y0(o,r+1,r===i),o=0,r++}}o++,a++}return n}function bu(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=vu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function Dg(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function Lg(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function zg(e){return e.length===2&&Lg(e.codePointAt(0),e.codePointAt(1))}function Fg(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function ct(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function $g(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Pu(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,l=0,m=0;for(;m<4&&(u=vu(c[s]))>=0;)l=(l<<4)+u,s++,m++;if(c[s]===46){if(m===0||o>6)return null;s-=m;let S=0;for(;c[s]!==void 0;){let y=0;if(S>0)if(c[s]===46&&S<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(y=10*y+vu(c[s]),y>255)return null;s++}i[o]=256*i[o]+y,S++,S%2==0&&o++}if(S!==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]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,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 Fg(r)?null:En(r,go)})(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 l of u){let m=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!Ug(N0,m)||mo(V0,m))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let m of u){let S=m.codePointAt(0);if(S!==8204&&S!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(m))continue;let y=L0(m,S);if(y){l+=y;continue}let p=D0.indexOf(S);l+=p<0?m:F0[p]}return l})(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 l=/[^\0-\x7f]/.test(u);if(q0(u)||l&&(/^\p{Mark}/u.test(u)||!z0(u)||!K0(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${X0(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:wu(e));return n===null||Fg(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(bu(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 l=bu(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=bu(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Eu(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,l=1,m=0;for(let S=0;S<s.length;++S)s[S]!==0?(m>l&&(c=u,l=m),u=-1,m=0):(u===-1&&(u=S),++m);return m>l?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 Gg(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 Kg(e){return e.username!==""||e.password!==""}function Su(e){return e.host===null||e.host===""||e.scheme==="file"}var C=0,q="",Se="",Ve=null,V,Ha=!1,Qa=!1,Fr=!1,ut;function cn(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,Se="",Ve=n||null,V=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},Ha=!1,Qa=!1,Fr=!1,ut=r||0;let i=eI;switch(r){case 3:case 4:i=Za;break;case 5:i=Nu;break;case 6:i=Mr;break;case 7:i=ar;break;case 8:i=Rn}return i(G(e,C))!==1?V:null}function W(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 Hg(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var eI=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 Se=q.slice(C,n).toLowerCase(),C=n,tI(n<q.length?e:void 0)}else return ut?1:(--C,W(t,e)?Qg(G(q,C)):0)},tI=e=>{let t=C;if(e===58){if(ut){if(ct(V.scheme)!==ct(Se))return 0;if((Kg(V)||V.port!==null)&&Se==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=Se,ut?(V.port===$g(V.scheme)&&(V.port=null),0):(Se="",V.scheme==="file"?W(t,e)?Du(G(q,C)):0:ct(V.scheme)&&Ve!==null&&Ve.scheme===V.scheme?W(t,e)?nI(G(q,C)):0:ct(V.scheme)?W(t,e)?iI(G(q,C)):0:G(q,C+1)===47?(C++,W(t,e)?rI(G(q,C)):0):(V.path=[""],V.opaquePath=!0,W(t,e)?Zg(G(q,C)):0))}else return ut?1:(Se="",C=-1,W(t,e)?Qg(G(q,C)):0)},Qg=e=>{let t=C;return Ve===null||Ve.opaquePath&&e!==35?1:Ve.opaquePath&&e===35?(V.scheme=Ve.scheme,V.path=Ve.path.slice(),V.opaquePath=Ve.opaquePath,V.query=Ve.query,V.fragment="",W(t,e)?Rn(G(q,C)):0):Ve.scheme==="file"?(C--,W(t,e)?Du(G(q,C)):0):(C--,W(t,e)?Tu(G(q,C)):0)},nI=e=>{let t=C;return e===47&&G(q,C+1)===47?(++C,W(t,e)?Ya(G(q,C)):0):(C--,W(t,e)?Tu(G(q,C)):0)},rI=e=>{let t=C;return e===47?W(t,e)?bi(G(q,C)):0:(C--,W(t,e)?wn(G(q,C)):0)},Tu=e=>{let t=C;return V.scheme=Ve.scheme,e===47||ct(V.scheme)&&e===92?W(t,e)?Mg(G(q,C)):0:(V.username=Ve.username,V.password=Ve.password,V.host=Ve.host,V.port=Ve.port,V.path=Ve.path.slice(),V.query=Ve.query,e===63?(V.query="",W(t,e)?ar(G(q,C)):0):e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):e!=null?(V.query=null,V.path.pop(),C--,W(t,e)?wn(G(q,C)):0):W(t,e)?Tu(G(q,C)):0)},Mg=e=>{let t=C;return ct(V.scheme)&&(e===47||e===92)?W(t,e)?Ya(G(q,C)):0:e===47?W(t,e)?bi(G(q,C)):0:(V.username=Ve.username,V.password=Ve.password,V.host=Ve.host,V.port=Ve.port,C--,W(t,e)?wn(G(q,C)):0)},iI=e=>{let t=C;return e===47&&G(q,C+1)===47?C++:C--,W(t,e)?Ya(G(q,C)):0},Ya=e=>{let t=C;return e!==47&&e!==92?(C--,W(t,e)?bi(G(q,C)):0):W(t,e)?Ya(G(q,C)):0},bi=e=>{let t=C;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!ct(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&&ct(V.scheme))break;n+=vn(r)}return Se+=q.slice(C,n),C=n-1,W(t,e)?bi(G(q,C)):0}if(e===64){Ha&&(Se=`%40${Se}`),Ha=!0;for(let n=0;n<Se.length;n++){let r=Se.codePointAt(n);if(r===58&&!Qa){Qa=!0;continue}let i=Bg(r,Ja);Qa?V.password+=i:V.username+=i,r!=null&&r>65535&&n++}return Se="",W(t,e)?bi(G(q,C)):0}else return e==null||e===35||e===47||e===63||e===92&&ct(V.scheme)?Ha&&Se===""?1:(C-=Se.length+1,Se="",W(t,e)?Za(G(q,C)):0):(Se+=Hg(e),W(t,e)?bi(G(q,C)):0)},Za=e=>{let t=C;if(ut&&V.scheme==="file")return C--,W(t,e)?Fu(G(q,C)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!ct(V.scheme))){let n=C+vn(e);for(e===91?Fr=!0:e===93&&(Fr=!1);n<q.length;){let r=G(q,n);if(r==null||!Fr&&r===58||r===35||r===47||r===63||r===92&&ct(V.scheme))break;r===91?Fr=!0:r===93&&(Fr=!1),n+=vn(r)}return Se+=q.slice(C,n),C=n-1,W(t,e)?Za(G(q,C)):0}else if(e===58&&!Fr){if(Se===""||ut===4)return 1;let n=Pu(Se,!ct(V.scheme));return n===null?1:(V.host=Eu(n),Se="",W(t,e)?Nu(G(q,C)):0)}else if(e==null||e===35||e===47||e===63||e===92&&ct(V.scheme)){if(C--,ct(V.scheme)&&Se==="")return 1;if(ut&&Se===""&&(Kg(V)||V.port!==null))return 1;let n=Pu(Se,!ct(V.scheme));return n===null?1:(V.host=Eu(n),Se="",ut?0:W(t,e)?Mr(G(q,C)):0)}else return Se+=Hg(e),W(t,e)?Za(G(q,C)):0},Nu=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 Se+=q.slice(C,n),C=n-1,W(t,e)?Nu(G(q,C)):0}else if(ut||e==null||e===35||e===47||e===63||e===92&&ct(V.scheme)){if(Se!==""){let n=parseInt(Se,10);if(n>65535)return 1;if(V.port=n===$g(V.scheme)?null:n,Se="",ut)return 0}return ut?1:(C--,W(t,e)?Mr(G(q,C)):0)}else return 1};function Jg(e,t){let n=e.length-t;if(n<2)return!1;if(Lg(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 Du=e=>{let t=C;return V.scheme="file",V.host="",e===47||e===92?W(t,e)?oI(G(q,C)):0:Ve?.scheme==="file"?(V.host=Ve.host,V.path=Ve.path.slice(),V.opaquePath=Ve.opaquePath,V.query=Ve.query,e===63?(V.query="",W(t,e)?ar(G(q,C)):0):e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):e!=null?(V.query=null,Jg(q,C)?V.path=[]:Gg(V),C--,W(t,e)?wn(G(q,C)):0):W(t,e)?Du(G(q,C)):0):(C--,W(t,e)?wn(G(q,C)):0)},oI=e=>{let t=C;return e===47||e===92?W(t,e)?Fu(G(q,C)):0:(Ve!==null&&Ve.scheme==="file"&&(!Jg(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})(Ve.path[0])&&V.path.push(Ve.path[0]),V.host=Ve.host),C--,W(t,e)?wn(G(q,C)):0)},Fu=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 Se+=q.slice(C,n),C=n-1,W(t,e)?Fu(G(q,C)):0}else if(e==null||e===47||e===92||e===63||e===35){if(C--,!ut&&zg(Se))return W(t,e)?wn(G(q,C)):0;if(Se==="")return V.host="",ut?0:W(t,e)?Mr(G(q,C)):0;{let n=Pu(Se,!ct(V.scheme));return n===null?1:(n==="localhost"&&(n=""),V.host=Eu(n),Se="",ut?0:W(t,e)?Mr(G(q,C)):0)}}return 1},Mr=e=>{let t=C;return ct(V.scheme)?(e!==92&&e!==47&&C--,W(t,e)?wn(G(q,C)):0):!ut&&e===63?(V.query="",W(t,e)?ar(G(q,C)):0):!ut&&e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):e!=null?(e!==47&&C--,W(t,e)?wn(G(q,C)):0):(ut&&V.host===null&&V.path.push(""),W(t,e)?Mr(G(q,C)):0)},wn=e=>{let t=C;if(e!=null&&e!==47&&(!ct(V.scheme)||e!==92)&&(ut||e!==63&&e!==35)){let n=C+vn(e);for(;n<q.length;){let r=G(q,n);if(r==null||r===47||ct(V.scheme)&&r===92||!ut&&(r===63||r===35))break;n+=vn(r)}Se+=En(q.slice(C,n),Ou),C=n,e=G(q,n)}if(e==null||e===47||ct(V.scheme)&&e===92||!ut&&(e===63||e===35)){let n=ct(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}})(Se)?(Gg(V),e!==47&&!n&&V.path.push("")):Dg(Se)&&e!==47&&!n?V.path.push(""):Dg(Se)||(V.scheme==="file"&&V.path.length===0&&zg(Se)&&(Se=`${Se[0]}:`),V.path.push(Se)),Se="",e===63?(V.query="",W(t,e)?ar(G(q,C)):0):e===35?(V.fragment="",W(t,e)?Rn(G(q,C)):0):W(t,e)?wn(G(q,C)):0}else return Se+=Bg(e,Ou),W(t,e)?wn(G(q,C)):0},Zg=e=>{let t=C;if(e===63)return V.query="",W(t,e)?ar(G(q,C)):0;if(e===35)return V.fragment="",W(t,e)?Rn(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]+=En(r.slice(0,-1),go)+"%20":V.path[0]+=En(r,go),C=n,(e=G(q,n))===63)return V.query="",W(t,e)?ar(G(q,C)):0;if(e===35)return V.fragment="",W(t,e)?Rn(G(q,C)):0}return W(t,e)?Zg(G(q,C)):0},ar=e=>{let t=C,n=C;if(e!=null){if(ut)n=q.length;else{let i=q.indexOf("#",C);n=i===-1?q.length:i}let r=ct(V.scheme)?T0:ku;V.query+=En(q.slice(C,n),r)}return C=n,G(q,n)===35&&!ut?(V.fragment="",W(t,e)?Rn(G(q,C)):0):W(t,e)?ar(G(q,C)):0},Rn=e=>{let t=C;return e!=null&&(V.fragment+=En(q.slice(C),j0),C=q.length),W(t,e)?Rn(G(q,C)):0};function Ru(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function Wg(e){switch(e.scheme){case"blob":{let t=cn(Ru(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":Wg(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"),mn=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=cn(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=cn(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=cn(n,null,null,0),r==null)?!1:cn(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+=Ru(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[$e].url)}set href(t){let n=cn(t=Ge(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[$e].url=n,this[$e].query&&xu(this[$e].query,n.query)}get origin(){return Wg(this[$e].url)}get protocol(){return`${this[$e].url.scheme}:`}set protocol(t){cn(`${t=Ge(t)}:`,this[$e].url,null,2)}get username(){return this[$e].url.username}set username(t){t=Ge(t),Su(this[$e].url)||(function(r,i){r.username=En(i,Ja)})(this[$e].url,t)}get password(){return this[$e].url.password}set password(t){t=Ge(t),Su(this[$e].url)||(function(r,i){r.password=En(i,Ja)})(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||cn(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||cn(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];Su(n)||(t?cn(t,n,null,5):n.port=null)}get pathname(){return Ru(this[$e].url)}set pathname(t){t=Ge(t);let{url:n}=this[$e];n.opaquePath||(n.path=[],cn(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&&xu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",cn(i,n,null,7),r&&xu(r,n.query)}}get searchParams(){let t=this[$e],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new Wa;return o[tt].url=i,o[tt].serialized=a==null,a&&(o[tt].list=ju(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="",cn(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(mn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var tt=Symbol("URLSearchParamsImpl"),aI=Symbol.dispose||Symbol.for("dispose");function xu(e,t){t?e[tt].list=ju(t):e[tt].list.length=0,e[tt].serialized=t==null}function Ga(e){if(e.url){let t=_u(e.list);(function(r,i){r[$e].url.query=i})(e.url,t||null),e.serialized=!0}}var sI=typeof Iterator<"u"?Iterator:Object,fo=class extends sI{constructor(t,n){super(),this[tt]={ptr:t,map:n,index:0}}next(){let t=this[tt];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}[aI](){}},Wa=class{constructor(t){let n=this[tt]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Rg(t[i]));else if((r=qg(t))!=null){let i;for(;!(i=Iu(r.next())).done;)n.list.push(Rg(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=R0(o),c=Ge(t[o]),u=n.list.find(l=>l[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=ju(i)}}get size(){return this[tt].list.length}append(t,n){t=Ge(t),n=Ge(n),this[tt].list.push([t,n]);let r=this[tt];r.url&&r.serialized?(function(a,o){let s=a[$e].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,_u([[t,n]])):Ga(r)}delete(t,n){t=Ge(t),n=n!=null?Ge(n):void 0;let{list:r}=this[tt],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;Ga(this[tt])}get(t){t=Ge(t);let{list:n}=this[tt];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[tt];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[tt];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[tt],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&&Ga(this[tt])}sort(){this[tt].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),Ga(this[tt])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[tt];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new fo(this[tt],t=>t)}keys(){return new fo(this[tt],t=>t[0])}values(){return new fo(this[tt],t=>t[1])}toString(){return _u(this[tt].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(Wa.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var sr="https://api.longplayai.com";function Yg(e){let t,n,r=0,i,a=new Map,o=()=>{for(let m of[...a.keys()])try{m()}catch{}};function s(m,S){let y=++r;i=void 0,t=void 0,n=void 0;for(let p of[...a.values()])try{p?.()}catch{}y===r&&(t=m,n=S,o())}let c=()=>s();function u(m,S=!1){let y=Gn.safeParse(m);if(!y.success||S&&Date.parse(y.data.expiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<=Date.now()||Date.parse(y.data.refreshExpiresAt)<Date.parse(y.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return y.data}async function l(){if(i)return i;let m=t,S=r;if(!m||Date.parse(m.refreshExpiresAt)<=Date.now())throw m&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let y=(async()=>{try{let p=await e(m.refreshToken);if(S!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let g=u(p,!0);if(g.customerId!==m.customerId||g.sessionId!==m.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=g,n=g.accessToken,{...g}}catch(p){throw S!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(p instanceof b&&p.status===401&&c(),p)}})();i=y;try{return await y}finally{i===y&&(i=void 0)}}return{identify(m){let S=typeof m=="string"?void 0:u(m),y=typeof m=="string"?m:S.accessToken;if(!y.trim()||/\s/.test(y)||y.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(S,y)},reset:c,subscribeIdentity(m,S){return a.set(m,S),()=>{a.delete(m)}},access(){if(t&&Date.parse(t.expiresAt)<=Date.now()+3e4)return l().then(()=>{if(!n)throw new b("NOT_IDENTIFIED","Customer authentication is required");return n});if(!n)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return n},peek:()=>n,snapshot:()=>t&&{...t},refresh:l}}var Xg=Symbol("IndianaNoContent");function cr(e,t,n=mn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?Ue.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??sr);if(o.username||o.password||o.search||o.hash)throw new b("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 b("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 b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=null,l=0,m=null,S=new Set,y=e.session??Yg(async A=>{let P=await I("customer-sessions/refresh",{},"POST",{},A);if(!P||typeof P!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:w,scope:R,...N}=P;return N});function p(){l+=1,u=null,m=null;for(let A of S)A.abort();S.clear()}let g=y.subscribeIdentity(p);function f(){y.reset()}async function I(A,P={},w="POST",R={},N){let B=R.installationDetach===!0;if(B&&(A!=="push/installations/detach"||w!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!N&&!u&&!B)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let me=l,xe=new AbortController;B||S.add(xe);let Ce=()=>!B&&me!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Ie,Fe=new Promise((We,kt)=>{Ie=()=>kt(Ce()),xe.signal.addEventListener("abort",Ie,{once:!0})}),Ee=setTimeout(()=>xe.abort(),c),zt=async()=>{let We=await s(`${o.href.replace(/\/$/,"")}/api/v1/${A}`,{method:w,headers:{"Content-Type":"application/json",...B?{}:{Authorization:`Bearer ${N??u}`},[ps]:ms.current,[rl]:Eg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:w==="POST"?JSON.stringify(P):void 0,signal:xe.signal,credentials:"omit",cache:"no-store",redirect:"error",...R.keepalive?{keepalive:!0}:{}});if(xe.signal.aborted)throw Ce();let kt;try{kt=We.status===204?Xg:await We.json()}catch{throw xe.signal.aborted?Ce():new b(We.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",We.status,We.headers.get("X-Request-Id")??void 0)}if(xe.signal.aborted)throw Ce();if(!B&&me!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!We.ok){let at=ds.safeParse(kt),$t=at.success&&(!Tn.safeParse(at.data.error.code).success||tl(at.data.error.code,We.status)),dr=$t?at.data.error.code:"HTTP_ERROR",pr=Io(dr,We.status,{retryAfter:We.headers.get("Retry-After"),recovery:$t?at.data.error.recovery:void 0,reason:$t?at.data.error.reason:void 0});throw new b(dr,$t?at.data.error.message:"Longplay request failed",We.status,We.headers.get("X-Request-Id")??(at.success?at.data.requestId:void 0),{...pr,...at.success&&at.data.error.retryable===!1?{retryable:!1}:{},...pr.retryAfterSeconds===void 0&&at.success&&at.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:at.data.error.retryAfterSeconds}:{}})}if(We.headers.get(ps)!==ms.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&kt!==Xg){let at=kt&&typeof kt=="object"&&"scope"in kt?kt:kt&&typeof kt=="object"&&"configuration"in kt?kt.configuration:null;if(!at||typeof at!="object"||!("scope"in at))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let $t=Ue.safeParse(at.scope);if(!$t.success||$t.data.projectId!==a.projectId||$t.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let qr=We.headers.get("X-Indiana-Telemetry-Subject");if(qr){if(!/^[a-f0-9]{64}$/.test(qr))throw new b("INVALID_RESPONSE","Invalid telemetry identity");m!==qr&&(m=qr,t?.(m))}return kt};try{return await Promise.race([zt(),Fe])}catch(We){throw!B&&me!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):We instanceof b?We:new b(xe.signal.aborted?"TIMEOUT":"NETWORK_ERROR",xe.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(Ee),xe.signal.removeEventListener("abort",Ie),S.delete(xe)}}return{session:y,requestWithCredential(A,P,w,R={}){return I(A,P,"POST",R,w)},subjectKey:()=>m,identify(A){if(a&&typeof A=="object"&&"scope"in A){let P=Ue.safeParse(A.scope);if(!P.success||P.data.projectId!==a.projectId||P.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}y.identify(A),u=y.peek()??null},reset:f,dispose(){g(),p()},request(A,P={},w="POST",R={}){if(R.installationDetach)return I(A,P,w,R);let N=l;try{let B=y.access(),me=xe=>{if(N!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return I(A,P,w,R,xe)};return typeof B=="string"?me(B):B.then(me)}catch(B){return Promise.reject(B)}}}}function eh(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(!Ft.test(s))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(s),e.identify(o)},reset(){try{n.beforeReset?.()}finally{e.reset()}}}}}import{ZodError as cI}from"zod";function th(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof cI?new b(n,r):i}}async function pe(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=th(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):th(t.response,s,"INVALID_RESPONSE",a.response)}function Be(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}function nh(e){return{async checkEntitlement(t){Be(t);let n=O.checkEntitlement;return pe(e,n,t)},async readHoldings(t={}){let n=O.readHoldings;return pe(e,{...n,request:n.request.omit({customerId:!0})},t)}}}function rh(e){return{async readLedger(t){let n=O.readLedger;return pe(e,n,{query:t})},async readCreditStatement(t){Be(t);let n=O.readCreditStatement;return pe(e,n,t)},async quoteBalance(t){Be(t);let n=O.quoteBalance;return pe(e,n,{command:t})}}}function ih(e){return{async setupPayment(t){Be(t);let n=O.setupPayment;return pe(e,n,t)},async readPaymentSetup(t){Be(t);let n=O.readPaymentSetup;return pe(e,n,t)},async readBillingInvoice(t){Be(t);let n=O.readBillingInvoice;return pe(e,n,t)},async readBillingControls(t={}){Be(t);let n=O.readBillingControls;return pe(e,n,t)},async prepareBillingAuthorization(t){Be(t);let n=O.prepareBillingAuthorization;return pe(e,n,t)},async confirmBillingAuthorization(t){Be(t);let n=O.confirmBillingAuthorization;return pe(e,n,t)},async setBillingCoupons(t){Be(t);let n=O.setBillingCoupons;return pe(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Be(t);let n=O.revokeBillingAuthorization;return pe(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Be(t);let n=O.listBillingInvoices;return pe(e,n,t)},async confirmBillingAdjustment(t){Be(t);let n=O.confirmBillingAdjustment;return pe(e,n,t)}}}function oh(e){return{async previewUpdate(t){Be(t);let n=O.previewUpdate;return pe(e,n,t)},async update(t){Be(t);let n=O.update;return pe(e,n,t)},async readSubscriptionUpdate(t){Be(t);let n=O.readSubscriptionUpdate;return pe(e,n,t)},async restoreNativePurchase(t){Be(t);let n=O.restoreNativePurchase;return pe(e,n,t)},async previewAttach(t){Be(t);let n=O.previewAttach;return pe(e,n,t)},async attach(t){Be(t);let n=O.attach;return pe(e,n,t)},async readSubscriptionOperation(t){Be(t);let n=O.readSubscriptionOperation;return pe(e,n,t)}}}function ah(e){return{async redeemReward(t){return Be(t),(await pe(e,O.redeemReward,{...t,requestId:t.requestId??crypto.randomUUID()},{request:"Invalid reward redemption",response:"Invalid reward receipt"})).redemption},async claimRewardProduct(t){return Be(t),(await pe(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Be(t),(await pe(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 pe(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 pe(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 pe(e,O.listOffers,{},{response:"Invalid offers response"})).offers}}}function sh(e){return{...nh(e),...rh(e),...ih(e),...oh(e),...ah(e)}}function ch(e){return{async resolveContent(t){Be(t);let n=O.resolveContent;return pe(e,n,t)},async resolvePaywall(t){Be(t);let n=O.resolvePaywall;return pe(e,n,t)},async resolveOffering(t){Be(t);let n=O.resolveOffering;return pe(e,n,t)}}}var uh=e=>new TextEncoder().encode(JSON.stringify(e)).length,lh=16384;function dh(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 b("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 l(p,g={},f={}){if(c(),r&&Date.now()<r.until&&!Om(r.config,p))return;y();let I=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:p,properties:g,...f}]}).events[0];if(uh({events:[I]})>lh)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(I)),u()}async function m(p=!1){if(c(),o)return o;let g=n,f=(async()=>{let I={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&&uh({events:[...P,N]})>lh)break;P.push(N)}let w=O.trackEvents,R=await pe(e,w,{events:P},void 0,{keepalive:p});if(g!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(R.inserted+R.duplicates+R.rejected+R.skipped!==P.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(R.analyticsConfig),a.splice(0,P.length),A-=P.length,I.inserted+=R.inserted,I.duplicates+=R.duplicates,I.rejected+=R.rejected,I.skipped+=R.skipped}return I})();o=f;try{return await f}finally{o===f&&(o=null)}}let S;function y(){if(S||typeof document>"u")return;let p=()=>{document.visibilityState==="hidden"&&t()&&a.length&&m(!0).catch(()=>{})};document.addEventListener("visibilitychange",p),S=()=>document.removeEventListener("visibilitychange",p)}return{rememberConfiguration:i,track(p,g,f={}){return y(),l(p,g,f)},flush:m,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){S?.(),S=void 0}}}function Mu(e){let t=null,n=null,r=0,i=0,a=!1,o=new Set,s=null,c=null,u=new Set,l=()=>{for(let A of u)try{A()}catch{}},m={attributes:ht.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},S=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function y(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(w=>[...w.parentConditions??[],...(w.tracks??[]).flatMap(R=>R.experiment.parentConditions??[])].some(R=>y(R.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()?S():structuredClone(s.features[A]??S()):e.evaluateRemote&&(m.attributes?.merchandise||m.attributes?.merchandiseId)&&!a||y(A)?S():structuredClone(Dn(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,w=t,R=[...o],N=(async()=>{let B=Sa.parse(await e.evaluateRemote({attributes:structuredClone(m.attributes),features:R}));if(!(P!==r||A!==i||w!==t)){if(e.assertUsable?.(w.generation),B.generation!==w.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(R.some(me=>!Object.hasOwn(B.features,me))||Object.keys(B.features).some(me=>!o.has(me)))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=ht.parse({...m.attributes,...B.merchandiseContext}),a=!0}s=structuredClone(B),m.features={...w.features,...Object.fromEntries(Object.entries(s.features).map(([me,xe])=>[me,{defaultValue:xe.value}]))},l()}})();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 I(){if(n)return n;let A=r,P=(async()=>{let w=await e.load(),R="remoteFeatures"in w?eo.parse(w):null,N=R??ln.parse(w);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:me,expiresAt:xe,...Ce}=t,{evaluatedAt:Ie,expiresAt:Fe,...Ee}=N;if(yt(Ce)!==yt(Ee))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=N.evaluatedAt,t.expiresAt=N.expiresAt,l(),(!s||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now())&&f(),structuredClone(t)}let B=new Set(R?.remoteFeatures??[]);if([...B].some(me=>Object.hasOwn(N.features,me)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in N&&!t.analyticsConfig.experimentViewsEnabled&&R?.analyticsConfig.experimentViewsEnabled&&m.trackedExperiments?.clear(),t=structuredClone(N),o=B,s=null,c=null,i++,m.features=t.features,m.savedGroups=Kr(t.savedGroups),m.trackedFeatureUsage={},l(),f(),structuredClone(t)})();n=P;try{return await P}finally{n===P&&(n=null)}}return{init:I,refresh:I,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=ht.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={},l(),f()},evalFeature:p,isOn(A){return p(A).on},isOff(A){return p(A).off},getFeatureValue(A,P){let w=p(A).value;return structuredClone(w===null?P:w)},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(),l()}}}function ph(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 uI(e){let t=ph(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function mh(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,m=!1,S=async()=>{if(m||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Ce=O.getFeatures,Ie=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await pe(e,Ce,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Ie.scope.projectId!==r.projectId||Ie.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Ie.payload.analyticsConfig),Ie},y=await S(),p=!0,g,f=Ce=>{try{u.onError?.(Ce)}catch{}},I=(Ce,Ie,Fe)=>{try{let Ee=ph(Fe);n.track(Ce,Ie,Ee?{merchandise:Ee}:{})}catch(Ee){f(Ee)}},A=Mu({assertUsable:i?.assertFeatures,scope:y.scope,attributes:u.attributes,onError:u.onError,load:async()=>p?(p=!1,y.payload):(await S()).payload,evaluateRemote:async Ce=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Ie=O.evaluateFeatures,Fe=await pe(e,Ie,{...Ce,attributes:uI(Ce.attributes)});if(Fe.scope.projectId!==y.scope.projectId||Fe.scope.environment!==y.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:Fe.generation,evaluatedAt:Fe.evaluatedAt,expiresAt:Fe.expiresAt,features:Fe.features,...Fe.merchandiseContext?{merchandiseContext:Fe.merchandiseContext}:{}}},onExperimentViewed:(Ce,Ie,Fe)=>I("Experiment Viewed",{experimentId:Ce.key,variationId:Ie.key},Fe),onFeatureUsage:(Ce,Ie,Fe)=>I("Feature Evaluated",{feature:Ce,value:Ie.value,source:Ie.source,ruleId:Ie.ruleId,...Ie.experimentResult?{variationId:Ie.experimentResult.key}:{}},Fe)}),P=A.refresh;function w(){clearTimeout(g),!i&&(m||l!==a||!A.expiresAt||(g=setTimeout(()=>{R().catch(f)},Math.min(2147483647,Math.max(1e3,Date.parse(A.expiresAt)-Date.now()))),typeof g=="object"&&"unref"in g&&g.unref()))}async function R(){try{return await P()}finally{w()}}let N=()=>{m||R().catch(f)},B=A.subscribe(w),me=i?.subscribe(()=>{!m&&i.fresh&&R().catch(f)});function xe(){m||(m=!0,clearTimeout(g),typeof window<"u"&&window.removeEventListener("focus",N),B(),me?.(),A.reset(),o.delete(xe))}o.add(xe);try{await A.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await A.refreshRemote()}catch(Ce){throw xe(),Ce}return w(),!i&&typeof window<"u"&&window.addEventListener("focus",N),Object.assign(A,{refresh:R,destroy:xe})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as lI}from"zod";function fh(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=lI.object({funnelId:La.shape.id,funnelVersionId:La.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("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 b("SCOPE_MISMATCH","The original Funnel source cannot change");return{...o,...i}}return{async claimCoupon(o,s=crypto.randomUUID()){let c=O.grantOffer,u=await pe(e,c,a({couponId:o,requestId:s}));return{offer:u.offer,reason:u.reason}},async resolveOffering(o){let s=O.resolveOffering;return pe(e,s,a(o))},async resolvePaywall(o){let s=O.resolvePaywall;return pe(e,s,a(o))},async previewAttach(o){let s=O.previewAttach;return pe(e,s,a(o))}}}function gh(e){let t=cr(e),n=t.request,r=Cg(e.push,t,e.scope??e.configuration?.scope),i=eh(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start}),a=dh(n,i.isIdentified),o=mh(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Pg(n,r),...sh(n),...ch(n),forFunnel(s){return fh(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 Si(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)=>Si(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)&&Si(a,Reflect.get(t,i)))}async function Xa(e,t){let n=gg.safeParse(t);if(!n.success)throw new b("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 b("SCOPE_MISMATCH","Funnel scope changed");return r}var xi=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function es(e){let t=Ft.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!xi.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");let n=cr({...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 b("INVALID_REQUEST","Invalid current Funnel start");let a=i.data,o=lo.safeParse(await Xa(e,await n.request("funnels",a)));if(!o.success||!o.data.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");let s=o.data;if(s.run.source.id!==a.funnelId||s.run.locale!==(a.locale??"en")||!Si(s.run.parameters,a.parameters??{})||(a.customer?!s.customerId||a.customer.type==="id"&&s.customerId!==a.customer.value:s.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...s,runToken:s.runToken}}}}async function qu(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 hh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await qu(e,t,n))}function ts(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&Xc(n)===t.sha256}async function ns(e,t){let n=kr.parse(t),{artifact:r,environmentId:i}=n.content,a=new mn(e.baseUrl??sr).origin,o=new mn(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 b("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 b("INVALID_RESPONSE","Public Paywall is unavailable");let l=await qu(u,r.byteLength,{signal:s.signal,error:m=>new b("INVALID_RESPONSE",m==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ts(l,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return bf(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(l)))}finally{clearTimeout(c)}}var Ah=(e,t)=>new b(e,t);async function Vu(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 b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("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=dI(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 dI(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=mu({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:ln.parse(o)}),c=pI(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function pI(e,t,n){return wg(e,t,n,Ah)}import{z as kn}from"zod";var yh=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 b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),bh=kn.strictObject({schemaVersion:kn.literal(1),scope:Ue,runId:kn.uuid(),funnelId:kn.uuid(),versionId:kn.uuid(),command:yh.optional(),closeCommand:yh.refine(e=>e.operation==="close").optional(),purchase:kn.strictObject({receiptId:kn.uuid(),operationId:kn.uuid(),generation:kn.number().int().nonnegative()}).optional(),closed:kn.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"),Wt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),rs=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Sh(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 b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:c.revision,entry:c.entry===null?null:bh.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 l=await a();if(l.entry&&n!==null&&r(l.entry)!==n)throw Wt();let m=c(l.entry,l.revision);if(rs(l.entry,m)){t=l.revision;return}let S=await e.write(l.revision,m);if(S!==null){if(!Number.isSafeInteger(S)||S<=l.revision)throw Wt();t=S;return}}throw Wt()}return{bind(c){let u=JSON.stringify([c.scope,c.runId,c.funnelId,c.versionId]);if(n!==null&&n!==u)throw Wt();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=bh.parse(c),l=u.command;return!l||n!==null&&r(u)!==n?Promise.reject(Wt()):(n??(n=r(u)),o(()=>s((m,S)=>{if(m&&!rs(r(m),r(u)))throw Wt();if(!m){if(S!==t&&l.operation!=="close")throw Wt();return u}if(!m.command)return{...m,command:l,...l.operation==="close"?{closed:!0}:{}};if(l.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===l.requestId||m.closeCommand&&!rs(m.closeCommand,l))throw Wt();return{...m,closeCommand:l,closed:!0}}if(!rs(m.command,l))throw Wt();return m})))},observePurchase(c,u,l){return o(()=>s((m,S)=>{if(!m&&S!==t||m&&r(m)!==r({...c,schemaVersion:1}))throw Wt();if(m?.purchase&&m.purchase.generation>u.generation)return m;if(m?.purchase&&m.purchase.generation===u.generation&&m.purchase.operationId!==u.operationId)throw Wt();return l?!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 xh(e){let t,n,r=()=>new b("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??sr).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 b?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 Ih(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 b("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||!Si(s.parameters,t.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&s.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(s,c,u,l,m){if(!(s.operation==="review"&&t&&t!==u&&c.run.revision<=t.revision)&&!(t&&c.run.revision===t.revision&&l!==void 0&&l<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 S of o)try{S(structuredClone(t))}catch{}}},identify(s){if(!Ft.test(s))throw new b("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 ur(e){let{customerToken:t,...n}=e;return n}var mI=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status);function vh({options:e,journal:t,state:n,call:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=!1,u,l=null,m=t?t.load().then(f=>{if(n.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=f,!f)return;if(e.scope&&(f.scope.projectId!==e.scope.projectId||f.scope.environment!==e.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=f.purchase,o=f.closed===!0,!f.command)return;let I=Un.parse(f.command);if(I.operation==="start"||I.operation==="get"||I.operation==="review")throw new b("COMMAND_STORAGE_INVALID","Stored mutation required");i=I,f.closeCommand&&(a=f.closeCommand,o=!0),I.operation==="close"&&(o=!0),c=!0}):Promise.resolve();m.catch(()=>{});async function S(f=i){if(t&&await m,!f)throw new b("INVALID_REQUEST","No command is pending");let I=f,A=n.generation;if(t){if(!n.view||!e.scope)throw new b("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:ur(I)})}if(A!==n.generation||i!==I&&a!==I)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let P={...I,...n.customerToken?{customerToken:n.customerToken}:{}},w=c;c=!0;try{return await r(P,R=>{if(!R.settlement)throw new b("INVALID_RESPONSE","Exact command settlement is missing");if(R.settlement.requestId!==I.requestId)throw new b("INVALID_RESPONSE","Command settlement identity changed");if(A===n.generation&&(i===I||a===I)&&R.run.pendingRequest?.requestId!==I.requestId&&R.settlement.state==="settled"&&(!o||I.operation==="close"||R.settlement?.state==="settled"&&!["running","waiting"].includes(R.run.status))){let N=()=>A!==n.generation||i!==I&&a!==I?!1:(i===I&&(i=null),a===I&&(a=null),c=i!==null,l=null,!0);return t?t.settle(I.requestId).then(N):N()}return!1})}catch(R){throw A===n.generation&&i===I&&!w&&!mI(R)&&(t&&await t.settle(I.requestId),A===n.generation&&i===I&&(i=null,c=!1,l=null)),R}}function y(f){let I=Un.parse(f);if(I.operation==="start"||I.operation==="get"||I.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&I.operation!=="close"){if(i?.requestId===I.requestId)return g(I.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(I.operation==="close"&&i?.operation!=="close"){if(o=!0,a&&JSON.stringify(ur(a))!==JSON.stringify(ur(I)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=I),s.close?s.close:p(a,"close")}if(i){if(JSON.stringify(ur(i))!==JSON.stringify(ur(I)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=I,c=!1;return p(i,"command")}function p(f,I){let A=S(f);s[I]=A;let P=()=>{s[I]===A&&(s[I]=null)};return A.then(P,P),A}async function g(f){let I=await r({operation:"get",settlementRequestId:f,...n.customerToken?{customerToken:n.customerToken}:{}});if(I.settlement?.requestId!==f)throw new b("INVALID_RESPONSE","Exact command settlement is missing");return I.settlement.state==="settled"&&(t&&await t.settle(f),i?.requestId===f&&(i=null,c=!1),a?.requestId===f&&(a=null)),I}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(l&&(f.run.id!==l.runId||f.run.source.id!==l.funnelId||f.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},observePurchase(f,I,A,P){t?.bind({scope:I.scope,runId:I.run.id,funnelId:I.run.source.id,versionId:I.run.source.versionId}),t&&!e.scope&&(e.scope=I.scope);let w=I.run.paywall,R=w??I.purchase,N=R?.operation,B=I.settlement&&(!w||w.purchaseRequestId===I.settlement.requestId)&&(!u||u.operationId===I.settlement.operationId)?I.settlement:void 0,me=N?.operationId??R?.quote?.operationId??B?.operationId,xe=R?.receiptId??B?.receiptId,Ce=w?.selectionGeneration??u?.generation??0;if(t&&me&&xe&&f.operation!=="review"&&(!n.view||I.run.revision>=n.view.revision)&&(P===void 0||P>=n.readSequence)&&(!u||Ce>=u.generation)){let Ie={receiptId:xe,operationId:me,generation:Ce},Fe=N?.status==="complete"||R?.canReselect===!0;return t.observePurchase({scope:I.scope,runId:I.run.id,funnelId:I.run.source.id,versionId:I.run.source.versionId},Ie,Fe).then(()=>{n.assertCurrent(A),Fe?u?.operationId===Ie.operationId&&(u=void 0):u=Ie})}},stop(){o=!0},submit:y,executePending:S,settle:g,reset(){i=null,a=null,s.close=null,c=!1,s.command=null}}}function Ii(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!xi.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=cr({...e,session:void 0,...e.serverKey?{fetch:(f,I)=>{let A=new Headers(I?.headers),P=typeof I?.body=="string"?JSON.parse(I.body):null;return P!==null&&typeof P=="object"&&"customerToken"in P&&typeof P.customerToken=="string"&&P.customerToken.length>0||A.set(hg,e.serverKey),(e.fetch??globalThis.fetch)(f,{...I,headers:A})}}:{},...e.session?{fetch:async(f,I)=>{let A=await e.session.access(),P=typeof I?.body=="string"?JSON.parse(I.body):{};if(!P||typeof P!="object"||Array.isArray(P))throw new b("INVALID_REQUEST","Run command must be an object");return(e.fetch??globalThis.fetch)(f,{...I,body:JSON.stringify({...P,customerToken:A})})}}:{},timeoutMs:e.timeoutMs??35e3});t.identify(e.runToken);let n=Ih(e.funnelId),r=e.session?.subscribeIdentity(()=>{n.reset(),t.reset()}),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?xh(e):void 0),o=a&&Sh(a),s=vh({options:e,journal:o,state:n,call:c});async function c(f,I,A){let P=n.generation,w=()=>n.assertCurrent(P);o&&await s.ready,w();let R=n.view,N=lo.parse(await Xa(e,await t.request("funnels",Un.parse(f))));if(f.operation==="review"&&!N.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(w(),N.runToken&&N.runToken!==e.runToken)throw new b("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 b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(N),n.assertRun(N.run);let me=s.observePurchase(f,N,P,A);if(me&&await me,!N.run.stopped&&["running","waiting"].includes(N.run.status)&&f.operation==="get"&&f.settlementRequestId)return N;let xe=I?.(N),Ce=typeof xe=="boolean"?xe:xe?await xe:!1;return w(),["running","waiting"].includes(N.run.status)||s.stop(),n.publish(f,N,R,A,Ce),N}let u=s.submit,l=null,m=new WeakMap;function S(f){let I=m.get(f);if(I)return I;let A=p(f);return m.set(f,A),A}let y=!1;async function p(f){let I=await f;if(I.run.instruction?.type!=="evaluate_segment")return I;if(l)return l;y=!0;let A=n.generation,P=(async()=>{for(let w=0;w<32&&I.run.instruction?.type==="evaluate_segment";w++){if(s.pending||s.closeRequested)return I;let R=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:B}=await Vu(e.configuration,R,{predict:!1});if(A!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return I;if(n.view&&(n.view.revision!==R.revision||n.view.visit!==R.visit||n.view.nodeId!==R.nodeId))return c({operation:"get",...n.customerToken?{customerToken:n.customerToken}:{}});let me=!0;Vu(e.configuration,R).then(({prediction:xe})=>{me&&A===n.generation&&!s.closeRequested&&n.view?.id===R.id&&!n.view.stopped&&n.view.nodeId===R.nodeId&&n.view.visit===R.visit&&n.view.revision===R.revision&&(i=xe)}).catch(()=>{});try{I=await u({operation:"commit_segment",requestId:fg(R.id,R.visit,`segment:${R.revision}`),nodeId:R.nodeId,visit:R.visit,revision:R.revision,...B})}finally{me=!1,i=null}}}return I})();l=P;try{return await P}finally{l===P&&(l=null)}}let g={get configuration(){return y?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(ur(f)):null},get pendingCommands(){return[s.pending,s.closing].filter(f=>f!==null).map(f=>structuredClone(ur(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 ns(e,f)},async pageExperiments(f,I=[]){let A=n.generation;n.assertCurrent(A);let P=n.view?.id;if(!P)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let w=_g.parse(await t.request("funnels",Og.parse({operation:"page_experiments",release:f,usedReceiptIds:I,...n.customerToken?{customerToken:n.customerToken}:{}})));if(n.assertCurrent(A),w.runId!==P||w.scope.projectId!==e.scope?.projectId||w.scope.environment!==e.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return w},review(f){return c({operation:"review",...f?{receiptId:f}:{},...n.customerToken?{customerToken:n.customerToken}:{}},void 0,n.nextRead())},async get(f,I){o&&await s.ready,I??(I=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let A=n.nextRead();return S(c({operation:"get",...f?{data:f}:{},...I?{purchase:I}:{},...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?S(u(s.pending)):S(u({operation:"resume",requestId:f})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(f){return S(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?S(s.inFlight):s.pending?S(u(s.pending)):Promise.reject(new b("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 wh(e){if(!Ft.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=es({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=Ii({...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 Oh(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 _h(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function Ch(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 b("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 b("INVALID_RESPONSE",n)}function Ph(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 Eh(e,t){if(!Ft.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");let n=cr(e);if(!e.session)n.identify(t.customerToken);else if(e.session.peek()!==t.customerToken)throw new b("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,l=e.session?.subscribeIdentity(()=>{a=!0,n.dispose(),i=null,o=null,s=null,c=null});async function m(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed");let p=O.resolvePaywall,g=await pe(n.request,p,{...r,selector:i?{type:"version",versionId:i.id}:r.selector}),f={paywall:await ns(e,g.paywall)};if(a)throw new b("IDENTITY_CHANGED","Paywall is closed");if(t.paywallVersionId?f.paywall.id!==t.paywallVersionId:f.paywall.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!Oh(f.paywall,i)||f.paywall.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=f.paywall,structuredClone(i)}async function S(p){if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let g=p==="read"?O.readSubscriptionOperation:O.attach,f=await pe(n.request,g,{operationId:o.operationId,...p==="read"?{}:{intent:p}});return _h(f.operation,{operationId:o.operationId,currency:r.commerce.currency},"The purchase operation changed"),s=Ph(s,f.operation),structuredClone(s)}let y={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 b("INVALID_REQUEST","Load the Paywall first");let g=i.document.buttons[p.actionId];if(g?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let f=Im(g.product,p.selection,i.capabilities);if(!f)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let I=lf(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(I).length?{featureQuantities:I}:{}}],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 b("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 w=(async()=>{let R=O.previewAttach,N=await pe(n.request,R,A);return Ch(N.quote,{productVersionId:f,featureQuantities:I,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=w;try{return await w}finally{u===w&&(u=null)}},confirm:()=>S("confirm"),cancel:()=>S("cancel"),read:()=>S("read"),destroy(){l?.(),a=!0,n.dispose(),i=null,o=null,s=null,c=null}};return await m(),y}function Rh(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let y=r;n&&e.nativeModule&&n.then(p=>e.nativeModule.reset(p,y)).catch(()=>{})}),l=e.nativeEvents?.(y=>{!n||!e.nativeModule||typeof y?.requestId!="string"||(async()=>{let p=await n;if(y.instanceId!==p)return;if(y.kind==="credential"){let I=r,A=null;try{if(!o&&y.revision===I){let P=await t.access();!o&&r===I&&(A=P)}}finally{await e.nativeModule.provideCredential(p,y.requestId,A)}return}let g=!1,f=r;try{if(o||y.revision!==f||!e.onNativeAction)throw c();await e.onNativeAction(y.action),g=!o&&r===f}finally{await e.nativeModule.acknowledge(p,y.requestId,g)}})().catch(()=>{})});async function m(y,p={}){let g=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let f=r,I=await t.access();if(o||r!==f)throw c();if(!n){let w=g.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=w,w.catch(()=>{n===w&&(n=void 0)})}let A=await n;if(o||r!==f)throw c();if(i!==f){if(!a||a.epoch!==f){let R=(async()=>{if(await g.identify(A,JSON.stringify({revision:f,credentials:I})),o||r!==f)throw await g.reset(A,f),c();i=f})();a={epoch:f,task:R}}let w=a;try{await w.task}finally{a===w&&(a=void 0)}}let P=await g.invoke(A,y,JSON.stringify(p));if(o||r!==f)throw c();try{return JSON.parse(P)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function S(y,p){let g=await m(y,p);if(!g||typeof g!="object"||Array.isArray(g)||g.status!=="complete"&&g.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return g}return{showFunnel(y){return S("showFunnel",{runToken:y})},showPaywall(y){return S("showPaywall",y)},showContent(y){return S("showContent",y)},purchaseSubscription(y,p){return m("purchaseSubscription",{operationId:y,accepted:p})},switchSubscription(y,p){return m("switchSubscription",{operationId:y,accepted:p})},restorePurchases(){return m("restorePurchases")},manageSubscriptions(y){return m("manageSubscriptions",y?{productId:y}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var fI=O.trackUsage.request.shape.command,gI=O.trackUsage.response;function hI(e){let t=Ue.parse(e.scope),n=gh({...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 b("UNAUTHENTICATED","Identify the Customer first");return o};return{...n,native:Rh(e,n.session),funnel(){return wh({...r,customerToken:a()})},resumeFunnel(o){return a(),Ii({...r,runToken:o})},paywall(o){return Eh(r,{...o,customerToken:a()})},async trackUsage(o){if(!n.session.peek())throw new b("UNAUTHENTICATED","Identify the Customer first");if(!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let s=fI.parse(o),c=i,u;try{u=await e.usageReporter(s)}catch(m){throw c!==i?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):m}if(c!==i)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let l=gI.parse(u);if(l.scope.projectId!==t.projectId||l.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return l}}}import{z as SI}from"zod";import{z as ho}from"zod";var AI=ho.record(ho.string().regex(/^[a-f0-9]{64}$/),ho.strictObject({at:ho.number(),text:ho.string()})),kh=2*1048576,yI=100;function bI(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function jh(e,t){let n=t===void 0?bI():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),yI)})])}catch{return null}finally{clearTimeout(s)}}async function a(){try{let o=await i(`${e}:artifacts`);if(o&&o.length<=kh)return AI.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 l={},m=2,S=0;for(let[y,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({[y]:p})).byteLength;m+g>kh||S>=128||(l[y]=p,m+=g,S++)}await n.setItem(`${e}:artifacts`,JSON.stringify(l))}).catch(()=>{}))}}}var _e=(e,t)=>new b(e,t),lr=()=>performance.now(),Th=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function xI(e){let t=Zc.parse(e.scope),n=new mn(e.origin??sr);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(Y=>{let H=new mn(Y);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}:${yt(t)}`,s=jh(o,e.storage),c,u=0,l=0,m=!1,S=!1,y=0,p=0,g,f,I,A,P=0,w=new Set,R=new Set,N=new Map,B=new Map,me=0,xe=!1;function Ce(){for(let Y of w)try{Y()}catch{}}function Ie(Y){try{e.onError?.(Y)}catch{}}let Fe=()=>!S&&!m&&!!c&&lr()<u&&Date.now()<l;function Ee(){if(!Fe())throw _e("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function zt(Y,H){let se=new TextEncoder().encode(H).byteLength;if(!N.has(Y)){for(;N.size&&(N.size>=128||me+se>Zt.maxCacheBytes);){let ce=N.entries().next().value;me-=new TextEncoder().encode(ce[1]).byteLength,N.delete(ce[0])}N.set(Y,H),me+=se}}function We(Y,H,se){return hh(Y,H,{signal:se,error:ce=>_e("INVALID_RESPONSE",ce==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function kt(Y){let H=new mn(Y,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 Ao(Y,H,se=!1){let ce=await i(kt(Y),{method:"GET",credentials:"omit",redirect:"error",cache:se?"default":"no-cache",signal:H,headers:{}});if(ce.status===429){let Ne=ce.headers.get("retry-after")??"";P=/^\d+$/.test(Ne)?Number(Ne)*1e3:Math.max(0,Date.parse(Ne)-Date.now())||15e3}if(!ce.ok&&ce.status!==304)throw _e(`CONFIGURATION_HTTP_${ce.status}`,"Configuration synchronization failed");return ce}function qr(Y,H,se){let ce=Date.parse(Y.headers.get("x-indiana-config-validated-at")??""),Ne=Date.parse(Y.headers.get("x-indiana-config-valid-until")??""),wt=Date.parse(Y.headers.get("date")??""),Ke=Y.headers.get("age"),Yt=Ke!==null&&/^\d+(\.\d+)?$/.test(Ke)?Number(Ke)*1e3:NaN;if(![ce,Ne,wt,Yt].every(Number.isFinite)||Ne<=ce||Ne-ce>Zt.maxControlAgeMs||ce>wt+1e3)throw _e("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Ot=Math.min(Ne-ce,se.maxControlAgeSeconds*1e3,Zt.maxControlAgeMs)-Math.max(Yt,wt-ce,0)-(lr()-H);if(Ot<=0)throw _e("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return lr()+Ot}function at(){if(clearTimeout(I),clearTimeout(A),S||!w.size)return;Fe()&&(A=setTimeout(()=>{Fe()?at():Ce()},Math.max(1,u-lr())),Th(A));let Y=p?Math.min(15e3,1e3*2**Math.min(p-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);I=setTimeout(()=>{$t().catch(Ie)},Math.max(P,Y*(.8+Math.random()*.2))),Th(I)}async function $t(){if(S)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(g)return g;let Y=y,H=new AbortController;f=H;let se=(async()=>{if(!xe){xe=!0;try{let bo=await s.readManifest();if(bo&&!c){let jn=Yc.parse(JSON.parse(bo));yt(jn.scope)===yt(t)&&(c=jn)}}catch{}}H.signal.throwIfAborted();let Ke=c,Yt=lr(),Nt=await Ao(a,H.signal);Nt.status===304&&(!Ke||!Nt.headers.has("x-indiana-config-validated-at")||!Nt.headers.has("x-indiana-config-valid-until")||!Nt.headers.has("age"))&&(Nt=await Ao(a,H.signal));let Ot=Nt.status===304?Ke:Yc.parse(JSON.parse(await We(Nt,Zt.maxManifestBytes,H.signal))),{generation:zn,...$n}=Ot,mr=Nt.headers.get("etag");if(yt(Ot.scope)!==yt(t)||gf($n)!==zn||mr!==`"${zn}"`&&mr!==`W/"${zn}"`)throw _e("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ke&&(Ot.revision<Ke.revision||Ot.revision===Ke.revision&&Ot.generation!==Ke.generation))throw _e("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[bo,jn]of Object.entries(Ke?.funnels??{})){let fr=Ot.funnels[bo];if(fr&&(fr.controlRevision<jn.controlRevision||fr.evaluationRevision<jn.evaluationRevision||fr.controlRevision===jn.controlRevision&&fr.state!==jn.state||fr.evaluationRevision===jn.evaluationRevision&&fr.evaluationMode!==jn.evaluationMode))throw _e("INVALID_RESPONSE","Funnel control revision changed identity")}let $u=qr(Nt,Yt,Ot.policy);if(H.signal.throwIfAborted(),Y!==y)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Ot,u=$u,l=Date.now()+Math.max(0,$u-lr()),m=!1,p=0,P=0,s.writeManifest(yt(Ot)),Ce(),structuredClone(Ot)})(),ce=setTimeout(()=>H.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs),Ne=new Promise((Ke,Yt)=>H.signal.addEventListener("abort",()=>Yt(H.signal.reason),{once:!0})),wt=Promise.race([se,Ne]).catch(Ke=>{throw p++,(Ke instanceof SI.ZodError||Ke instanceof SyntaxError||Ke instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ke.code))&&(u=0,m=!0,Ce()),Ke}).finally(()=>{clearTimeout(ce),g===wt&&(g=void 0),at()});return g=wt,wt}async function dr(Y){let H=Y.sha256,se=zn=>ts(zn,Y);kt(Y.url);let ce=N.get(H);if(ce&&se(ce))return N.delete(H),N.set(H,ce),ce;if(B.has(H))return B.get(H);let Ne=new AbortController;R.add(Ne);let wt=y,Ke=(async()=>{try{let mr=await s.readArtifact(H);if(mr&&se(mr))return zt(H,mr),mr}catch{}Ne.signal.throwIfAborted();let zn=await Ao(Y.url,Ne.signal,!0),$n=await We(zn,Y.byteLength,Ne.signal);if(!se($n))throw _e("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(S||wt!==y)throw _e("CONFIGURATION_DISPOSED","Configuration scope changed");return zt(H,$n),s.writeArtifact(H,$n),$n})(),Yt=setTimeout(()=>Ne.abort(_e("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Zt.initializationMs),Nt=new Promise((zn,$n)=>Ne.signal.addEventListener("abort",()=>$n(Ne.signal.reason),{once:!0})),Ot=Promise.race([Ke,Nt]).finally(()=>{clearTimeout(Yt),R.delete(Ne),B.delete(H)});return B.set(H,Ot),Ot}async function pr(){return Fe()||await $t(),Ee(),c}async function vi(Y){let H,se=new Promise((ce,Ne)=>{H=setTimeout(()=>Ne(_e("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Zt.initializationMs)});try{return await Promise.race([Y(),se])}finally{clearTimeout(H)}}function wi(Y,H){if(Ee(),c?.generation!==Y.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 Bu(Y){let H=Y.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let se=Y.artifacts[H];if(se.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let ce=Ic.parse(JSON.parse(await dr(se)));if(yt(ce.scope)!==yt({projectId:t.projectId,environment:t.environment})||ce.generation!==se.generation||ce.remoteFeatures.some(Ne=>Object.hasOwn(ce.features,Ne)))throw _e("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return wi(Y),{...ce,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-lr())).toISOString()}}async function Uu(Y,H){let se=await pr(),ce=se.funnels[Y];H&&(!ce||ce.evaluationMode==="local"&&!ce.versions[H])&&(g&&await g,se=await $t()),wi(se,Y);let Ne=se.funnels[Y];if(Ne.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let wt=H??Ne.currentVersionId,Ke=Ne.versions[wt];if(!Ke)throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(se.artifacts[Ke.artifact].formatVersion!==3)throw _e("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[Yt,Nt]=await Promise.all([dr(se.artifacts[Ke.artifact]).then(Ot=>Af(JSON.parse(Ot))),Ne.evaluationMode==="local"?Bu(se):void 0]);if(Nt&&yt(hf(Yt,Nt))!==yt(Ke.dependencies))throw _e("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return wi(se,Y),{document:Yt,growth:Nt,versionId:wt,control:structuredClone(Ne),manifest:structuredClone(se)}}async function Lu(Y,H){try{return await Uu(Y,H)}catch(se){if(!(se instanceof b)||!(se.code==="CONFIGURATION_CHANGED"||se.code==="CONFIGURATION_HTTP_404"&&Fe()))throw se;let ce=c?.generation;if(g&&await g,await $t(),se.code!=="CONFIGURATION_CHANGED"&&c?.generation===ce)throw se;return Uu(Y,H)}}function is(){m=!0,Ce(),$t().catch(Ie)}let yo=()=>{(typeof document>"u"||document.visibilityState==="visible")&&is()};function Nh(Y){if(S)throw _e("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return w.add(Y),w.size===1&&(typeof window<"u"&&(window.addEventListener("online",is),window.addEventListener("focus",yo),document.addEventListener("visibilitychange",yo)),at()),()=>{w.delete(Y),w.size||(clearTimeout(I),clearTimeout(A),zu())}}function zu(){typeof window<"u"&&(window.removeEventListener("online",is),window.removeEventListener("focus",yo),document.removeEventListener("visibilitychange",yo))}return{scope:Object.freeze({...t}),refresh:$t,subscribe:Nh,assertFresh:Ee,assertFeatures(Y){Ee();let H=c.gb.features;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(Y!==void 0&&c.artifacts[H].generation!==Y)throw _e("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return Fe()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return Fe()?Math.max(0,u-lr()):0},async features(){return vi(async()=>Bu(await pr()))},pageExperiments:()=>vi(async()=>{let Y=await pr(),H=Y.gb.pageExperiments;if(!H)throw _e("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let se=Y.artifacts[H];if(se.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let ce=xg.parse(JSON.parse(await dr(se)));if(ce.environmentId!==t.environmentId||ce.generation!==se.generation)throw _e("INVALID_RESPONSE","Page experiment scope or generation changed");return wi(Y),ce}),funnel:(Y,H)=>vi(()=>Lu(Y,H)),paywall:(Y,H)=>vi(async()=>{let se=await pr(),ce=se.paywalls?.[Y];if(!ce||!H&&ce.state!=="published")throw _e("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let Ne=H??ce.currentVersionId,wt=ce.versions[Ne],Ke=wt&&se.artifacts[wt.artifact];if(!Ke||Ke.kind!=="paywall"||Ke.formatVersion!==1)throw _e("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let Yt=Ua.parse(JSON.parse(await dr(Ke)));return wi(se),{document:Yt,versionId:Ne,version:wt.version,control:structuredClone(ce),manifest:structuredClone(se)}}),async localFunnel(Y,H){let se=await vi(()=>Lu(Y,H));if(!se.growth)throw _e("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:ce,remoteFeatures:Ne,...wt}=se.growth;return bg({scope:{projectId:t.projectId,environment:t.environment},funnelId:Y,versionId:se.versionId,evaluationMode:"local",evaluationRevision:se.control.evaluationRevision,document:se.document,payload:wt})},assertFunnel(Y,H,se){Ee();let ce=c.funnels[Y];if(!ce||ce.state!=="active")throw _e("FUNNEL_STOPPED","Funnel is paused or unavailable");if(ce.evaluationMode!=="local")throw _e("EVALUATION_MODE","This Funnel now executes at Longplay");if(H!==void 0&&ce.controlRevision!==H)throw _e("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(se!==void 0&&!ce.versions[se])throw _e("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!S){S=!0,y++,u=0,f?.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(I),clearTimeout(A),zu(),Ce(),w.clear();for(let Y of R)Y.abort(_e("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));N.clear(),me=0}}}}async function II(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&yt(n)!==yt(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=xi.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=es({...e,scope:n,apiKey:e.credential}),o=s=>{let c=Ii({...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),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}export{b as LongplayError,xI as createConfigurationSync,Mu as createFeatureClient,II as createLocalFunnelClient,hI as createLongplayReactNative};
17
+ */var Se=N.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=N.record(N.string().min(1).max(128),Se).superRefine((e,t)=>{(!Se.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"})}),iy=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"]),Jt=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"&&!N.strictObject({id:N.uuid(),attributeKey:N.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("$")&&!iy.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)}),oy=N.discriminatedUnion("type",[N.strictObject({type:N.literal("condition"),condition:Jt}),N.strictObject({type:N.literal("list"),attributeKey:N.string().min(1).max(128),values:N.array(N.union([N.string(),N.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 Ln(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 ay=N.record(N.uuid(),oy).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"&&Ln(o.condition).forEach(i),n.delete(a),r.add(a)}Object.keys(e).forEach(i)}),Zs=N.tuple([N.number().min(0).max(1),N.number().min(0).max(1)]).refine(([e,t])=>e<=t),wd=N.strictObject({attribute:N.string().optional(),seed:N.string().min(1),hashVersion:N.literal(2),ranges:N.array(Zs).min(1).max(100)}),sy=N.strictObject({id:N.string().min(1).max(128),condition:Jt,gate:N.boolean().optional()}),Js={id:N.string().max(128).optional(),condition:Jt.optional(),parentConditions:N.array(sy).max(50).optional(),filters:N.array(wd).max(20).optional()},cy=N.union([N.strictObject({...Js}),N.strictObject({...Js,force:Se,coverage:N.number().min(0).max(1).optional(),range:Zs.optional(),seed:N.string().min(1).optional(),hashAttribute:N.string().optional(),hashVersion:N.literal(2).optional()}),N.strictObject({...Js,type:N.literal("experiment-ref"),experimentId:N.uuid(),values:N.record(N.string().min(1),Se),meta:N.record(N.string().min(1),N.strictObject({passthrough:N.boolean()})).optional()})]),uy=N.strictObject({defaultValue:Se,rules:N.array(cy).max(100)}),Tw=N.record(N.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),uy).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)}),ly=N.strictObject({name:N.string().max(80),reason:N.string().max(500),dateStarted:N.iso.datetime({offset:!0}),dateEnded:N.iso.datetime({offset:!0}).nullable(),coverage:N.number().min(0).max(1),variationWeights:N.array(N.number().min(0).max(1)).min(2).max(20).refine(e=>Math.abs(e.reduce((t,n)=>t+n,0)-1)<=.01),condition:Jt,savedGroups:N.array(N.strictObject({match:N.enum(["any","all","none"]),ids:N.array(N.uuid()).min(1)})).max(50),namespace:N.strictObject({id:N.uuid(),ranges:N.array(Zs).min(1)}).nullable(),seed:N.string().min(1).max(128)}),dy=N.strictObject({key:N.string().min(1).max(128),name:N.string().min(1).max(80),hypothesis:N.string().max(2e3),status:N.enum(["draft","running","stopped"]),hashAttribute:N.string().min(1).max(128),fallbackAttribute:N.string().max(128).nullable(),hashVersion:N.literal(2),disableStickyBucketing:N.boolean(),bucketVersion:N.number().int().min(0).max(1e3),minBucketVersion:N.number().int().min(0).max(1e3),variations:N.array(N.strictObject({id:N.string().min(1),key:N.string().min(1),name:N.string().max(80),description:N.string().max(500)})).min(2).max(20),phases:N.array(ly).min(1).max(100),releasedVariationId:N.string().nullable(),excludeFromPayload:N.boolean(),statusSchedule:N.strictObject({startAt:N.iso.datetime({offset:!0}).nullable(),stopAt:N.iso.datetime({offset:!0}).nullable(),stopAfter:N.strictObject({value:N.number().int().positive().max(36500),unit:N.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 py=dy.safeExtend({filters:N.array(wd).optional()}),my=N.strictObject({experiments:N.record(N.uuid(),py),savedGroups:ay}),Mi=N.strictObject({attributeName:N.string(),attributeValue:N.string(),assignments:N.record(N.string(),N.string())}),Nw=N.strictObject({snapshot:my,attributes:xt,results:xt,stickyBucketAssignmentDocs:N.record(N.string(),Mi)}),Dw=N.strictObject({variantKey:N.string().nullable(),bucketVersion:N.number().int().min(0),source:N.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),bucket:N.number().min(0).max(1).optional(),stickyBucketUsed:N.boolean().optional(),hashUsed:N.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 fy=kt.enum(["active","inactive"]),gy=kt.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),hy=kt.strictObject({id:kt.string().trim().min(1).max(255),name:kt.string().trim().min(1).max(255),status:fy,metadata:gy}),Lw=hy.extend({internal_id:kt.uuid(),project_id:kt.uuid(),environment_id:kt.uuid(),created_at:kt.iso.datetime({offset:!0}),updated_at:kt.iso.datetime({offset:!0})}),Pd=kt.union([kt.strictObject({id:kt.string().trim().min(1).max(255)}),kt.strictObject({internalId:kt.uuid()})]),Uw=kt.enum(["customer","merchandise","context"]),zw=kt.enum(["system","stored","request"]),$w=kt.enum(["customer","merchandise","mixed"]),Od=e=>e==="merchandiseId"||e==="merchandise"||e.startsWith("merchandise.");function Ws(e,t={},n=new Set){if(Zn(e).some(Od))return!0;for(let r of Ln(e)){if(n.has(r))continue;n.add(r);let i=t[r];if(i?.type==="list"&&Od(i.attributeKey)||i?.type==="condition"&&Ws(i.condition,t,n))return!0}return!1}import{z as Ay}from"zod";var yy=/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,yn=Ay.string().max(16).regex(yy,"\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 Yw=X.enum(["draft","active","paused","archived"]),Wn=X.discriminatedUnion("type",[X.object({type:X.literal("percent"),percentOff:X.number().min(1).max(100).multipleOf(.01)}).strict(),X.object({type:X.literal("amount"),amountOffCents:X.number().int().min(1).max(1e8),currency:be}).strict()]),nn=X.discriminatedUnion("type",[X.object({type:X.literal("once")}).strict(),X.object({type:X.literal("repeating"),months:X.number().int().min(1).max(36)}).strict(),X.object({type:X.literal("forever")}).strict()]),Cd=[X.object({type:X.literal("all")}).strict(),X.object({type:X.literal("plans"),planIds:X.array(X.uuid()).min(1).max(50).refine(e=>new Set(e).size===e.length,"\u5957\u9910\u4E0D\u80FD\u91CD\u590D")}).strict()],by=X.discriminatedUnion("type",[...Cd,X.strictObject({type:X.literal("merchandise"),scope:X.discriminatedUnion("type",[X.strictObject({type:X.literal("all")}),X.strictObject({type:X.literal("selected"),merchandiseIds:X.array(X.uuid()).min(1).max(1e3).refine(e=>new Set(e).size===e.length,"Duplicate merchandise")}),X.strictObject({type:X.literal("condition"),condition:Jt})])})]),Ys=X.discriminatedUnion("type",[...Cd,X.strictObject({type:X.literal("merchandise"),scope:X.strictObject({type:X.enum(["all","selected","condition"])})})]),xy=X.strictObject({firstPurchaseOnly:X.boolean(),condition:Jt}),Xw=X.object({name:X.string().trim().min(1).max(80),description:X.string().max(500),discount:Wn,duration:nn,appliesTo:by,eligibility:xy,selfClaimEnabled:X.boolean().default(!1),startsAt:X.iso.datetime().nullable(),endsAt:X.iso.datetime().nullable(),totalLimit:X.number().int().min(1).max(1e6).nullable(),perCustomerLimit:X.number().int().min(1).max(10),grantWindowHours:X.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=>!Ws(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"]}),eO=X.object({code:X.string().trim().transform(e=>e.toUpperCase()).pipe(X.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:X.number().int().min(1).max(1e6).nullable(),expiresAt:X.iso.datetime().nullable(),firstPurchaseOnly:X.boolean(),minimumAmountCents:X.number().int().min(1).max(1e8).nullable(),minimumAmountCurrency:be.nullable()}).strict().refine(e=>e.minimumAmountCents===null==(e.minimumAmountCurrency===null),"Minimum amount requires its currency");var qi=X.object({id:X.uuid(),couponId:X.uuid(),status:X.enum(["issued","reserved","redeemed","revoked","expired"]),issuedAt:X.iso.datetime(),expiresAt:X.iso.datetime(),coupon:X.object({name:X.string(),discount:Wn,duration:nn,appliesTo:Ys}).strict()}).strict(),_d=X.enum(["claim_disabled","unavailable","inactive","outside_window","not_targeted","not_first_purchase","limit_reached","sold_out"]);var Td=x.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),Xs=x.string().regex(/^(0|[1-9]\d{0,14})$/),Xr=x.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,30})?$/),Sy=x.string().regex(/^(?:[1-9]\d{0,7}|1\d{8}|200000000)$/),Bi=Sy,Un=Ae.refine(e=>/[1-9]/.test(e)),Vt=x.iso.datetime({offset:!0}),ta=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"))},Iy=x.array(x.object({upTo:Un.nullable(),unitAmountMinor:Td,flatAmountMinor:x.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&&ta(t.upTo)>ta(r))})}catch{return!1}},"Tier ceilings must increase and the final tier must be unbounded"),vy=x.discriminatedUnion("kind",[x.object({kind:x.literal("flat"),units:Un,unitAmountMinor:Td}).strict(),x.object({kind:x.enum(["graduated","volume"]),units:Un,tiers:Iy}).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"),wy=x.strictObject({interval:x.enum(["month","year"]),count:x.number().int().min(1).max(12),anchor:x.enum(["membership","calendar"])}),Vi=x.object({currency:be,pricing:vy,billingCycle:wy.optional()}).strict().refine(e=>e.pricing.kind!=="volume"||e.pricing.tiers.length===1,"Multiple volume tiers require prepaid billing");var Ed={requestId:x.uuid(),productVersionId:x.uuid(),internal_feature_id:x.uuid(),currency:be},Nd=x.strictObject({interval:x.enum(["hour","day","week","month"]),intervalCount:x.number().int().min(1).max(12),limit:x.number().int().min(1).max(1e6)}),Dd=x.discriminatedUnion("kind",[x.object({...Ed,kind:x.literal("auto_topup"),threshold:Uo,quantity:Un.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Nd.optional()}).strict(),x.object({...Ed,kind:x.literal("postpaid"),maxAmountMinorPerPeriod:Bi,maxOutstandingMinor:Bi}).strict()]),Rd={productVersionId:x.uuid(),internal_feature_id:x.uuid(),currency:be},Fd=x.discriminatedUnion("kind",[x.object({...Rd,kind:x.literal("auto_topup"),threshold:Uo,quantity:Un.refine(e=>Number(e)>=1,"AutoTopup quantity must be at least 1"),purchaseLimit:Nd.optional(),purchaseAmountMinor:Bi,purchaseUnits:Un}).strict(),x.object({...Rd,kind:x.literal("postpaid"),maxAmountMinorPerPeriod:Bi,maxOutstandingMinor:Bi,cashPrice:Vi}).strict().refine(e=>e.cashPrice.currency===e.currency,"Currency must match")]),na=x.object({id:x.uuid(),terms:Fd,status:x.enum(["prepared","active","revoked","blocked"]),createdAt:Vt,acceptedAt:Vt.nullable(),effectiveAt:Vt.nullable(),revokedAt:Vt.nullable()}).strict().refine(e=>(e.status==="prepared"?e.acceptedAt===null:!0)&&(e.status==="active"?e.acceptedAt!==null&&e.effectiveAt!==null:!0)&&(e.status==="revoked"?e.revokedAt!==null:e.revokedAt===null),"Authorization consent and revocation must be explicit"),Md=x.object({authorizationId:x.uuid(),terms:Fd,setupUrl:x.url().nullable()}).strict(),qd=x.object({authorizationId:x.uuid(),accepted:x.literal(!0)}).strict(),Bd=x.object({authorizationId:x.uuid(),requestId:x.uuid()}).strict(),Vd=x.object({internal_feature_id:x.uuid(),entityId:x.uuid().nullable(),interval:x.enum(["day","week","month","year"]),anchor:x.enum(["billing_cycle","utc"]).optional(),basis:x.enum(["usage","credits"]),filter:bt.optional(),limit:Ae.nullable(),thresholds:x.array(x.number().positive().max(1)).max(8),includedThresholds:x.array(x.number().positive().max(1)).max(8).optional(),absoluteThresholds:x.array(Un).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&&ta(t)>ta(i)}),"Notification thresholds must increase"),Oy=Vd.safeExtend({requestId:x.uuid()}),kd={control:x.literal("overage"),requestId:x.uuid(),internal_feature_id:x.uuid(),entityId:x.uuid().nullable()},Py=x.discriminatedUnion("action",[x.strictObject({...kd,action:x.literal("set"),allowed:x.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:x.boolean()}),x.strictObject({...kd,action:x.literal("remove")})]),Ld=x.union([Oy,Py]),Cy=x.strictObject({internal_feature_id:x.uuid(),entityId:x.uuid().nullable(),allowed:x.boolean().nullable(),overageLimit:Ae.nullable(),skipOverageBilling:x.boolean(),interval:x.enum(["day","week","month","year"]),startsAt:Vt,endsAt:Vt,used:x.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),reserved:x.string().regex(/^(0|[1-9]\d{0,23})(\.\d{1,6})?$/),remaining:x.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,6})?$/).nullable()}),_y=x.object({internal_feature_id:x.uuid(),entityId:x.uuid().nullable(),interval:x.enum(["day","week","month","year"]),anchor:x.enum(["billing_cycle","utc"]).optional(),basis:x.enum(["usage","credits"]),filter:bt.optional(),startsAt:Vt,endsAt:Vt,used:Qt,reserved:Qt,limit:Ae.nullable(),thresholds:x.array(x.number().positive().max(1)).max(8),notifiedThresholds:x.array(x.number().positive().max(1)).max(1024),includedThresholds:x.array(x.number().positive().max(1)).max(8).optional(),includedAllowance:x.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/).optional(),notifiedIncludedThresholds:x.array(x.number().positive().max(1)).max(1024).optional(),absoluteThresholds:x.array(Un).max(8).optional(),notifiedAbsoluteThresholds:x.array(Un).max(1024).optional()}).strict().refine(e=>e.basis!=="usage"||Ae.safeParse(e.used).success&&Ae.safeParse(e.reserved).success,"Usage counters retain six decimals; credit costs retain twelve"),Ey=x.object({authorizationId:x.uuid(),status:x.enum(["idle","pending","blocked"]),taskId:x.uuid().nullable(),invoiceId:x.uuid().nullable(),hostedInvoiceUrl:x.url().nullable(),purchaseCount:x.number().int().nonnegative(),purchaseWindowEndsAt:Vt.nullable(),attemptCount:x.number().int().nonnegative(),failedAttemptCount:x.number().int().nonnegative(),suspendedAt:Vt.nullable(),nextAttemptAt:Vt.nullable(),failureReason:x.string().min(1).max(240).nullable()}).strict(),Ud=x.object({internal_feature_id:x.uuid().optional(),entityId:x.uuid().optional()}).strict(),ec=x.object({authorizations:x.array(na).max(100),limits:x.array(Vd).max(100),overages:x.array(Cy).max(100).optional(),windows:x.array(_y).max(200),autoTopups:x.array(Ey).max(100),limited:x.boolean()}).strict(),Ry=x.object({id:x.uuid(),internal_feature_id:x.uuid(),productVersionId:x.uuid(),authorizationId:x.uuid(),entityId:x.uuid().nullable(),units:Ae,amountMinor:Xr,cashPrice:Vi}).strict(),Li=x.object({id:x.uuid(),sourceKind:x.enum(["product","usage","manual"]),providerInvoiceId:x.string().min(1).max(240).nullable(),status:x.enum(["accruing","open","pending","paid","failed","void"]),currency:be,startsAt:Vt.nullable(),endsAt:Vt.nullable(),amountMinor:x.string().regex(/^-?(0|[1-9]\d{0,14})$/),grossAmountMinor:x.string().regex(/^-?(0|[1-9]\d{0,14})$/),discountMinor:Xs,paidAmountMinor:Xs,refundedAmountMinor:Xs,createdAt:Vt,hostedInvoiceUrl:x.url().nullable(),adjustment:x.object({originalInvoiceId:x.uuid(),amountMinor:x.string().regex(/^-?(0|[1-9]\d{0,8})$/).refine(e=>e!=="-0"&&/^-?(0|[1-9]\d{0,8})$/.test(e)&&BigInt(e)>=-200000000n&&BigInt(e)<=200000000n,"Invoice adjustment exceeds the bounded minor amount"),acceptedAt:Vt.nullable(),reason:x.string().min(1).max(500).optional()}).strict().nullable(),lines:x.array(Ry).max(100),linesLimited:x.boolean()}).strict(),zd=x.object({invoiceId:x.uuid(),accepted:x.literal(!0)}).strict(),$d=x.strictObject({requestId:x.uuid(),originalInvoiceId:x.uuid(),amountMinor:x.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:x.string().trim().min(1).max(500)}),Gd=x.object({after:x.uuid().nullable(),limit:x.number().int().min(1).max(100)}).strict(),Kd=x.object({rows:x.array(Li).max(100),nextCursor:x.uuid().nullable()}).strict(),jd=x.strictObject({id:x.string(),coupon:x.string(),start:x.number().nonnegative(),end:x.number().nullable()}),ky=x.strictObject({subscriptionId:x.string(),customerId:x.string(),accountId:x.string(),sourceItems:x.array(x.strictObject({id:x.string(),price_id:x.string(),quantity:x.number().int(),discounts:x.array(jd).optional()})).max(100),items:x.array(x.strictObject({id:x.string(),price:x.string(),quantity:x.number().int(),discounts:x.array(x.strictObject({coupon:x.string().optional(),terms:x.strictObject({id:x.string(),name:x.string().optional(),percent_off:x.number().optional(),amount_off:x.number().optional(),currency:x.string().optional(),duration:x.enum(["once","forever","repeating"]),duration_in_months:x.number().optional()}).optional(),discount:x.string().optional(),receipt:jd.optional()})).max(20)})).max(100)}),Hd=x.strictObject({membershipId:x.uuid(),requestId:x.uuid(),grantIds:x.array(x.uuid()).max(20).refine(e=>new Set(e).size===e.length,"Duplicate Coupon grants")}),Qd=x.strictObject({membershipId:x.uuid(),operationId:x.uuid(),status:x.enum(["pending","effective"]),execution:ky.nullable(),grants:x.array(x.strictObject({id:x.uuid(),couponId:x.uuid(),name:x.string(),discount:Wn,duration:nn,startedAt:Vt.nullable()})).max(20)});import{z as Ui}from"zod";var Jd=Ui.enum(["minute","hour","day","week","month","quarter","semi_annual","year","lifetime"]),Zd=Ui.number().int().min(1).max(1e3),ra=Ui.object({cap:Ae.refine(e=>/[1-9]/.test(e)).nullable(),capPercentage:Ui.number().positive().max(1e4).nullable(),cycles:Ui.number().int().min(1).max(1200).nullable()}).strict().refine(e=>e.cap===null||e.capPercentage===null,"Choose a fixed or percentage cap");import{z as Yn}from"zod";var Wd=Yn.strictObject({itemKey:Yn.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:Yn.uuid(),includedAmount:Yn.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),quantity:Yn.number().int().min(0).max(1e4),terms:$o,pricing:Ni.optional(),unitAmountMinor:Yn.number().int().min(0).max(1e8),productId:Yn.string().min(1).max(255).nullable(),priceId:Yn.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{zl(e.includedAmount,e.terms.units,e.quantity),zo({quantity:e.quantity,unitAmountMinor:e.unitAmountMinor,...e.pricing===void 0?{}:{pricing:e.pricing}})}catch{t.addIssue({code:"custom",message:"Purchased allowance exceeds the ledger quantity limit"})}});import{z as ee}from"zod";var Ir=Ae.refine(e=>/[1-9]/.test(e),"Quantity must be positive"),zi=ee.string().min(1).max(120),ia=ee.enum(["cap","overflow"]),rn=(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"))},$i=e=>{try{return e()}catch{return!1}},Gi=ee.discriminatedUnion("operation",[ee.object({operation:ee.literal("quote"),overageBehavior:ia.optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:Ir,properties:bt}).strict(),ee.object({operation:ee.literal("consume"),overageBehavior:ia.optional(),occurredAt:ee.iso.datetime({offset:!0}).optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:Ae,properties:bt,idempotencyKey:zi}).strict(),ee.object({operation:ee.literal("reserve"),occurredAt:ee.iso.datetime({offset:!0}).optional(),internal_feature_id:ee.uuid(),entityId:ee.uuid().optional(),quantity:Ir,properties:bt,idempotencyKey:zi,expiresInSeconds:ee.number().int().min(1).max(86400)}).strict(),ee.object({operation:ee.literal("confirm"),operationId:ee.uuid(),quantity:Ir,properties:bt.optional(),idempotencyKey:zi}).strict(),ee.object({operation:ee.literal("refund"),operationId:ee.uuid(),quantity:Ir,idempotencyKey:zi}).strict(),ee.object({operation:ee.literal("release"),operationId:ee.uuid(),idempotencyKey:zi}).strict()]),tc=ee.object({internal_credit_feature_id:ee.uuid().nullable(),internal_metered_feature_id:ee.uuid(),dimension:ee.string().min(1).max(64),counterKey:ee.string().min(1).max(240),cycleStart:ee.iso.datetime({offset:!0}),unitCost:Ae,units:Ir,amount:Qt,tier:ee.number().int().min(1).max(12).nullable()}).strict(),vr=ee.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/);function Yd(e,t){let n=e.reduce((r,i)=>r+rn(i.units,12),0n)-rn(t,12);return e.some(r=>r.funding==="balance")?n>=-100n&&n<=100n:n===0n}var Xd=ee.discriminatedUnion("funding",[ee.strictObject({funding:ee.literal("balance"),sourceId:ee.uuid(),rolloverId:ee.uuid().nullable(),units:vr.refine(e=>/[1-9]/.test(e)),amount:Qt}),ee.strictObject({funding:ee.literal("unbilled"),units:vr.refine(e=>/[1-9]/.test(e))}),ee.object({funding:ee.literal("prepaid"),sourceId:ee.uuid(),units:Ir,amount:Qt,pricing:ee.array(tc).min(1).max(12)}).strict().refine(e=>$i(()=>e.pricing.reduce((t,n)=>t+rn(n.units,6),0n)===rn(e.units,6)&&e.pricing.reduce((t,n)=>t+rn(n.amount,12),0n)===rn(e.amount,12)&&e.pricing.every(t=>rn(t.unitCost,6)*rn(t.units,6)===rn(t.amount,12))),"Frozen pricing must conserve allocated units and amounts"),ee.object({funding:ee.literal("postpaid"),invoiceLineId:ee.uuid().nullable(),units:Ir,authorizationId:ee.uuid()}).strict()]),oa=ee.enum(["unavailable","insufficient_balance","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded"]),ep=ee.object({allowed:ee.boolean(),internal_feature_id:ee.uuid(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ia.optional(),reason:oa.nullable(),allocations:ee.array(Xd).max(500)}).strict().refine(e=>$i(()=>e.allowed?e.reason===null&&Yd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"A quote must conserve its accepted units").refine(e=>$i(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0&&/[1-9]/.test(e.quantity):e.requestedQuantity!==void 0&&rn(e.requestedQuantity,6)>=rn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Explicit overage behavior must retain the requested quantity"),Ki=ee.object({id:ee.uuid(),internal_feature_id:ee.uuid(),kind:ee.enum(["consume","reserve","confirm","refund","release","expire"]),originalId:ee.uuid().nullable(),quantity:Ae,requestedQuantity:Ae.optional(),overageBehavior:ia.optional(),accepted:ee.boolean(),reason:ee.enum([...oa.options,"expired"]).nullable(),createdAt:ee.iso.datetime({offset:!0}),reservationStatus:ee.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:ee.iso.datetime({offset:!0}).nullable(),allocations:ee.array(Xd).max(500)}).strict().refine(e=>$i(()=>e.accepted?e.reason===null&&Yd(e.allocations,e.quantity):e.reason!==null&&e.allocations.length===0),"An operation must conserve its requested units").refine(e=>$i(()=>e.overageBehavior===void 0?e.requestedQuantity===void 0:e.kind==="consume"&&e.requestedQuantity!==void 0&&rn(e.requestedQuantity,6)>=rn(e.quantity,6)&&(e.overageBehavior==="cap"||e.requestedQuantity===e.quantity)),"Overage metadata belongs to consumption and preserves requested units").refine(e=>/[1-9]/.test(e.quantity)||e.kind==="consume","Only consumption can record a zero cost event").refine(e=>e.allocations.every(t=>t.funding!=="postpaid"||t.invoiceLineId!==null),"Accepted operations must reference persisted invoice lines").refine(e=>e.originalId!==null===["confirm","refund","release","expire"].includes(e.kind)&&e.expiresAt!==null==(e.reservationStatus!==null)&&(e.kind!=="reserve"||!e.accepted||e.reservationStatus!==null),"Operation provenance and reservation state must be explicit");import{z as Te}from"zod";var wr=Te.iso.datetime({offset:!0}),tp=Ae.refine(e=>/[1-9]/.test(e)),np=Te.strictObject({interval:Jd.exclude(["lifetime"]),count:Zd}),jy=Te.strictObject({action:Te.literal("create"),requestId:Te.uuid(),internal_feature_id:Te.uuid(),entityId:Te.uuid().nullable(),amount:tp.nullable(),expiresAt:wr.nullable(),reset:np.nullable(),rollover:ra.nullable(),nextResetAt:wr.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"),rp=Te.discriminatedUnion("action",[jy,Te.strictObject({action:Te.literal("update"),requestId:Te.uuid(),grantId:Te.uuid(),revision:Te.number().int().nonnegative(),amount:tp.nullable(),expiresAt:wr.nullable(),rollover:ra.nullable(),nextResetAt:wr.nullable()}),Te.strictObject({action:Te.enum(["add","subtract","set_remaining"]),requestId:Te.uuid(),grantId:Te.uuid(),revision:Te.number().int().nonnegative(),amount:Ae}),Te.strictObject({action:Te.literal("revoke"),requestId:Te.uuid(),grantId:Te.uuid(),revision:Te.number().int().nonnegative()})]),nc=Te.strictObject({id:Te.uuid(),internal_feature_id:Te.uuid(),entityId:Te.uuid().nullable(),amount:Ae.nullable(),reset:np.nullable(),rollover:ra.nullable(),nextResetAt:wr.nullable(),startsAt:wr,expiresAt:wr.nullable(),revision:Te.number().int().nonnegative(),revoked:Te.boolean(),available:Qt,held:Qt,spent:Qt}),ip=Te.strictObject({customerId:Te.uuid(),after:Te.uuid().nullable(),limit:Te.number().int().min(1).max(100)}),op=Te.strictObject({rows:Te.array(nc).max(100),nextCursor:Te.uuid().nullable()});import{z as ne}from"zod";var En=ne.iso.datetime({offset:!0}),ap=ne.strictObject({invoiceId:ne.uuid(),after:ne.string().min(1).max(180).nullable(),limit:ne.number().int().min(1).max(100)}),Ty=ne.strictObject({kind:ne.literal("product"),key:ne.string(),productVersionId:ne.uuid(),productName:ne.string(),itemKey:ne.string(),entityId:ne.uuid().nullable(),quantity:ne.number().positive(),subtotalMinor:ne.string().regex(/^-?\d+$/),discountMinor:ne.string().regex(/^\d+$/),taxMinor:ne.string().regex(/^-?\d+$/).nullable(),totalMinor:ne.string().regex(/^-?\d+$/),startsAt:En.nullable(),endsAt:En.nullable(),providerLineId:ne.string().nullable(),providerItemId:ne.string()}),sp=ne.strictObject({invoice:Li,items:ne.array(ne.discriminatedUnion("kind",[Ty,ne.strictObject({kind:ne.literal("invoice_credit"),key:ne.string(),internal_feature_id:ne.uuid(),internal_credit_feature_id:ne.uuid(),name:ne.string(),units:Ae,reserved:Ae,amountMinor:Xr,grossAmountMinor:Xr,creditsAppliedMinor:Xr,properties:bt,cashPrice:Vi,providerItemId:ne.string().nullable(),creditProviderItemId:ne.string().nullable()}),ne.strictObject({kind:ne.literal("usage"),key:ne.string(),internal_feature_id:ne.uuid(),name:ne.string(),units:Ae,reserved:Ae,amountMinor:Xr,cashPrice:Vi})])).max(100),nextCursor:ne.string().min(1).max(180).nullable()}),Ny=ne.string().regex(/^-?(0|[1-9]\d{0,17})(\.\d{1,12})?$/).refine(e=>!/^\-0(?:\.0+)?$/.test(e)),rc=ne.strictObject({from:En,to:En,entityId:ne.uuid().optional(),snapshotAt:En.nullable(),after:ne.strictObject({at:En,id:ne.uuid(),position:ne.number().int().nonnegative()}).nullable(),limit:ne.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"),cp=ne.strictObject({customerId:ne.uuid(),entityId:ne.uuid().nullable(),from:En,to:En,snapshotAt:En,totals:ne.array(ne.strictObject({internal_credit_feature_id:ne.uuid(),name:ne.string(),consumed:Qt,refunded:Qt,net:Ny})).max(1e3),rows:ne.array(ne.strictObject({operationId:ne.uuid(),position:ne.number().int().nonnegative(),kind:ne.enum(["consume","confirm","refund"]),originalId:ne.uuid().nullable(),occurredAt:En,internal_feature_id:ne.uuid(),entitlementName:ne.string(),sourceId:ne.uuid(),internal_credit_feature_id:ne.uuid(),creditName:ne.string(),units:vr,amount:Qt,pricing:ne.array(tc).max(12),properties:bt})).max(100),nextCursor:rc.shape.after});import{z as D}from"zod";import{z as bn}from"zod";var Dy=bn.string().max(40).regex(/^(0|[1-9]\d*)(\.\d{1,12})?$/),Fy=bn.string().max(41).regex(/^-?(0|[1-9]\d*)(\.\d{1,12})?$/),aa=bn.strictObject({internal_feature_id:bn.uuid(),entityId:bn.uuid().nullable()}),up=aa.extend({quantity:Ae,expectedRevision:bn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),idempotencyKey:bn.string().min(1).max(120),properties:bt.refine(e=>Object.keys(e).length<=13&&!Object.keys(e).some(t=>t.startsWith("usage_")),"Usage accounting reserves three properties")}).strict(),Hi=aa.extend({operationId:bn.uuid().nullable(),usage:Ae,capacity:Dy.nullable(),remaining:Fy.nullable(),withinLimit:bn.boolean(),revision:bn.number().int().min(0).max(Number.MAX_SAFE_INTEGER),updatedAt:bn.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 Lt=D.string().regex(/^(0|[1-9]\d{0,17})(\.\d{1,12})?$/),xn=D.iso.datetime({offset:!0}),My=D.enum(["access","metered","credit"]),Qi={internal_feature_id:D.uuid(),key:xr,name:D.string().min(1).max(120),kind:My},lp=D.object({customerId:D.uuid(),snapshotAt:xn,memberships:D.array(D.object({id:D.uuid(),productId:D.string().min(1).max(255),productVersionId:D.uuid(),billingProductVersionId:D.uuid(),version:D.number().int().positive(),key:D.string().min(1).max(64),name:D.string().min(1).max(120),groupId:D.string().max(255).nullable(),membershipType:D.enum(["main","addon"]),status:D.enum(["trial","active","past_due","ended","expired","trialing","paused","pending","scheduled","unknown"]),cancelAtPeriodEnd:D.boolean(),accessEnabled:D.boolean(),renewalChange:D.object({productVersionId:D.uuid(),name:D.string().min(1).max(120),version:D.number().int().positive(),effectiveAt:xn,benefitsAppliedAt:xn.nullable(),timing:D.enum(["immediate","renewal"]),changeKind:D.enum(["plan","seats","quantity"]),feature:D.strictObject({internal_feature_id:D.uuid(),name:D.string().min(1).max(80),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).optional(),seat:D.object({key:D.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),fromQuantity:D.number().int().min(0).max(1e4),toQuantity:D.number().int().min(0).max(1e4)}).strict().nullable(),status:D.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:D.object({phase:D.enum(["paid","trial"]),startsAt:xn,endsAt:xn.nullable()}).strict().nullable()}).strict()).max(100),membershipsLimited:D.boolean(),balances:D.array(D.object({...Qi,usageType:D.enum(["consumable","non_consumable"]).nullable(),accessible:D.boolean(),unlimited:D.boolean(),available:Lt,held:Lt,debt:Lt,nextExpiresAt:xn.nullable(),usage:Hi.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:D.boolean()}).strict(),dp=D.enum(["source","usage","transaction","invoice","debt","settlement"]),sa=D.object({at:xn,id:D.uuid(),type:dp}).strict(),pp=D.object({type:dp.nullable(),resourceKey:xr.optional(),kind:D.enum(["purchase","refund"]).optional(),topup:D.boolean().optional(),from:D.iso.date().nullable(),to:D.iso.date().nullable(),after:sa.nullable(),limit:D.number().int().min(1).max(50)}).strict().refine(e=>!e.from||!e.to||e.from<=e.to,"Date range is reversed"),ei={id:D.uuid(),occurredAt:xn},qy=D.discriminatedUnion("type",[D.strictObject({...ei,type:D.literal("invoice"),status:D.string().min(1).max(80),paid:Lt,refunded:Lt,currency:be,externalId:D.string().nullable()}),D.object({...ei,...Qi,type:D.literal("source"),reason:D.enum(["membership","trial","topup","manual","rollover","upgrade_carry","seat"]),quantity:Lt,unlimited:D.boolean(),status:D.enum(["scheduled","active","expired","revoked","unavailable"]),startsAt:xn,expiresAt:xn.nullable(),orderId:D.uuid().nullable(),parentSourceId:D.uuid().nullable()}).strict(),D.object({...ei,type:D.literal("usage"),internal_feature_id:D.uuid(),name:D.string().min(1).max(120),kind:D.enum(["consume","set_usage","reserve","confirm","refund","release","expire"]),originalId:D.uuid().nullable(),quantity:Ae,accepted:D.boolean(),reason:D.enum([...oa.options,"expired"]).nullable(),properties:bt,reservationStatus:D.enum(["pending","confirmed","released","expired"]).nullable(),expiresAt:xn.nullable(),charges:D.array(D.discriminatedUnion("funding",[D.strictObject({funding:D.literal("balance"),sourceId:D.uuid(),rolloverId:D.uuid().nullable(),units:vr,amount:Lt}),D.strictObject({funding:D.literal("unbilled"),units:vr}),D.object({...Qi,funding:D.literal("prepaid"),amount:Lt}).strict(),D.object({funding:D.literal("postpaid"),invoiceId:D.uuid(),invoiceLineId:D.uuid(),authorizationId:D.uuid(),units:Ae,currency:be}).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"),D.object({...ei,type:D.literal("transaction"),purpose:D.enum(["product","invoice"]),productVersionId:D.uuid().nullable(),productName:D.string().min(1).max(120).nullable(),productVersion:D.number().int().positive().nullable(),invoiceId:D.uuid().nullable(),orderId:D.uuid(),originalId:D.uuid().nullable(),kind:D.enum(["purchase","refund"]),amountMinor:D.number().int().nonnegative().max(2e8).nullable(),currency:be.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"),D.object({...ei,...Qi,type:D.literal("debt"),sourceId:D.uuid(),transactionId:D.uuid(),amount:Lt}).strict(),D.object({...ei,...Qi,type:D.literal("settlement"),sourceId:D.uuid(),debtId:D.uuid(),kind:D.enum(["payment","usage_refund","payment_return"]),amount:Lt}).strict()]),mp=D.object({customerId:D.uuid(),rows:D.array(qy).max(50),nextCursor:sa.nullable()}).strict().refine(e=>new Set(e.rows.map(t=>t.type+t.id)).size===e.rows.length,"A page cannot repeat a fact").refine(e=>{let t=e.rows.at(-1);return!e.nextCursor||!!(t&&t.id===e.nextCursor.id&&t.type===e.nextCursor.type&&t.occurredAt===e.nextCursor.at)},"Cursor must name the final displayed fact");import{z as pe}from"zod";var gp=pe.object({customerId:pe.uuid()}).strict(),hp=pe.discriminatedUnion("action",[pe.object({customerId:pe.uuid(),requestId:pe.uuid(),action:pe.literal("assign"),poolId:pe.uuid(),memberCustomerId:pe.uuid()}).strict(),pe.strictObject({customerId:pe.uuid(),requestId:pe.uuid(),action:pe.literal("assign_entity"),poolId:pe.uuid(),entityId:pe.uuid()}),pe.object({customerId:pe.uuid(),requestId:pe.uuid(),action:pe.literal("release"),poolId:pe.uuid(),slotId:pe.uuid()}).strict()]),Ji=pe.number().int().nonnegative(),ic=pe.iso.datetime({offset:!0}),oc=pe.strictObject({internalId:pe.uuid(),id:pe.string(),name:pe.string().nullable(),version:pe.number().int().positive()}),fp=pe.enum(["active","past_due"]),ac=pe.strictObject({customerId:pe.uuid(),licenses:pe.array(pe.strictObject({id:pe.uuid(),linkId:pe.uuid(),parent:pe.strictObject({customerProductId:pe.uuid(),status:fp,product:oc}),product:oc,planLicense:pe.strictObject({id:pe.uuid(),prepaidOnly:pe.boolean(),isCustom:pe.boolean()}).nullable(),granted:Ji,included:Ji,paidQuantity:Ji,usage:Ji,remaining:Ji,createdAt:ic}).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:pe.array(pe.strictObject({id:pe.uuid(),linkId:pe.uuid(),status:fp,product:oc,entity:pe.strictObject({internalId:pe.uuid(),id:pe.string().nullable(),name:pe.string().nullable()}).nullable(),beneficiary:pe.strictObject({internalId:pe.uuid(),id:pe.string().nullable(),name:pe.string().nullable()}).nullable(),startedAt:ic.nullable(),endedAt:ic.nullable()}).refine(e=>e.entity!==null||e.beneficiary!==null,"A seat assignment has a holder")).max(1e4),limited:pe.boolean()});import{z as de}from"zod";var Zi=de.enum(["email","sms","voice","push"]),BO=de.enum(["resend","twilio","fcm","apns"]);var VO=de.string().regex(/^\+[1-9]\d{1,14}$/),By=de.enum(["email_recipient","sms_segment","voice_second","push_device"]);var Vy=de.string().trim().min(1).max(200).refine(e=>!/[\r\n\0]/.test(e),"Invalid email header"),Ly=de.strictObject({subject:Vy,html:de.string().min(1).max(131072).optional(),text:de.string().min(1).max(65536).optional()}).refine(e=>e.html!==void 0||e.text!==void 0,{message:"Email requires HTML or text content"}),Uy=de.strictObject({body:de.string().min(1).max(1600).refine(e=>e.trim().length>0)}),zy=de.strictObject({text:de.string().trim().min(1).max(4e3),language:de.string().regex(/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/).max(35),maxDurationSeconds:de.number().int().min(1).max(900)}),$y=de.record(de.string().min(1).max(64),de.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"),Gy=de.strictObject({title:de.string().trim().min(1).max(200),body:de.string().trim().min(1).max(2e3),url:de.url().max(2048).refine(e=>!/^(?:javascript|data|file|vbscript):/i.test(e)).optional(),data:$y.optional()}).refine(e=>new TextEncoder().encode(JSON.stringify(e)).length<=3072,"Push content exceeds the provider payload budget"),Ap=de.discriminatedUnion("channel",[de.strictObject({channel:de.literal("email"),content:Ly}),de.strictObject({channel:de.literal("sms"),content:Uy}),de.strictObject({channel:de.literal("voice"),content:zy}),de.strictObject({channel:de.literal("push"),content:Gy})]),yp=de.strictObject({requestId:de.uuid(),customerId:de.uuid(),connectionId:de.uuid().optional(),message:Ap,expiresAt:de.iso.datetime({offset:!0})}),Ky=de.array(de.uuid()).min(1).max(1e4).refine(e=>new Set(e).size===e.length,"Duplicate Customer"),Hy=de.discriminatedUnion("kind",[de.strictObject({kind:de.literal("all")}),de.strictObject({kind:de.literal("customers"),customerIds:Ky})]),LO=de.strictObject({name:de.string().trim().min(1).max(120),connectionId:de.uuid().optional(),message:Ap,audience:Hy,frequencyLimit:de.number().int().min(1).max(100)}),bp=de.strictObject({requestId:de.uuid(),channel:Zi,state:de.enum(["allowed","denied"]),expectedRevision:de.number().int().min(0).max(Number.MAX_SAFE_INTEGER-1)}),xp=de.enum(["queued","leased","dispatching","accepted","unknown","retry","skipped","failed","canceled"]),Sp=de.enum(["accepted","sent","delivered","delayed","bounced","complained","unsubscribed","opened","clicked","ringing","answered","completed","busy","no_answer","failed","cost_finalized"]),UO=de.strictObject({meter:By,estimatedUnits:de.string().regex(/^(0|[1-9]\d{0,11})$/),observedUnits:de.string().regex(/^(0|[1-9]\d{0,11})$/).nullable()});import{z as Pe}from"zod";import{z as te}from"zod";import{z as ti}from"zod";var Wi=ti.strictObject({internalFeatureId:ti.uuid(),name:ti.string().min(1).max(120),includedAmount:ti.string().regex(/^(0|[1-9]\d{0,11})(\.\d{1,6})?$/),reset:ti.enum(["hour","day","week","month","year","lifetime"]),resetCount:ti.number().int().min(1).max(100),terms:$o});import{z as ot}from"zod";import{z as Qy}from"zod";import{z as ni}from"zod";var Ip=ni.enum(["stripe","apple","google","merchant"]),vp=ni.enum(["membership","credit_pack","lifetime"]),QO=ni.enum(["active","grace","suspended","inactive","revoked"]),JO=ni.strictObject({currency:ni.string().regex(/^[A-Z]{3}$/),micros:ni.string().regex(/^(0|[1-9][0-9]{0,29})$/)});var ri=Qy.object({provider:Ip,currency:be}).strict();var Xn=ot.strictObject({internal_feature_id:ot.uuid(),quantity:Ae.refine(e=>/[1-9]/.test(e)),properties:bt,entityId:ot.uuid().optional()}),wp=ot.strictObject({requirement:Xn,commerce:ri.optional(),paywallId:ot.uuid().optional()}),Jy=ot.enum(["not_entitled","insufficient_balance","capacity_exceeded","limit_exceeded","awaiting_topup","authorization_required","payment_blocked","cash_budget_exceeded","unavailable","authentication_required"]),sc=ot.strictObject({productId:ot.string().min(1),productVersionId:ot.string().min(1),name:ot.string().min(1).max(120),action:ot.enum(["purchase","upgrade","addon","topup"]),membershipId:ot.string().min(1).nullable(),currency:be,amountMinor:ot.string().regex(/^(0|[1-9]\d{0,8})$/),interval:ot.enum(["free","week","month","year","one_time"]),intervalCount:ot.number().int().min(1).max(156)}),Or=ot.strictObject({internal_feature_id:ot.string().min(1),name:ot.string().min(1).max(120),kind:ot.enum(["access","metered","credit"]),quantity:Ae,allowed:ot.boolean(),reason:Jy.nullable(),preview:ot.strictObject({scenario:ot.enum(["feature_flag","usage_limit"]),candidates:ot.array(sc).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"})}),oP=ot.strictObject({paywallId:ot.uuid(),requirement:Xn});var ua=te.object({plan:te.string().min(1).max(200).optional(),coupon:te.uuid().optional(),promotionCode:te.uuid().optional(),picker:te.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/).optional()}).strict(),ca=te.object({text:te.string().optional(),label:te.string().optional(),alt:te.string().optional(),html:te.string().max(32768).optional(),price:te.object({current:te.string(),original:te.string().nullable(),period:te.string()}).optional(),code:te.string().optional(),countdownAt:te.iso.datetime().optional(),planId:te.string().min(1).max(200).optional(),planVersionId:te.string().min(1).max(200).optional(),currency:be.optional(),couponId:te.uuid().optional(),offerId:te.uuid().optional(),unavailable:te.boolean().optional(),unavailableReason:te.string().optional(),missing:te.array(te.string()).optional()}).strict(),ii=te.object({paywall:Or.optional(),nodes:te.record(te.string(),te.object({base:ca,picker:te.string().optional(),byPlan:te.record(te.string(),ca).optional()}).strict()),plans:te.record(te.string(),te.object({id:te.string().min(1).max(200),versionId:te.string().min(1).max(200),available:te.boolean(),name:te.string(),price:te.string(),period:te.string(),currency:be.optional(),amountMinor:te.number().int().nonnegative().optional(),interval:te.enum(["free","week","month","year","one_time"]).optional(),intervalCount:te.number().int().positive().optional(),prepaid:te.array(Wi).max(100).optional()}).strict()),pickers:te.record(te.string(),te.object({options:te.array(te.string().min(1).max(200)).max(20),selected:te.string().min(1).max(200).nullable()}).strict()),quantities:te.record(te.string(),te.strictObject({minimum:te.number().int().nonnegative(),maximum:te.number().int().nonnegative(),step:te.number().int().positive(),value:te.number().int().nonnegative(),label:te.string(),available:te.boolean()})).optional(),diagnostics:te.array(te.object({nodeId:te.string(),message:te.string()}).strict())}).strict();function Op(e){return[...e.matchAll(/\{\{\s*([^{}]+?)\s*\}\}/g)].flatMap(t=>t[1]===void 0?[]:[t[1].trim()])}import{z as S}from"zod";function Zy(e){return e.type==="stack"&&e.interaction?.type==="select"&&e.interaction.purpose==="product"&&!!e.interaction.pickerId}function Pp(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}import{z as zn}from"zod";var Cp=zn.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),la=zn.strictObject({tiers:zn.array(zn.strictObject({id:Cp,name:zn.string().trim().min(1).max(80)})).min(1).max(8),assignments:zn.array(zn.strictObject({productVersionId:zn.string().min(1).max(200),tierId:Cp,period:zn.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 da(e,t){return e.assignments.length===t.length&&e.assignments.every(n=>t.includes(n.productVersionId))}import{z as se}from"zod";var Wy=["credit_balance","credit_transactions","membership","billing","billing_controls","customer_plans","credit_packs","credit_pack_orders","offer_history"],_p=se.enum(Wy),Ep=se.object({source:_p,layout:se.enum(["full","compact"]),resourceKey:xr.optional(),pageSize:se.number().int().min(1).max(50),showSources:se.boolean(),allowPurchase:se.boolean(),outputs:se.object({billing_adjustment:se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_authorization:se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),buy_pack:se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),billing_portal:se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),cancel_membership:se.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/).optional(),resume_membership:se.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"})}),_t=se.string().max(2e3),Rp=se.object({id:se.string().max(100),label:_t,detail:se.array(_t).max(12),value:_t.optional(),status:_t.optional(),facts:se.array(se.object({label:_t,value:_t}).strict()).max(1e3),purchaseId:se.uuid().optional(),invoiceUrl:se.url().max(2048).refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}).optional(),billingActions:se.array(se.strictObject({action:se.literal("invoice_open"),label:_t})).max(1).optional(),membershipActions:se.array(se.object({value:se.string().max(100),label:_t}).strict()).max(3).optional()}).strict(),Yy=se.object({key:xr,name:_t,spendable:_t,reserved:_t,available:_t,expiry:_t.nullable(),sources:se.array(Rp).max(50),sourceCount:se.number().int().nonnegative(),sourcePage:se.number().int().positive(),hasNextSources:se.boolean(),hasPreviousSources:se.boolean()}).strict(),Xy=se.object({source:_p,status:se.enum(["idle","loading","ready","error"]),stale:se.boolean(),preview:se.boolean(),errorCode:se.string().max(80).optional(),errorMessage:_t.optional(),resources:se.array(Yy).max(500),rows:se.array(Rp).max(50),hasNext:se.boolean(),hasPrevious:se.boolean(),page:se.number().int().positive(),filter:se.string().max(40),updatedAt:se.iso.datetime().optional(),buyingId:se.uuid().optional(),membershipBusy:se.boolean().optional(),billingBusy:se.boolean().optional(),membershipReview:se.object({title:_t,note:_t,facts:se.array(se.object({label:_t,value:_t}).strict()).max(100)}).strict().optional(),membershipResult:_t.optional()}).strict(),kp=se.object({nodes:se.record(se.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Xy)}).strict(),AP=se.object({nodeId:se.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),action:se.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:se.string().max(100).optional()}).strict();var tb=4,In={nodes:150,depth:8,children:50,locales:20,actions:40,pages:10,stringLength:2e3,customHtml:32768,customCss:16384,documentBytes:2e5},Xi=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),Me=S.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),nb=S.enum(["none","xs","sm","md","lg","xl"]),rb=S.enum(["none","sm","md","lg","full"]),cc=S.string().regex(/^#[0-9a-fA-F]{6}$/),Np=S.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"),uc=S.union([Np,S.string().max(32768).regex(/^data:image\/svg\+xml;base64,[A-Za-z0-9+/]+={0,2}$/),S.string().max(131072).regex(/^data:image\/jpeg;base64,\/9j\/[A-Za-z0-9+/]+={0,2}$/),S.string().max(131072).regex(/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]+={0,2}$/)]),jp=S.object({primary:cc,background:cc,text:cc,radius:rb,font:S.enum(["system","serif","rounded","mono"])}).strict(),eo=S.union([S.enum(["primary","text","muted","background","surface"]),S.string().regex(/^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/)]),De=(e,t)=>S.number().int().min(e).max(t),Tp=S.union([S.enum(["fit","fill"]),De(1,1200)]),ib=S.object({top:De(0,200),right:De(0,200),bottom:De(0,200),left:De(0,200)}).strict(),ob=S.object({top:De(-100,200),right:De(-100,200),bottom:De(-100,200),left:De(-100,200)}).strict(),Dp=S.object({x:De(0,100),y:De(0,100)}).strict(),ab=S.discriminatedUnion("type",[S.object({type:S.literal("color"),color:eo}).strict(),S.object({type:S.literal("linear"),angle:De(0,360),stops:S.array(S.object({color:eo,at:De(0,100)}).strict()).min(2).max(4)}).strict(),S.object({type:S.literal("image"),src:uc,fit:S.enum(["cover","contain"]),position:Dp.optional()}).strict()]),sb=S.discriminatedUnion("type",[S.object({type:S.literal("rect"),radius:S.union([De(0,200),S.object({topLeft:De(0,200),topRight:De(0,200),bottomRight:De(0,200),bottomLeft:De(0,200)}).strict()])}).strict(),S.object({type:S.literal("pill")}).strict()]),cb=S.object({width:De(0,12),color:eo,style:S.enum(["solid","dashed"])}).strict(),ub=S.object({x:De(-40,40),y:De(-40,40),blur:De(0,80),spread:De(-20,40),color:eo}).strict(),lb=S.object({font:S.enum(["system","serif","rounded","mono"]),size:De(8,96),weight:S.number().int().min(100).max(900).multipleOf(100),lineHeight:S.number().min(.8).max(3),letterSpacing:S.number().min(-5).max(20),color:eo,align:S.enum(["start","center","end"]),italic:S.boolean(),decoration:S.enum(["none","underline","line-through"]),transform:S.enum(["none","uppercase"])}).strict().partial(),Pr=S.object({width:Tp,height:Tp,padding:ib,margin:ob,gap:De(0,120),grow:S.union([S.boolean(),S.number().min(0).max(12)]),background:ab,opacity:S.number().min(0).max(1),clipContent:S.boolean(),shape:sb,border:cb,shadow:ub,text:lb}).strict().partial(),Yt={id:Xi,name:S.string().trim().min(1).max(60).optional(),hidden:S.boolean().optional(),style:Pr.optional(),fallback:Me.optional()},db=S.object({...Yt,type:S.literal("text"),productField:S.enum(["name","price","trial","period"]).optional(),feature:S.object({id:S.uuid(),field:S.enum(["name","allowance"])}).strict().optional(),text:Me,variant:S.enum(["title","heading","body","caption"])}).strict(),pb=S.object({...Yt,type:S.literal("image"),src:uc,localizedSrc:S.record(yn,uc).optional(),alt:Me,aspect:S.enum(["auto","1:1","4:3","16:9","3:1"]),fit:S.enum(["cover","contain"]),position:Dp.optional()}).strict(),mb=S.object({...Yt,type:S.literal("button"),label:Me,variant:S.enum(["primary","secondary","link"]),action:Me,purpose:S.enum(["purchase","navigation","close"]).optional(),bind:ua.optional()}).strict(),fb=S.object({...Yt,type:S.literal("divider")}).strict(),gb=S.object({...Yt,type:S.literal("customer_data"),title:Me,data:Ep}).strict(),hb=S.object({...Yt,type:S.literal("spacer"),size:nb}).strict(),Ab=S.object({...Yt,type:S.literal("custom_html"),html:S.record(yn,S.string().max(In.customHtml)),css:S.string().max(In.customCss)}).strict(),yb=S.object({...Yt,type:S.literal("price"),fallback:Me,parts:S.object({current:Pr.optional(),original:Pr.optional(),period:Pr.optional()}).strict().optional()}).strict(),bb=S.object({...Yt,type:S.literal("coupon_code"),label:Me,fallback:Me}).strict(),xb=S.object({...Yt,type:S.literal("countdown"),source:S.enum(["offer.ends_at","offer.expires_at","fixed"]),at:S.iso.datetime().optional(),granularity:S.enum(["day","hour","minute","second"]),expired:Me,fallback:Me}).strict().refine(e=>e.source!=="fixed"||!!e.at,"\u56FA\u5B9A\u5012\u8BA1\u65F6\u9700\u8981\u7ED3\u675F\u65F6\u95F4"),Sb=S.object({...Yt,type:S.literal("plan_picker"),label:Me,fallback:Me,planIds:S.array(S.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:S.string().min(1).max(200).optional(),grouping:la.safeExtend({monthLabel:Me,yearLabel:Me,unavailableLabel:Me}).optional(),states:S.object({selected:Pr.optional()}).strict().optional()}).strict().superRefine((e,t)=>{e.grouping&&(!e.planIds||!da(e.grouping,e.planIds))&&t.addIssue({code:"custom",message:"Grouped picker assignments must match its product allowlist"})}),Ib=S.object({...Yt,type:S.literal("quantity_picker"),bind:ua.optional(),label:Me,fallback:Me,internalFeatureId:S.uuid(),minimumQuantity:De(0,1e4),maximumQuantity:De(0,1e4),defaultQuantity:De(0,1e4),step:De(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"),vb=S.discriminatedUnion("type",[S.object({type:S.literal("input"),label:Me,keyboard:S.enum(["text","email","tel","url"]),maxLength:De(1,500)}).strict(),S.object({type:S.literal("multiselect"),label:Me,min:De(0,50),max:De(1,50)}).strict(),S.object({type:S.literal("select"),label:Me,defaultIndex:De(0,49),purpose:S.enum(["option","product","tier"]).optional(),pickerId:Xi.optional(),selectedStyle:Pr.optional()}).strict(),S.object({type:S.literal("tabs"),label:Me,defaultIndex:De(0,49),purpose:S.literal("tier").optional()}).strict(),S.object({type:S.literal("toggle"),label:Me,defaultEnabled:S.boolean()}).strict(),S.object({type:S.literal("carousel"),label:Me}).strict()]),Sn={...Yt,type:S.literal("stack"),direction:S.enum(["vertical","horizontal","overlay"]),align:S.enum(["start","center","end","stretch"]),justify:S.enum(["start","center","end","between"]),productSlot:S.object({index:De(0,19),period:S.enum(["month","year"]).optional(),requireBinding:S.boolean().optional()}).strict().optional(),interaction:vb.optional(),states:S.object({selected:Pr.optional()}).strict().optional(),purpose:S.literal("benefits").optional(),purchaseAction:Me.optional(),buttonVariant:S.enum(["primary","secondary","link"]).optional(),bind:ua.optional()},Fp=S.lazy(()=>S.object({...Yt,type:Sn.type,direction:Sn.direction,align:Sn.align,justify:Sn.justify,children:S.array(wb).max(In.children),productSlot:Sn.productSlot,interaction:Sn.interaction,states:Sn.states,purpose:Sn.purpose,purchaseAction:Sn.purchaseAction,buttonVariant:Sn.buttonVariant,bind:Sn.bind}).strict()),wb=S.lazy(()=>S.union([Fp,db,pb,mb,fb,hb,Ab,yb,bb,xb,Sb,Ib,gb])),Ob=S.union([S.string().max(500),S.number().finite(),S.boolean(),S.null()]),Yi={id:Me,event:Me,properties:S.record(Me,Ob).refine(e=>Object.keys(e).length<=20,"\u6700\u591A 20 \u4E2A\u53C2\u6570")},Pb=S.discriminatedUnion("type",[S.object({...Yi,type:S.literal("navigate"),close:S.literal(!1),pageId:Xi}).strict(),S.object({...Yi,type:S.literal("event"),close:S.boolean()}).strict(),S.object({...Yi,type:S.literal("close"),close:S.literal(!0)}).strict(),S.object({...Yi,type:S.literal("open_url"),close:S.boolean(),url:Np}).strict(),S.object({...Yi,type:S.literal("claim_offer"),close:S.boolean(),couponId:S.uuid()}).strict()]),Cb=S.object({defaultLocale:yn,locales:S.record(yn,S.record(Me,S.string().max(In.stringLength)))}).strict(),_b=S.enum(["popup","paywall","onboarding","page","banner"]);var Eb=S.discriminatedUnion("type",[S.object({type:S.literal("modal"),size:S.enum(["sm","md","lg"])}).strict(),S.object({type:S.literal("sheet"),size:S.enum(["sm","md","lg"])}).strict(),S.object({type:S.literal("fullscreen")}).strict(),S.object({type:S.literal("inline")}).strict()]);var Rb=S.object({kind:S.literal("screen"),schemaVersion:S.literal(tb),name:S.string().trim().min(1).max(80),surface:_b,initialPageId:Xi.optional(),presentation:Eb,theme:jp,pages:S.array(S.object({id:Xi,name:S.string().trim().min(1).max(60),root:Fp,theme:jp.optional(),editorPosition:S.object({x:S.number().finite().min(-1e5).max(1e5),y:S.number().finite().min(-1e5).max(1e5)}).strict().optional()}).strict()).min(1).max(In.pages),strings:Cb,actions:S.array(Pb).max(In.actions)}).strict();function Ut(e,t){for(let n of e.pages)$n(n.root,t)}var on=Rb.superRefine((e,t)=>{let n=In;e.surface!=="paywall"&&e.pages.length!==1&&t.addIssue({code:"custom",message:"Only a Paywall can contain multiple screens"}),e.initialPageId&&!e.pages.some(l=>l.id===e.initialPageId)&&t.addIssue({code:"custom",message:"Initial screen does not exist"});for(let l of e.actions)l.type==="navigate"&&(e.surface!=="paywall"||!e.pages.some(f=>f.id===l.pageId))&&t.addIssue({code:"custom",message:"Navigation screen does not exist"});e.pages.length>n.pages&&t.addIssue({code:"custom",message:`\u9875\u9762\u6700\u591A ${n.pages} \u4E2A`}),e.actions.length>n.actions&&t.addIssue({code:"custom",message:`\u52A8\u4F5C\u6700\u591A ${n.actions} \u4E2A`});let r=l=>t.addIssue({code:"custom",message:l}),i=Object.keys(e.strings.locales);i.includes(e.strings.defaultLocale)||r("\u9ED8\u8BA4\u8BED\u8A00\u5FC5\u987B\u5728\u8BED\u8A00\u5217\u8868\u91CC"),i.length>In.locales&&r(`\u6700\u591A ${In.locales} \u79CD\u8BED\u8A00`);let a=new Set;for(let l of e.actions)a.has(l.id)&&r(`\u52A8\u4F5C\u6807\u8BC6\u91CD\u590D\uFF1A${l.id}`),a.add(l.id);let o=new Set;for(let l of e.pages)["next","back"].includes(l.id)&&r(`\u9875\u9762 id \u4E0D\u80FD\u4F7F\u7528\u4FDD\u7559\u540D\u79F0\uFF1A${l.id}`),o.has(l.id)&&r(`\u9875\u9762 id \u91CD\u590D\uFF1A${l.id}`),o.add(l.id);let s=new Set,c=0,u=!1;Ut(e,(l,f)=>{if(c++,f>In.depth&&(u=!0),s.has(l.id)&&r(`\u7EC4\u4EF6 id \u91CD\u590D\uFF1A${l.id}`),s.add(l.id),l.type==="button"&&!a.has(l.action)&&r(`\u6309\u94AE ${l.id} \u5F15\u7528\u7684\u52A8\u4F5C\u4E0D\u5B58\u5728\uFF1A${l.action}`),l.type==="custom_html")for(let m of Object.keys(l.html))i.includes(m)||r(`\u81EA\u5B9A\u4E49 HTML ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`);if(l.type==="image")for(let m of Object.keys(l.localizedSrc??{}))i.includes(m)||r(`\u56FE\u7247 ${l.id} \u542B\u6709\u672A\u542F\u7528\u7684\u8BED\u8A00\uFF1A${m}`)}),c>n.nodes&&r(`\u7EC4\u4EF6\u6700\u591A ${n.nodes} \u4E2A`),u&&r(`\u5C42\u7EA7\u6700\u591A ${In.depth} \u5C42`)});function $n(e,t,n=1,r=null){if(t(e,n,r)!==!1&&e.type==="stack")for(let i of e.children)$n(i,t,n+1,e)}function pa(e){let t=[],n=new Set;return Ut(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 kb(e,t,n){if(t.field==="html"){let r;return Ut(e,i=>{i.id===t.nodeId&&i.type==="custom_html"&&(r=i.html[n])}),r}if(t.field==="src"){let r=to(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=pa(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=>!kb(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 jb(e,t){let n=null;return $n(e,r=>{if(n)return!1;r.id===t&&(n=r)}),n}function to(e,t){for(let n of e.pages){let r=jb(n.root,t);if(r)return r}return null}import{z as Ft}from"zod";var yt=Ft.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"),lc=Ft.strictObject({type:Ft.enum(["string","number","boolean","strings","json","offering_version","reward","paywall_version"]),nullable:Ft.boolean(),enum:Ft.array(Ft.string().max(255)).min(1).max(100).optional()}),oi=lc.extend({type:Ft.enum([...lc.shape.type.options,"array"]),items:lc.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"})}),ai=oi.safeExtend({source:Ft.discriminatedUnion("type",[Ft.strictObject({type:Ft.literal("input")}),Ft.strictObject({type:Ft.literal("node")}),Ft.strictObject({type:Ft.enum(["parameter","attribute"]),key:yt})])}),_P=Ft.record(yt,ai),dc=Ft.record(yt,yt).refine(e=>Object.keys(e).length<=20);function pn(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=>pn(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&&Ft.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 pc(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&&pc(e.items,t.items)}function ma(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 l of s.split(".")){if(!u||typeof u!="object"||!Object.hasOwn(u,l)||Array.isArray(u)&&(!/^(0|[1-9]\d*)$/.test(l)||Number(l)>=u.length)){c=!1;break}u=u[l]}}if(!(!c||u===void 0)){if(!pn(i,u))throw new Error(`Invalid variable value: ${r}`);n[r]=u}}return n}function si(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 Mp(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"||!pn(e[i],a))throw new Error(`Invalid node variable write: ${i}`);if(r.size!==Object.keys(n).length)throw new Error("Node output is incomplete")}import{z as Cr}from"zod";var vn=Cr.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"),Rn=Cr.discriminatedUnion("source",[Cr.strictObject({source:Cr.literal("literal"),value:Se}),Cr.strictObject({source:Cr.literal("variable"),key:Cr.string().min(1).max(255),path:vn.optional()})]);function qp(e,t){if(!t)return e;for(let n of vn.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 mc(e,t){if(e.source==="literal")return structuredClone(e.value);let n=ma(t.declarations,t);if(!Object.hasOwn(n,e.key))throw new Error("Capability input is missing");return structuredClone(Se.parse(qp(n[e.key],e.path)))}function fc(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&&!vn.safeParse(r).success?null:{key:n,path:r}}function gc(e){let t=Object.values(e.strings.locales).flatMap(n=>Object.values(n));return Ut(e,n=>{n.type==="custom_html"&&t.push(...Object.values(n.html))}),[...new Set(t.flatMap(Op))]}function fa(e){return gc(e).filter(t=>t.startsWith("variables.")).map(t=>t.slice(10))}function an(e){let t=JSON.stringify(e);if(t===void 0)throw new TypeError("A JSON value is required");let n=new TextEncoder().encode(t).length,r=!1;for(let i=0;i<t.length;i++){let a=t.charAt(i);if(r)a==="\\"?i++:a==='"'&&(r=!1);else if(a==='"')r=!0;else if(a===":"||a===",")n++;else if(a==="-"||a>="0"&&a<="9"){let o=i;for(;i+1<t.length&&/[0-9.eE+-]/.test(t.charAt(i+1));)i++;let s=t.slice(o,i+1);if(!/[eE]/.test(s))continue;let[c="",u]=s.split(/[eE]/),l=c.replace(/^-/,""),f=l.replace(".","").length,m=(l.includes(".")?l.indexOf("."):f)+Number(u),h=m<=0?2-m+f:m>=f?m:f+1;n+=h+(c.startsWith("-")?1:0)-s.length}}return n}var tr=Pe.enum(["page","popup","banner"]),Tb=3e5,Bp=Pe.strictObject({type:Pe.enum(["string","number","boolean","strings","json"]),nullable:Pe.boolean()}),Nb=Pe.strictObject({inputs:Pe.record(Me,Bp.extend({required:Pe.boolean()})).refine(e=>Object.keys(e).length<=40,"Too many content inputs"),outputs:Pe.record(Me,Bp).refine(e=>Object.keys(e).length<=40,"Too many content outputs")}),Db=Pe.strictObject({kind:tr,schemaVersion:Pe.literal(1),name:Pe.string().trim().min(1).max(80),screen:on,contract:Nb}),ga=Db.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"]),an(e)>Tb&&n("Content document exceeds its byte budget",[])});function Fb(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 Mb=ga.superRefine((e,t)=>{for(let n of fa(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&&!Fb(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"})}),Vp=Pe.strictObject({id:Pe.uuid(),kind:tr,projectId:Pe.uuid(),environmentId:Pe.uuid(),name:Pe.string(),revision:Pe.number().int().nonnegative(),status:Pe.enum(["draft","published","archived"]),publishedVersionId:Pe.uuid().nullable(),createdAt:Pe.iso.datetime({offset:!0}),updatedAt:Pe.iso.datetime({offset:!0})}),$P=Vp.extend({draft:ga}),GP=Pe.strictObject({rows:Pe.array(Vp).max(200),nextCursor:Pe.uuid().nullable()}),hc=Pe.strictObject({id:Pe.uuid(),kind:tr,resourceId:Pe.uuid(),projectId:Pe.uuid(),environmentId:Pe.uuid(),version:Pe.number().int().positive(),sourceRevision:Pe.number().int().nonnegative(),document:Mb,createdAt:Pe.iso.datetime({offset:!0})}),KP=hc.omit({document:!0}),HP=Pe.discriminatedUnion("action",[Pe.strictObject({action:Pe.literal("create"),kind:tr,id:Pe.uuid(),document:ga}),Pe.strictObject({action:Pe.literal("save"),kind:tr,id:Pe.uuid(),revision:Pe.number().int().nonnegative(),document:ga}),Pe.strictObject({action:Pe.enum(["publish","archive"]),kind:tr,id:Pe.uuid(),revision:Pe.number().int().nonnegative()})]).superRefine((e,t)=>{"document"in e&&e.document.kind!==e.kind&&t.addIssue({code:"custom",path:["document","kind"],message:"Content cannot change domain"})});import{z as Lp}from"zod";var ci={funnelId:Lp.uuid().optional(),funnelVersionId:Lp.uuid().optional()};import{z as ha}from"zod";var Aa=ha.strictObject({runId:ha.uuid(),bindingId:ha.uuid(),receiptId:ha.uuid()});import{z as rt}from"zod";import{z as qe}from"zod";import{z as Ye}from"zod";var eC=Ye.discriminatedUnion("action",[Ye.strictObject({action:Ye.literal("create"),couponId:Ye.uuid(),productBindingId:Ye.uuid(),storeOfferId:Ye.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),storeOfferType:Ye.enum(["introductory","promotional"])}),Ye.strictObject({action:Ye.literal("set_enabled"),id:Ye.uuid(),revision:Ye.number().int().nonnegative(),enabled:Ye.boolean()})]),tC=Ye.array(Ye.strictObject({id:Ye.uuid(),couponId:Ye.uuid(),productBindingId:Ye.uuid(),storeOfferId:Ye.string().min(1).max(255).nullable(),storeOfferType:Ye.enum(["introductory","promotional"]),enabled:Ye.boolean(),revision:Ye.number().int().nonnegative()})).max(500),ui=Ye.strictObject({offerKind:Ye.enum(["none","introductory","promotional"]),offerId:Ye.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).nullable(),discountMinor:Ye.number().int().min(0).max(1e8),trialDays:Ye.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"})}),nC=Ye.record(Ye.uuid(),ui).refine(e=>Object.keys(e).length<=20,"At most 20 native store selections");var Ac=qe.object({type:qe.literal("native_purchase"),receiptId:qe.uuid(),orderId:qe.uuid(),productVersionId:qe.uuid(),provider:qe.enum(["apple","google"]),productId:qe.string().min(1).max(255),productKind:vp,replacement:qe.strictObject({sourceOrderId:qe.uuid(),sourceProductId:qe.string().min(1).max(255),policy:qe.enum(["apple_store","google_full_price"]),sourceAccountTokens:qe.array(qe.uuid()).max(50)}).nullable(),appAccountToken:qe.uuid().optional(),obfuscatedAccountId:qe.string().min(1).max(64).optional(),obfuscatedProfileId:qe.uuid().optional(),basePlanId:qe.string().min(1).max(255).optional(),offerId:qe.string().min(1).max(255).optional(),offerKind:qe.enum(["none","introductory","promotional"]),currency:be,catalogAmountMinor:qe.number().int().nonnegative().max(1e8),discountMinor:qe.number().int().nonnegative().max(1e8),trialDays:qe.number().int().min(1).max(730).nullable(),seatBundle:qe.array(qe.strictObject({key:qe.string().regex(/^[a-z][a-z0-9_]{0,63}$/),quantity:qe.number().int().min(1).max(1e4)})).max(20),applePromotionalOffer:qe.strictObject({offerId:qe.string().min(1).max(255),keyId:qe.string().min(1).max(255),nonce:qe.uuid(),signature:qe.string().min(1).max(1024),timestamp:qe.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}).nullable()}).strict().superRefine((e,t)=>{let n=e.provider==="apple";(e.replacement!==null&&(e.productKind!=="membership"||e.offerKind!=="none"||e.trialDays!==null||e.replacement.policy!==(n?"apple_store":"google_full_price"))||e.productKind!=="membership"&&(e.trialDays!==null||e.offerKind!=="none"||e.basePlanId!==void 0)||!n&&e.productKind==="membership"&&e.basePlanId===void 0||e.discountMinor>e.catalogAmountMinor||new Set(e.seatBundle.map(i=>i.key)).size!==e.seatBundle.length||e.trialDays!==null&&(e.discountMinor!==0||e.offerKind==="none")||e.offerKind==="none"&&e.discountMinor!==0||(n?!e.appAccountToken||e.obfuscatedAccountId!==void 0||e.obfuscatedProfileId!==void 0||e.basePlanId!==void 0||e.offerKind==="promotional"!=(e.applePromotionalOffer!==null)||e.offerKind==="promotional"!=(e.offerId!==void 0)||e.applePromotionalOffer!==null&&e.applePromotionalOffer.offerId!==e.offerId:e.appAccountToken!==void 0||!e.obfuscatedAccountId||!e.obfuscatedProfileId||e.applePromotionalOffer!==null||e.offerKind==="none"!=(e.offerId===void 0)))&&t.addIssue({code:"custom",message:"Native purchase terms must match the accepted store selection"})});import{z as p}from"zod";import{z as Ce}from"zod/v4";import{z as qb}from"zod/v4";var Bb=qb.registry(),{BillingInterval:Up}=(()=>{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:Vb}=(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')."})})}))(Ce),{withSpecDefault:Lb}=(e=>({withSpecDefault:({schema:n,defaultValue:r,description:i})=>(e.add(n,{description:i,default:r}),n)}))(Bb),{COMMON:zp}={COMMON:["usd","eur","gbp","cad","aud","jpy","chf","cny","inr"]},{STRIPE_PRESENTMENT_CURRENCIES:Ub}={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:zb}=(e=>({COMMON_SET:new Set(e)}))(zp),{hasNoDuplicateCurrencies:$p}={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:Gp}={DUPLICATE_CURRENCY_MESSAGE:"Each currency may appear at most once in additional_currencies."},{ApiStripePriceProcessorSchema:$b}=(e=>({ApiStripePriceProcessorSchema:e.object({price_id:e.string().meta({description:"Stripe price ID. For prepaid with included > 0 this is the V2 price."})})}))(Ce),{Infinite:Gb}={Infinite:"inf"},{TierBehavior:Kb}=(()=>{var e;return(function(t){t.Graduated="graduated",t.VolumeBased="volume"})(e||(e={})),{TierBehavior:e}})(),{BillingMethod:Kp}=(()=>{var e;return(function(t){t.Prepaid="prepaid",t.UsageBased="usage_based"})(e||(e={})),{BillingMethod:e}})(),{AllocatedBilling:Hb}=(()=>{var e;return(function(t){t.Arrear="arrear",t.ProratedLegacy="prorated_legacy"})(e||(e={})),{AllocatedBilling:e}})(),{CREDIT_DIMENSION_NAME_MAX_LENGTH:Qb}={CREDIT_DIMENSION_NAME_MAX_LENGTH:64},{USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:Jb}={USAGE_ATTRIBUTION_DIMENSION_SEPARATOR:"::"},{CreditMatchSchema:Zb}=(e=>({CreditMatchSchema:e.record(e.string(),e.union([e.string(),e.number(),e.boolean()]).transform(String).pipe(e.string()))}))(Ce),{ApiCreditTierSchema:Hp}=(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."})})}))(Ce),{VIOLATION_MESSAGES:Wb}={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)})}))(Ce),{ModelMarkupsSchema:Yb}=((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()}))(Ce,Qp),{InvoiceUsageEntrySchema:Xb}=(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()}))(Ce),{AttachDiscountSchema:Jp}=(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."})}))(Ce),{CustomLineItemSchema:ex}=(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."})})}))(Ce),{UnixMsTimestampSchema:tx}=(e=>({UnixMsTimestampSchema:e.number().int().safe().nonnegative()}))(Ce),{CreateInvoicePreviewLineSchema:nx}=(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()})}))(Ce),{ReissueInvoiceParamsSchema:Zp}=(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."})})}))(Ce),{InvoiceModeParamsSchema:_r}=(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."})}))(Ce),{InvoiceTemplateSchema:rx}=(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."})})}))(Ce),{BasePriceSchema:ix}=((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."})})}))(Ce,Up,Vb),{CURRENCY_CODES:ox}=((e,t,n)=>({CURRENCY_CODES:[...e,...t.filter(i=>!n.has(i)).sort()]}))(zp,Ub,zb),{ApiPriceProcessorsSchema:Wp}=((e,t)=>({ApiPriceProcessorsSchema:e.object({stripe:t.nullish()}).meta({"x-atmn-mapping":!0})}))(Ce,$b),{AllocatedBillingFieldSchema:ax}=((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'."})}))(Ce,Hb),{CreditDimensionNameSchema:sx}=((e,t,n)=>({CreditDimensionNameSchema:e.string().min(1).max(t).refine(i=>!i.includes(n),{message:`Dimension names cannot contain "${n}"`})}))(Ce,Qb,Jb),{ApiCreditMatchSchema:Yp}=(e=>({ApiCreditMatchSchema:e.meta({description:"Event properties this entry applies to. Every key must equal the tracked property, compared as strings."})}))(Zb),{findCreditTierViolations:cx}=(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}}))(Wb),{ApiCreditMultiplierSchema:ux}=((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."})}))(Ce,Yp),{ProviderMarkupsSchema:lx}=((e,t)=>({ProviderMarkupsSchema:e.record(e.string(),t).nullish()}))(Ce,Qp),{InvoiceFeatureQuantitySchema:Xp}=((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."})}))(Ce,Kp,Xb),{CreateInvoicePreviewSchema:yc}=((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()})}))(Ce,nx),{SUPPORTED_SET:dx}=(e=>({SUPPORTED_SET:new Set(e)}))(ox),{ApiCreditDimensionBaseSchema:px}=((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."})})}))(Ce,Yp),{refineGraduatedTiers:em}=(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"]})}}))(cx),{ApiFeatureMarkupsOverrideSchema:mx}=((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."})})}))(Ce,lx,Yb),{isValidCurrencyCode:fx}=(e=>({isValidCurrencyCode:n=>!!n&&e.has(n.toLowerCase())}))(dx),{ApiCreditDimensionSchema:gx}=((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()])}))(Ce,px,Hp,em),{CurrencyCodeSchema:tm}=((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')."})}))(Ce,fx),{AdditionalCurrencyTierSchema:hx}=((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"]})}))(Ce,tm),{ApiCreditSchemaItemBaseSchema:nm}=((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."})})}))(Ce,sx,gx,ux),{ApiFlatCreditSchemaItemSchema:Ax}=((e,t)=>({ApiFlatCreditSchemaItemSchema:e.extend({credit_cost:t.number().min(0).meta({description:"Credits consumed per billing-unit group."})}).strict()}))(nm,Ce),{AdditionalCurrencyPriceSchema:yx}=((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."})})}))(Ce,tm),{AdditionalCurrencyTierArraySchema:bx}=((e,t,n,r)=>({AdditionalCurrencyTierArraySchema:e.array(t).refine(n,{message:r})}))(Ce,hx,$p,Gp),{ApiGraduatedCreditSchemaItemSchema:xx}=((e,t,n,r)=>({ApiGraduatedCreditSchemaItemSchema:e.extend({tier_behavior:t.literal("graduated"),tiers:t.array(n).min(1)}).strict().superRefine(r)}))(nm,Ce,Hp,em),{AdditionalCurrencyPriceArraySchema:rm}=((e,t,n,r)=>({AdditionalCurrencyPriceArraySchema:e.array(t).refine(n,{message:r})}))(Ce,yx,$p,Gp),{ApiUsageTierWithCurrenciesSchema:Sx}=((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()}))}))(Ce,Gb,bx),{ApiCreditSchemaItemSchema:Ix}=((e,t,n)=>({ApiCreditSchemaItemSchema:e.union([t,n])}))(Ce,xx,Ax),{BasePriceParamsSchema:vx}=((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."})}))(ix,Lb,Ce,rm),{PlanItemPriceParamsSchema:wx}=((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."})})}))(Ce,rm,Sx,Kb,Up,Kp,ax),{ApiFeatureOverrideSchema:Ox}=((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."})})}))(Ce,Ix,mx),{InvoiceBasePriceParamsSchema:im}=((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()}))(vx,Wp),{InvoiceItemPriceParamsSchema:Px}=((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()}))(wx,Wp),{InvoiceLicenseQuantitySchema:Cx}=((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()}))(Ce,im,Xp),{InvoiceCustomizeItemSchema:_x}=((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()}))(Ce,Px,Ox),{InvoiceCustomizeSchema:Ex}=((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."})}))(Ce,im,_x),{InvoicePlanParamsSchema:Rx}=((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()}))(Ce,Ex,Xp,Cx,Jp),{CreateInvoiceParamsSchema:li}=((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."})}))(Ce,Rx,ex,Jp,tx);var sm=p.strictObject({requestId:p.uuid(),predecessorOperationId:p.uuid().optional(),invoiceMode:_r.optional(),entityId:p.uuid().optional(),billingSubscriptionId:p.uuid().optional(),newBillingSubscription:p.literal(!0).optional(),offerId:p.uuid().optional(),nativeOffer:ui.optional(),plans:p.array(p.strictObject({productVersionId:p.uuid(),seatQuantities:p.record(qo,p.number().int().min(0).max(1e4)).optional(),featureQuantities:p.record(p.uuid(),p.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100,"At most 100 feature quantities").optional()})).min(1).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Plan versions must be unique"),provider:p.enum(["stripe","apple","google","merchant"]),currency:be}).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"),Rr=p.strictObject({operationId:p.uuid()}),jt=p.number().int().min(0).max(1e8),kx=p.strictObject({lineId:p.uuid(),productVersionId:p.uuid(),productName:p.string().min(1).max(80),interval:p.enum(["free","week","month","year","one_time"]),intervalCount:p.number().int().min(1).max(156).optional(),baseAmountMinor:jt,seats:p.array(p.strictObject({key:qo,quantity:p.number().int().min(0).max(1e4),includedQuantity:p.number().int().min(0).max(1e4),maximumQuantity:p.number().int().min(0).max(1e4),unitAmountMinor:jt})).max(20),prepaid:p.array(Wd).max(100).optional(),catalogAmountMinor:jt,trial:p.strictObject({days:p.number().int().min(1).max(730),cardRequired:p.boolean()}).nullable()}).refine(e=>new Set(e.seats.map(t=>t.key)).size===e.seats.length&&e.seats.every(t=>t.quantity>=t.includedQuantity&&t.quantity<=t.maximumQuantity)&&e.baseAmountMinor+e.seats.reduce((t,n)=>t+n.unitAmountMinor*(n.quantity-n.includedQuantity),0)+(e.prepaid??[]).reduce((t,n)=>t+zo({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"),cm=p.string().regex(/^[A-Za-z0-9_-]{1,200}$/),jx=p.strictObject({id:cm,name:p.string().min(1).max(40),percent_off:p.number().gt(0).max(100).optional(),amount_off:p.number().int().positive().optional(),currency:p.string().regex(/^[a-z]{3}$/).optional(),duration:p.enum(["once","repeating","forever"]),duration_in_months:p.number().int().min(1).max(36).optional()}).refine(e=>e.percent_off===void 0!=(e.amount_off===void 0)&&e.amount_off===void 0==(e.currency===void 0)&&e.duration==="repeating"==(e.duration_in_months!==void 0),"A Stripe coupon has one percentage or amount and months only when repeating"),Tx=p.strictObject({subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),customerId:p.string().regex(/^cus_[A-Za-z0-9]+$/),sourceItems:p.array(p.strictObject({id:p.string(),price_id:p.string(),quantity:p.number().int().nonnegative(),discounts:p.array(p.strictObject({id:p.string(),coupon:p.string(),start:p.number(),end:p.number().nullable()})).optional()})).min(1).max(100),prorationDate:p.number().int().nonnegative(),amountMinor:p.number().int().positive(),periodStartMs:p.number(),periodEndMs:p.number()}),um=p.strictObject({invoiceMode:_r.optional(),append:Tx.optional(),provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),mode:p.enum(["payment","subscription"]),lineItems:p.array(p.strictObject({price:p.string().regex(/^price_[A-Za-z0-9]+$/).nullable(),quantity:p.number().int().min(1).max(1e4),priceId:p.uuid(),productName:p.string().min(1).max(80),amountMinor:p.number().int().min(0).max(1e8),currency:p.string().regex(/^[a-z]{3}$/),interval:p.enum(["week","month","year","one_off"]),intervalCount:p.number().int().min(1).max(52),slot:p.enum(["stripe_price_id","stripe_empty_price_id"]),tiers:p.strictObject({mode:p.enum(["graduated","volume"]),tiers:p.array(p.strictObject({upTo:p.number().int().min(1).max(1e6).nullable(),unitAmountMinor:p.number().int().min(0).max(1e8),flatAmountMinor:p.number().int().min(0).max(1e8).optional()})).min(2).max(12)}).nullable()})).min(1).max(100),discounts:p.array(p.strictObject({coupon:cm,terms:jx})).max(1),trialPeriodDays:p.number().int().min(1).max(730).nullable(),metadata:p.strictObject({grooveCheckoutId:p.uuid(),grooveCustomerId:p.uuid()}),expiresAt:p.iso.datetime({offset:!0})}),di=p.strictObject({operationId:p.uuid(),entityId:p.uuid().nullable(),billingSubscriptionId:p.uuid().nullable(),discount:p.strictObject({offerId:p.uuid(),couponId:p.uuid(),discount:Wn,duration:nn,amountMinor:jt,allocations:p.array(p.strictObject({productVersionId:p.uuid(),amountMinor:jt})).min(1).max(20),expiresAt:p.iso.datetime({offset:!0})}).nullable(),charge:p.strictObject({effectiveAt:p.iso.datetime({offset:!0}),periodEndsAt:p.iso.datetime({offset:!0}),debitMinor:jt,discountMinor:jt,taxMinor:jt,totalMinor:jt}).nullable(),expiresAt:p.iso.datetime({offset:!0}),provider:p.enum(["stripe","apple","google","merchant"]),nativeOffer:ui.optional(),currency:be,lines:p.array(kx).min(1).max(20),catalogAmountMinor:jt,automaticTax:p.boolean(),execution:p.union([um,To]).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"),pi=p.strictObject({operationId:p.uuid(),orderId:p.uuid(),append:p.boolean().optional(),invoiceMode:p.boolean().optional(),status:p.enum(["pending","complete","cancelled","failed"]),executor:p.enum(["indiana","merchant"]),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),execution:p.union([um,To]).nullable(),currency:be,catalogAmountMinor:jt,taxMinor:jt,totalMinor:p.number().int().min(0).max(2e8).nullable(),quoteFinalized:p.boolean(),nativePurchase:Ac.nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),quote:di.optional(),merchantExecution:yr.nullable().optional(),problem:ji.nullable().optional(),authority:Mo.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"),ba=p.strictObject({enabled:p.literal(!0),featureIds:p.array(p.uuid()).min(1).max(100).refine(e=>new Set(e).size===e.length,"Feature IDs must be unique").optional()}),lm=p.strictObject({requestId:p.uuid(),invoiceMode:_r.optional(),membershipId:p.uuid(),carryOverBalances:ba.optional(),carryOverUsages:ba.optional(),membershipIds:p.array(p.uuid()).min(1).max(20).optional(),prorationBehavior:p.enum(["prorate_immediately","none","bill_difference"]).optional(),timing:p.enum(["immediate","renewal","store"]),change:p.discriminatedUnion("type",[p.strictObject({type:p.literal("plan"),productVersionId:p.uuid()}),p.strictObject({type:p.literal("seats"),licenseKey:qo,quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("quantity"),internal_feature_id:p.uuid(),quantity:p.number().int().min(0).max(1e4)}),p.strictObject({type:p.literal("cancel")}),p.strictObject({type:p.literal("uncancel")}),p.strictObject({type:p.literal("billing_cycle"),billingCycleAnchor:p.union([p.literal("now"),p.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"),ya=p.string().regex(/^price_[A-Za-z0-9]+$/),om=p.strictObject({grooveUpdateId:p.uuid(),grooveCustomerId:p.uuid()}),am=p.strictObject({price:ya.nullable(),priceId:p.uuid().optional(),quantity:p.number().int().min(0).max(1e4)}),dm=p.strictObject({provider:p.literal("stripe"),invoiceMode:_r.optional(),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:p.string().regex(/^sub_[A-Za-z0-9]+$/),action:p.enum(["update","cancel","schedule","release"]),update:p.strictObject({items:p.array(am).max(20),remove:p.array(ya).max(20),restoreItems:p.array(p.strictObject({price:ya,quantity:p.number().int().min(0).max(1e4)})).min(1).max(20).optional(),prorationBehavior:p.enum(["always_invoice","create_prorations","none"]).optional(),prorationDate:p.number().int().positive().optional(),paymentBehavior:p.literal("error_if_incomplete").optional(),cancelAtPeriodEnd:p.boolean().optional(),clearCancelAt:p.literal(!0).optional(),billingCycleAnchorNow:p.literal(!0).optional(),metadata:om}).nullable(),cancel:p.strictObject({prorate:p.literal(!1),invoiceNow:p.literal(!1)}).nullable(),schedule:p.strictObject({currentItems:p.array(p.strictObject({price:ya,quantity:p.number().int().min(0).max(1e4)})).max(20),nextItems:p.array(am).min(1).max(20),switchAt:p.number().int().positive(),interval:p.enum(["week","month","year"]),intervalCount:p.number().int().min(1).max(52),resetBillingCycleAnchor:p.literal(!0).optional(),metadata:om}).nullable(),release:p.strictObject({schedule:p.string().regex(/^sub_sched_[A-Za-z0-9]+$/)}).nullable(),expiresAt:p.iso.datetime({offset:!0})}).refine(e=>["update","cancel","schedule","release"].every(t=>e[t]!==null==(e.action===t))&&(e.executor==="indiana"||[...e.update?.items??[],...e.schedule?.nextItems??[]].every(t=>t.price!==null)),"Stripe update execution carries exactly its action, with bound Prices for the merchant"),xa=p.strictObject({carryOverBalances:ba.optional(),carryOverUsages:ba.optional(),operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),expiresAt:p.iso.datetime({offset:!0}),currency:be,creditMinor:jt,debitMinor:jt,discountMinor:jt,taxMinor:jt,totalMinor:jt,retainedProductVersionIds:p.array(p.uuid()).max(19),execution:p.union([dm,No])}),Nx=p.strictObject({operationId:p.uuid(),invoiceMode:p.boolean().optional(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","quoted","confirmed","pending","scheduled","effective","cancelled","failed"]),timing:p.enum(["immediate","renewal"]),effectiveAt:p.iso.datetime({offset:!0}),checkoutUrl:p.url().refine(e=>new URL(e).protocol==="https:").nullable(),executor:p.enum(["indiana","merchant"]),execution:p.union([dm,No]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:yr.nullable().optional(),problem:ji.nullable().optional(),quote:xa.optional(),authority:Mo.optional()}).refine(e=>e.execution===null||e.executor==="merchant","Only record-only changes carry execution instructions"),Dx=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),timing:p.literal("store"),effectiveAt:p.null(),expiresAt:p.iso.datetime({offset:!0}),currency:be,creditMinor:p.null(),debitMinor:p.null(),discountMinor:p.null(),taxMinor:p.null(),totalMinor:p.null(),retainedProductVersionIds:p.array(p.uuid()).max(19),store:p.strictObject({provider:p.enum(["apple","google"]),productId:p.string().min(1).max(255),catalogAmountMinor:jt,policy:p.enum(["apple_store","google_full_price"])})}),Fx=p.strictObject({operationId:p.uuid(),membershipId:p.uuid(),productVersionId:p.uuid(),status:p.enum(["prepared","pending","effective","cancelled","failed"]),timing:p.literal("store"),effectiveAt:p.iso.datetime({offset:!0}).nullable(),checkoutUrl:p.null(),nativePurchase:Ac.nullable()}),pm=p.union([xa,Dx]),bc=p.union([Nx,Fx]),no=p.number().int().positive().max(2e8),Er=p.number().int().min(0).max(2e8),mm=p.strictObject({requestId:p.uuid(),invoiceId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:no.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount"),fm=p.strictObject({provider:p.literal("stripe"),executor:p.enum(["indiana","merchant"]),accountId:p.string().regex(/^acct_[A-Za-z0-9]+$/),invoice:p.string().regex(/^in_[A-Za-z0-9]+$/),amountMinor:no,currency:p.string().regex(/^[a-z]{3}$/),metadata:p.strictObject({indianaRefundId:p.uuid()}),idempotencyKey:p.string().regex(/^indiana-refund-[0-9a-f-]{36}$/),cancelSubscriptions:p.array(p.string().regex(/^sub_[A-Za-z0-9]+$/)).max(20)}),xc=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),currency:be,paidMinor:Er,refundedMinor:Er,pendingMinor:Er,amountMinor:no,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),revokes:p.strictObject({customerProductIds:p.array(p.uuid()).max(100),subscriptionIds:p.array(p.string().min(1).max(200)).max(20)}),execution:p.union([fm,Do]),expiresAt:p.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"),Sa=p.strictObject({operationId:p.uuid(),invoiceId:p.uuid(),providerInvoiceId:p.string().min(1).max(200),status:p.enum(["quoted","pending","succeeded","failed","expired"]),executor:p.enum(["indiana","merchant"]),currency:be,amountMinor:no,mode:p.enum(["full","partial"]),entitlementAction:p.enum(["retain","revoke"]),refundId:p.string().min(1).max(200).nullable(),quote:xc.optional(),execution:p.union([fm,Do]).nullable(),confirmedAt:p.iso.datetime({offset:!0}).nullable().optional(),merchantExecution:yr.nullable().optional(),problem:ji.nullable().optional(),authority:Mo.optional(),failureReason:p.string().min(1).max(200).nullable(),createdAt:p.iso.datetime({offset:!0}),completedAt:p.iso.datetime({offset:!0}).nullable()}).refine(e=>(e.execution===null||e.executor==="merchant"&&e.status==="quoted")&&(e.status!=="succeeded"||e.refundId!==null),"Only quoted record-only refunds carry instructions; a succeeded refund names its Stripe refund"),IC=p.strictObject({invoiceId:p.uuid(),currency:be,paidMinor:Er,refundedMinor:Er,pendingMinor:Er,refundableMinor:Er,executor:p.enum(["indiana","merchant"]).nullable(),canRefund:p.boolean(),operations:p.array(Sa).max(50)}).refine(e=>e.operations.every(t=>t.invoiceId===e.invoiceId),"Refund operations belong to the invoice"),vC=p.strictObject({requestId:p.uuid(),mode:p.enum(["full","partial"]),amountMinor:no.optional(),entitlementAction:p.enum(["retain","revoke"])}).refine(e=>e.mode==="partial"==(e.amountMinor!==void 0),"A partial refund states amountMinor; a full refund refunds the remaining amount");var gm=rt.strictObject({requestId:rt.uuid(),targets:rt.array(rt.strictObject({membershipId:rt.uuid(),action:rt.enum(["cancel","uncancel"]),timing:rt.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"),Ia=rt.strictObject({batchId:rt.uuid()}),Mx=rt.strictObject({operationId:rt.uuid(),membershipIds:rt.array(rt.uuid()).min(1).max(20),provider:rt.enum(["stripe","apple","google"]),action:rt.enum(["cancel","uncancel"]),timing:rt.enum(["immediate","renewal"]),status:rt.enum(["prepared","confirmed","pending","scheduled","effective","cancelled","failed","store_action_required"]),quote:xa.nullable(),managementUrl:rt.url().nullable(),failureCode:rt.enum(["provider_unavailable","invalid_evidence","pending_payment"]).nullable()}),ro=rt.strictObject({batchId:rt.uuid(),ready:rt.boolean(),status:rt.enum(["prepared","cancelled","expired","pending","partial","effective","action_required"]),createdAt:rt.iso.datetime({offset:!0}),acceptedAt:rt.iso.datetime({offset:!0}).nullable(),groups:rt.array(Mx).min(1).max(100)});import{z as Re}from"zod";var qx=Re.string().trim().min(1).max(240),Sc={requestId:Re.uuid(),reason:qx},va=Re.discriminatedUnion("action",[Re.strictObject({...Sc,action:Re.literal("start"),productVersionId:Re.uuid(),entityId:Re.uuid().optional(),days:Re.number().int().min(1).max(730).optional()}),Re.strictObject({...Sc,action:Re.literal("extend"),membershipId:Re.uuid(),days:Re.number().int().min(1).max(730)}),Re.strictObject({...Sc,action:Re.literal("end"),membershipId:Re.uuid()})]),hm=Re.strictObject({operationId:Re.uuid()}),Am=Re.iso.datetime({offset:!0}),Bx=Re.strictObject({provider:Re.literal("stripe"),executor:Re.enum(["indiana","merchant"]),accountId:Re.string().regex(/^acct_[A-Za-z0-9]+$/),subscriptionId:Re.string().regex(/^sub_[A-Za-z0-9]+$/),trialEnd:Re.union([Re.literal("now"),Am]),prorationBehavior:Re.literal("none")}),Ic=Re.strictObject({operationId:Re.uuid(),action:Re.enum(["start","extend","end"]),status:Re.enum(["pending","effective"]),managedBy:Re.enum(["indiana","stripe"]),membershipIds:Re.array(Re.uuid()).min(1).max(20),endsAt:Am.nullable(),execution:Bx.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"),EC=Re.strictObject({groupId:Re.uuid(),productVersionId:Re.uuid(),enabled:Re.boolean()});import{z as Je}from"zod";var ym=Je.strictObject({requestId:Je.uuid(),currency:be,makeDefault:Je.boolean()}),bm=Je.strictObject({setupId:Je.uuid()}),Vx=Je.strictObject({provider:Je.literal("stripe"),executor:Je.literal("merchant"),accountId:Je.string().regex(/^acct_[A-Za-z0-9]+$/),mode:Je.literal("setup"),currency:Je.string().regex(/^[a-z]{3}$/),customer:Je.string().regex(/^cus_[A-Za-z0-9]+$/).nullable(),clientReferenceId:Je.uuid(),metadata:Je.strictObject({grooveProjectId:Je.uuid(),grooveEnvironmentId:Je.uuid(),grooveCustomerId:Je.uuid(),groovePaymentSetupId:Je.uuid()}),setDefaultPaymentMethod:Je.boolean(),expiresAt:Je.iso.datetime({offset:!0})}),vc=Je.strictObject({id:Je.uuid(),provider:Je.literal("stripe"),status:Je.enum(["prepared","complete","expired"]),currency:be,makeDefault:Je.boolean(),url:Je.url().nullable(),createdAt:Je.iso.datetime({offset:!0}),expiresAt:Je.iso.datetime({offset:!0}),completedAt:Je.iso.datetime({offset:!0}).nullable(),execution:Vx.nullable()});import{z as Tt}from"zod";var xm=Tt.union([Tt.string(),Tt.number(),Tt.boolean(),Tt.null()]),Sm=Tt.strictObject({customerId:Tt.uuid()}),Im=Tt.strictObject({customerId:Tt.uuid(),provider:Tt.literal("stripe"),checkedAt:Tt.iso.datetime({offset:!0}),status:Tt.enum(["consistent","drifted","incomplete"]),checkedSubscriptions:Tt.number().int().nonnegative(),differences:Tt.array(Tt.strictObject({subscriptionId:Tt.string().startsWith("sub_"),itemId:Tt.string().nullable(),field:Tt.enum(["subscription","status","currency","cancelAtPeriodEnd","item","price","product","quantity","periodStart","periodEnd","trialEnd","evidence"]),expected:xm,actual:xm})).max(1e4)});import{z as Ie}from"zod";var wa=Ie.iso.datetime({offset:!0}),Oa=Ie.strictObject({createdAt:wa,id:Ie.uuid()}),Pa=Ie.strictObject({customerId:Ie.uuid().optional(),entityId:Ie.uuid().optional(),productId:Ie.string().min(1).max(256).optional(),provider:Ie.enum(["stripe","apple","google","merchant","free"]).optional(),status:Ie.enum(["trial","active","past_due","ended","refunded"]).optional(),cursor:Oa.optional(),limit:Ie.number().int().min(1).max(100).optional()}),wc={id:Ie.uuid(),customerId:Ie.uuid(),entityId:Ie.uuid().nullable(),productId:Ie.string().min(1).max(256),productVersionId:Ie.uuid(),name:Ie.string().min(1).max(120),provider:Ie.enum(["stripe","apple","google","merchant","free"]),createdAt:wa},Lx=Ie.strictObject({...wc,status:Ie.enum(["trial","active","past_due","ended"]),cancelAtPeriodEnd:Ie.boolean(),billingSubscriptionId:Ie.uuid().nullable()}),Ux=Ie.strictObject({...wc,status:Ie.enum(["active","ended","refunded"]),orderId:Ie.uuid().nullable(),transactionId:Ie.uuid().nullable(),currency:be.nullable(),amountMinor:Ie.string().regex(/^(0|[1-9]\d{0,17})$/).nullable()}),zx=Ie.strictObject({...wc,status:Ie.enum(["blocked","resolved"]),conflict:Ie.strictObject({detectedAt:wa,blockingMembershipIds:Ie.array(Ie.uuid()).min(1).max(100),transactionId:Ie.uuid()}),resolvedAt:wa.nullable()}),vm=Pa.extend({status:Ie.enum(["blocked","resolved"]).optional()}),wm=Ie.strictObject({customerId:Ie.uuid(),orderId:Ie.uuid()}),Om=Ie.strictObject({orderId:Ie.uuid(),status:Ie.enum(["blocked","resolved"])}),Pm=Ie.strictObject({items:Ie.array(Lx).max(100),nextCursor:Oa.nullable()}),Cm=Ie.strictObject({items:Ie.array(Ux).max(100),nextCursor:Oa.nullable()}),_m=Ie.strictObject({items:Ie.array(zx).max(100),nextCursor:Oa.nullable()});import{z as et}from"zod";var Em=et.union([et.strictObject({intent:et.literal("read"),requestId:et.uuid(),purchaseIntentId:et.uuid()}),et.strictObject({requestId:et.uuid(),provider:et.literal("apple"),purchaseIntentId:et.uuid(),productId:et.string().min(1).max(255).optional(),signedTransaction:et.string().min(1).max(131072)}),et.strictObject({requestId:et.uuid(),provider:et.literal("google"),purchaseIntentId:et.uuid(),productId:et.string().min(1).max(255).optional(),purchaseToken:et.string().min(1).max(16384)})]),Rm=et.strictObject({requestId:et.uuid(),orderId:et.uuid(),purchaseIntentId:et.uuid(),status:et.enum(["created","pending","trialing","paid","cancelled","failed"]),currency:be,refunded:et.boolean(),completion:et.strictObject({transactionIds:et.array(et.string().min(1).max(255)).min(1).max(50).refine(e=>new Set(e).size===e.length),membership:et.boolean()}).nullable()});import{z as U}from"zod";var Pc=U.uuid().refine(e=>e===e.toLowerCase(),"Product references require canonical lowercase UUIDs"),$x=U.record(U.string(),U.json()).refine(e=>Array.from(JSON.stringify(e)).length<=4e3,"Offering metadata exceeds 4000 characters"),Gx=3,io=20,Kx=Gx*io,Oc=U.strictObject({type:U.literal("product"),productId:Pc}),km={type:U.literal("group"),key:U.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),name:U.string().trim().min(1).max(80)},Hx=U.discriminatedUnion("type",[Oc,U.strictObject({...km,items:U.array(Oc).max(io)})]),Qx=U.discriminatedUnion("type",[Oc,U.strictObject({...km,items:U.array(Hx).max(io)})]),Jx=U.array(Qx).max(io).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>io||i>Kx)&&t.addIssue({code:"custom",message:"Offering item limit exceeded"})});function Cc(e){return e.items.flatMap(t=>t.type==="product"?[t.productId]:Cc(t))}var mi=U.strictObject({lookupKey:U.string().trim().min(1).max(200),displayName:U.string().trim().min(1).max(1500),items:Jx,metadata:$x}),Zx=U.strictObject({product:U.record(U.string(),U.json()),prices:U.array(U.record(U.string(),U.json())),entitlements:U.array(U.record(U.string(),U.json())),freeTrials:U.array(U.record(U.string(),U.json())),licenses:U.array(U.record(U.string(),U.json()))}),jm=mi.extend({id:U.uuid(),projectId:U.uuid(),environmentId:U.uuid(),state:U.enum(["active","archived"]),isCurrent:U.boolean(),revision:U.number().int().nonnegative(),publishedVersionId:U.uuid().nullable(),createdAt:U.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"})}),Tm=U.strictObject({id:U.uuid(),offeringId:U.uuid(),projectId:U.uuid(),environmentId:U.uuid(),version:U.number().int().positive(),document:mi,productEvidence:U.record(Pc,Zx),createdAt:U.iso.datetime({offset:!0})}).superRefine((e,t)=>{let n=Cc(e.document);(!n.length||Xx(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"})}),Wx=U.strictObject({rows:U.array(jm).max(200),versions:U.array(Tm).max(500)}),zC=U.discriminatedUnion("action",[U.strictObject({action:U.literal("create"),document:mi}),U.strictObject({action:U.literal("save"),id:U.uuid(),revision:U.number().int().nonnegative(),document:mi}),U.strictObject({action:U.enum(["publish","set_current","archive","restore"]),id:U.uuid(),revision:U.number().int().nonnegative()})]),$C=U.strictObject({record:jm,version:Tm.nullable()}),Nm=U.discriminatedUnion("type",[U.strictObject({type:U.literal("current")}),U.strictObject({type:U.literal("id"),id:U.uuid()}),U.strictObject({type:U.literal("lookup_key"),lookupKey:U.string().min(1).max(200)}),U.strictObject({type:U.literal("version"),versionId:U.uuid()})]),Yx=U.strictObject({internalId:Pc,id:U.string(),name:U.string().nullable(),version:U.number().int().positive(),archived:U.boolean()}),GC=Wx.extend({products:U.array(Yx).max(500),pagination:U.strictObject({rows:U.string().nullable(),versions:U.string().nullable(),products:U.string().nullable()}).optional()});function Xx(e){let t=[];Cc(e).length||t.push("Select at least one Product before publishing");function n(r){for(let i of r)i.type==="group"&&(i.items.length||t.push("Every published group requires a Product"),n(i.items))}return n(e.items),t}import{z as Ca}from"zod";var Dm=Ca.strictObject({id:Ca.uuid(),offeringId:Ca.uuid(),version:Ca.number().int().positive(),document:mi});import{z as wt}from"zod";import{z as fe}from"zod";import{z as fi}from"zod";var _a=fi.strictObject({items:fi.array(fi.strictObject({productVersionId:fi.string().min(1).max(200),label:fi.string().trim().max(40)})).max(20).refine(e=>new Set(e.map(t=>t.productVersionId)).size===e.length,"Duplicate Paywall Product"),defaultProductVersionId:fi.string().min(1).max(200).nullable(),grouping:la.optional()});function Fm(e,t,n){let r=e.type==="fixed"?e.productVersionId:t[e.pickerId];return typeof r!="string"||!Object.values(n.plans).some(i=>i.versionId===r&&i.available)||e.type==="picker"&&(!e.allowedProductVersionIds.includes(r)||!n.pickers[e.pickerId]?.options.includes(r))?null:r}import{z as St}from"zod";var eS=St.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Ea=St.discriminatedUnion("type",[St.object({type:St.literal("fixed"),productVersionId:St.string().min(1).max(200)}).strict(),St.object({type:St.literal("picker"),pickerId:eS,allowedProductVersionIds:St.array(St.string().min(1).max(200)).min(1).max(20)}).strict().refine(e=>new Set(e.allowedProductVersionIds).size===e.allowedProductVersionIds.length,"Product choices must be unique")]),Gn=St.discriminatedUnion("type",[St.object({type:St.literal("modal"),size:St.enum(["sm","md","lg"])}).strict(),St.object({type:St.literal("sheet"),size:St.enum(["sm","md","lg"])}).strict(),St.object({type:St.literal("fullscreen")}).strict(),St.object({type:St.literal("inline")}).strict()]);var _c=fe.discriminatedUnion("type",[fe.strictObject({type:fe.literal("event"),event:fe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/)}),fe.strictObject({type:fe.literal("open_url"),url:fe.url().refine(e=>new URL(e).protocol==="https:")})]),tS=on,nS=fe.discriminatedUnion("type",[fe.object({type:fe.literal("checkout"),product:Ea}).strict(),fe.object({type:fe.literal("close")}).strict(),fe.object({type:fe.literal("action"),action:_c}).strict()]),gi=fe.object({schemaVersion:fe.literal(3),kind:fe.literal("paywall"),name:fe.string().trim().min(1).max(80),presentation:Gn,requirement:Xn.optional(),products:_a,offeringVersionId:fe.uuid().nullable(),offeringId:fe.uuid(),screen:tS,buttons:fe.record(fe.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),nS)}).strict(),c_=gi.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 iS(e))t.addIssue({code:"custom",message:r});for(let r of rS(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 rS(e){let t=e.products.items.map(a=>a.productVersionId),n=Pp(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&&(!da(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")),Ut(e.screen,u=>{if(u.id!==o.pickerId||u.type!=="plan_picker")return;s=!0,(JSON.stringify(u.planIds)!==JSON.stringify(t)||JSON.stringify(o.allowedProductVersionIds)!==JSON.stringify(t)||u.defaultPlan!==e.products.defaultProductVersionId)&&i.push("picker");let l=u.grouping?{tiers:u.grouping.tiers,assignments:u.grouping.assignments}:void 0;JSON.stringify(l)!==JSON.stringify(e.products.grouping)&&i.push("grouping")}),s||i.push("picker")}}return(!r.size||[...r].some(a=>!t.includes(a)))&&i.push("purchase"),Ut(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 iS(e){let t=[],n=e.screen.pages.at(-1),r=new Map;for(let s of e.screen.pages)r.set(s.id,[]),$n(s.root,c=>{let u=c.type==="button"?c.action:c.type==="stack"?c.purchaseAction:void 0;if(u){let l=e.screen.actions.find(m=>m.id===u);l?.type==="navigate"&&r.get(s.id).push(l.pageId);let f=e.buttons[u];s.id!==n.id&&f&&f.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 Mm=fe.object({id:fe.uuid(),projectId:fe.uuid(),environmentId:fe.uuid(),revision:fe.number().int().nonnegative(),state:fe.enum(["active","archived"]),publishedVersionId:fe.uuid().nullable(),updatedAt:fe.iso.datetime({offset:!0}),draft:gi}).strict(),u_=fe.object({rows:fe.array(Mm).max(200),nextCursor:fe.uuid().nullable()}).strict(),l_=Mm.omit({draft:!0}).extend({name:fe.string(),productCount:fe.number().int().nonnegative()}).strict(),d_=fe.discriminatedUnion("action",[fe.object({action:fe.literal("save"),id:fe.uuid().nullable(),revision:fe.number().int().nonnegative(),document:gi}).strict(),fe.object({action:fe.enum(["publish","archive"]),id:fe.uuid(),revision:fe.number().int().nonnegative()}).strict()]),p_=fe.object({paywalls:fe.array(fe.object({id:fe.uuid(),paywallId:fe.uuid(),version:fe.number().int().positive(),name:fe.string().min(1).max(80),presentation:Gn,buttons:gi.shape.buttons}).strict()).max(500),limited:fe.boolean()}).strict();import{z as _e}from"zod";import{z as zt}from"zod";var hi=zt.string().regex(/^[a-f0-9]{64}$/),oS=ca.pick({text:!0,label:!0,alt:!0,html:!0,couponId:!0,countdownAt:!0,missing:!0}),qm=zt.strictObject({couponDigests:zt.record(zt.uuid(),hi),variables:zt.record(yn,zt.record(zt.uuid(),zt.partialRecord(zt.enum(["offer.name","offer.description","offer.headline","offer.eligibility","offer.validity","offer.terms","offer.discount","offer.months","offer.ends_at"]),zt.string()))),locales:zt.record(yn,ii.extend({nodes:zt.record(zt.string(),zt.strictObject({base:oS})),plans:zt.object({}).strict(),pickers:zt.object({}).strict()}).omit({paywall:!0}))});import{z as Be}from"zod";import{z as Ra}from"zod";var Ec=Ra.strictObject({eventsEnabled:Ra.boolean(),experimentViewsEnabled:Ra.boolean(),featureUsageEnabled:Ra.boolean()}),b_=Object.freeze({eventsEnabled:!0,experimentViewsEnabled:!0,featureUsageEnabled:!0});function Bm(e,t){return t==="Experiment Viewed"?e.experimentViewsEnabled:t==="Feature Evaluated"?e.featureUsageEnabled:e.eventsEnabled}import{z as $}from"zod";var Rc=$.tuple([$.number().min(0).max(1),$.number().min(0).max(1)]).refine(([e,t])=>e<=t),aS=$.strictObject({attribute:$.string().optional(),seed:$.string(),hashVersion:$.literal(2),ranges:$.array(Rc).max(100)}),sS=$.strictObject({id:$.string().min(1).max(255),condition:Jt,gate:$.boolean().optional()}),cS=$.strictObject({key:$.string().optional(),name:$.string().optional(),passthrough:$.boolean().optional()}),Vm={condition:Jt.optional(),parentConditions:$.array(sS).max(100).optional(),weights:$.array($.number().min(0).max(1)).max(20).optional(),coverage:$.number().min(0).max(1).optional(),hashAttribute:$.string().optional(),fallbackAttribute:$.string().optional(),hashVersion:$.literal(2).optional(),disableStickyBucketing:$.boolean().optional(),bucketVersion:$.number().int().nonnegative().optional(),minBucketVersion:$.number().int().nonnegative().optional(),filters:$.array(aS).max(100).optional(),ranges:$.array(Rc).max(20).optional(),meta:$.array(cS).max(20).optional(),seed:$.string().optional(),name:$.string().optional(),phase:$.string().optional()},Ai=$.strictObject({...Vm,key:$.string().min(1).max(255),variations:$.tuple([Se,Se]).rest(Se).refine(e=>e.length<=20),urlPatterns:$.array($.strictObject({include:$.boolean(),type:$.enum(["regex","simple"]),pattern:$.string()})).max(100).optional(),force:$.number().int().nonnegative().optional(),active:$.boolean().optional(),persistQueryString:$.boolean().optional()}),kc=$.strictObject({value:Se,variationId:$.number().int(),key:$.string(),name:$.string().optional(),bucket:$.number().optional(),passthrough:$.boolean().optional(),inExperiment:$.boolean(),hashUsed:$.boolean().optional(),hashAttribute:$.string(),hashValue:$.string(),featureId:$.string().nullable(),stickyBucketUsed:$.boolean().optional()}),uS=$.strictObject({...Vm,id:$.string().max(255).optional(),force:Se.optional(),variations:$.array(Se).min(2).max(20).optional(),key:$.string().optional(),range:Rc.optional(),tracks:$.array($.strictObject({experiment:Ai,result:kc})).max(100).optional()}),lS=$.strictObject({defaultValue:Se.optional(),rules:$.array(uS).max(500).optional()}),oo=$.record($.string(),$.union([$.strictObject({type:$.literal("hashed"),attributeKey:$.string(),values:$.array($.string().regex(/^[a-f0-9]{64}$/))}),$.strictObject({type:$.literal("list"),attributeKey:$.string(),values:$.array($.union([$.string(),$.number()]))}),$.strictObject({type:$.literal("condition"),condition:Jt})])),mn=$.strictObject({scope:je,generation:$.string().regex(/^[a-f0-9]{64}$/),evaluatedAt:$.iso.datetime({offset:!0}),expiresAt:$.iso.datetime({offset:!0}).nullable(),features:$.record($.string(),lS),savedGroups:oo,experiments:$.record($.uuid(),Ai)});var ao=mn.extend({analyticsConfig:Ec,remoteFeatures:Be.array(Be.string().min(1).max(255)).max(500)}),jc=ao.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"})}),Lm=Be.strictObject({attributes:xt,features:Be.array(Be.string().min(1).max(255)).max(500).optional(),customerId:Be.uuid().optional()}),dS=Be.strictObject({value:Se,source:Be.enum(["unknownFeature","defaultValue","force","override","experiment","prerequisite","cyclicPrerequisite"]),on:Be.boolean(),off:Be.boolean(),ruleId:Be.string(),experimentResult:kc.optional()}),ka=Be.strictObject({generation:mn.shape.generation,evaluatedAt:mn.shape.evaluatedAt,expiresAt:mn.shape.expiresAt,features:Be.record(Be.string(),dS),merchandiseContext:Be.strictObject({merchandiseId:Be.uuid(),merchandise:xt}).optional()}),Um=Be.strictObject({customerId:Be.uuid().optional(),events:Be.array(Be.strictObject({eventUuid:Be.uuid(),timestamp:Be.iso.datetime({offset:!0}),name:Be.string().min(1).max(255),merchandise:Pd.optional(),properties:Be.record(Be.string(),Se).default({}),deviceId:Be.string().min(1).max(255).optional(),sessionId:Be.string().min(1).max(255).optional()})).min(1).max(100)}),zm=Be.strictObject({inserted:Be.number().int().nonnegative(),duplicates:Be.number().int().nonnegative(),rejected:Be.number().int().nonnegative(),skipped:Be.number().int().nonnegative(),analyticsConfig:Ec});import{z}from"zod";import{z as pS}from"zod";var $m=pS.enum(["funnel-run/1","funnel-process/1"]),Gm="funnel-process/1";function Tc(e,t=[]){let n=[];Ut(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(pa(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 Km(e){return e.hidden?null:e.type!=="stack"?e:{...e,children:e.children.flatMap(t=>Km(t)??[])}}function mS(e){let t=e.pages.map(i=>{let a=Km(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(pa({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 Hm(e,t=[]){let n=on.parse(structuredClone(mS(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=Tc(n,t);if(i.length)throw new Error(i.join("; "));return n}import{z as H}from"zod";import{z as M}from"zod";import{z as lt}from"zod";var ja=lt.strictObject({schemaVersion:lt.literal(1),renderKey:lt.string().min(1).max(256),routeTemplate:lt.string().startsWith("/").max(2048),selectors:lt.array(lt.string().regex(/^[a-z][a-z0-9-]*\[(?:id|data-testid|data-test|data-qa|data-indiana-id)="(?:[^"\\\x00-\x1f\x7f]|\\["\\])*"\]$/).max(512)),present:lt.array(lt.number().int().min(0)).min(1),absent:lt.array(lt.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"})}),Qm=lt.strictObject({renderKey:lt.string().min(1).max(256),routeKey:lt.string().min(1).max(256),stateKey:lt.string().min(1).max(256),documentKey:lt.string().min(1).max(256),documentHash:lt.string().regex(/^[a-f0-9]{64}$/),compositionKey:lt.string().min(1).max(256),entryMode:lt.enum(["hard","soft"]),match:lt.strictObject({present:lt.array(lt.number().int().min(0)),absent:lt.array(lt.number().int().min(0))})});import{z as kr}from"zod";var fS=["enterprise-internal-indiana-test","tinkerland-indiana-prod"],Nc="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",gS=kr.string().regex(new RegExp(`^${Nc}/${Nc}/${Nc}/manifest\\.json$`)),Jm=kr.strictObject({kind:kr.literal("gcs-resumable"),url:kr.url(),bucket:kr.enum(fS),objectKey:gS,byteLength:kr.number().int().positive(),expiresAt:kr.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 ft=M.string().min(1).max(256),sn=M.string().regex(/^[a-f0-9]{64}$/),Ta=M.strictObject({versionId:M.uuid(),manifestDigest:sn,sourceGraphDigest:sn,pageKey:ft,stateKey:ft,documentKey:ft,documentHash:sn,elementKey:ft.optional(),nodeId:ft.optional(),contentHash:sn.optional(),renderKey:ft.optional()}),Zm=M.strictObject({pageKey:ft,documentKey:ft,expectedDocumentHash:sn,renderKey:ft.optional(),nodeId:ft,elementKey:ft,expectedContentHash:sn,property:M.enum(["text","fontSize","color"]),value:M.union([M.string().max(4e3),M.number().finite()])}),Wm=M.strictObject({versionId:M.uuid(),manifestDigest:sn,sourceGraphDigest:sn,pageKey:ft,stateKey:ft,documentKey:ft,documentHash:sn,renderKey:ft.optional(),patches:M.array(Zm.omit({pageKey:!0,documentKey:!0,expectedDocumentHash:!0,renderKey:!0})).min(1).max(200)}),hS=/^[a-z][a-z0-9-]{0,39}$/,so=M.string().regex(hS),Fc=M.enum(["web","ios","android"]),U_=M.discriminatedUnion("action",[M.strictObject({action:M.literal("register"),requestId:M.uuid(),client:so,platform:Fc,label:M.string().trim().min(1).max(100),sha256:sn,bytes:M.number().int().min(1),transferBytes:M.number().int().min(1)}),M.strictObject({action:M.literal("complete"),versionId:M.uuid()}),M.strictObject({action:M.literal("current"),versionId:M.uuid(),expectedCurrent:M.uuid().nullable()}),M.strictObject({action:M.literal("delivery"),enabled:M.boolean()}),M.strictObject({action:M.literal("changes"),versionId:M.uuid(),experimentId:M.uuid(),variationId:ft,changesetId:M.uuid().nullable(),expectedRevision:sn.nullable(),editorUrl:M.string().url().max(2048),patches:M.array(Zm).max(200)})]),Mc=M.strictObject({id:M.uuid(),projectId:M.uuid(),environmentId:M.uuid(),clientKey:so,platform:Fc,label:M.string(),sha256:sn,bytes:M.number().int().positive(),objectKey:M.string(),state:M.enum(["uploading","ready","rejected"]),isCurrent:M.boolean(),revision:M.number().int().nonnegative(),createdAt:M.string(),expiresAt:M.string(),readyAt:M.string().nullable(),summary:M.record(M.string(),M.json()),routeTree:M.json().nullable(),validation:M.record(M.string(),M.json())}),AS=M.strictObject({key:so,platform:Fc,currentId:M.uuid().nullable()}),z_=M.strictObject({rows:M.array(Mc).max(100),nextCursor:M.uuid().nullable(),clients:M.array(AS).max(20)}),Dc=M.strictObject({storedBytes:M.number().int().nonnegative(),reservedBytes:M.number().int().nonnegative(),chargedBytes:M.number().int().nonnegative(),versions:M.number().int().nonnegative(),objects:M.number().int().nonnegative(),orphanObjects:M.number().int().nonnegative(),missingReadyObjects:M.number().int().nonnegative(),unknownObjectSizes:M.number().int().nonnegative(),byteLimit:M.number().int().positive(),versionLimit:M.number().int().positive(),remainingBytes:M.number().int().nonnegative()}),$_=M.strictObject({asOf:M.iso.datetime({offset:!0}),reclamation:M.literal("manual-review-required"),buckets:M.strictObject({source:Dc,runtime:Dc,previews:Dc})}),G_=M.strictObject({version:Mc,actorId:M.uuid(),claims:M.record(M.string(),M.json())}),K_=M.strictObject({version:Mc,upload:Jm.nullable()}),H_=M.object({format:M.literal("indiana-route-state-index"),schemaVersion:M.literal(3),routes:M.array(M.object({routeKey:ft,path:M.string(),documentKey:ft,documentHash:sn,initialStateKey:ft,initialRenderKey:ft})),renders:M.array(Qm)}).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"})}),Q_=M.strictObject({rows:M.array(M.object({id:M.uuid(),name:M.string(),status:M.string(),variations:M.array(M.object({id:ft,key:ft,name:M.string().optional()}).loose())}).loose()),limited:M.boolean()}),J_=M.strictObject({enabled:M.boolean(),allowedOrigins:M.array(M.string())});import{z as yi}from"zod";var Ym=yi.strictObject({id:yi.uuid(),name:yi.string().trim().min(1).max(80),client:so,source:Ta,event:yi.enum(["screen_enter","button_click"]),cooldownSeconds:yi.number().int().min(0).max(2592e3),behavior:yi.literal("observe")}).superRefine((e,t)=>{e.event==="button_click"&&(!e.source.nodeId||!e.source.elementKey)&&t.addIssue({code:"custom",path:["source"],message:"Choose a uniquely bound button"})});import{z as $e}from"zod";var qc=Se,yS=["parameters","answers","results","variables"];function Bc(e){return yS.some(t=>e===t||e.startsWith(t+"."))}function Vc(e){let t={};for(let[r,i]of Object.entries(ma(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])=>!Bc(r))),variables:t}}import{z as gt}from"zod";var Na=gt.discriminatedUnion("kind",[gt.object({kind:gt.literal("ledger"),cursor:sa}).strict(),gt.object({kind:gt.literal("billing"),cursor:gt.uuid()}).strict()]),bS=gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),nr=gt.record(gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),gt.union([gt.string().max(500),gt.boolean(),gt.array(gt.string().max(500)).max(50)])).refine(e=>Object.keys(e).length<=40,"Too many answers"),xS=/^(?:api_?key|authorization|password|(?:customer|run|visitor|access|purchase)_?token|client_?secret|signed_?transaction|raw_?proof)$/i;function Lc(e,t=0){return t>20?!0:!!e&&typeof e=="object"&&(Array.isArray(e)?e.some(n=>Lc(n,t+1)):Object.entries(e).some(([n,r])=>["__proto__","constructor","prototype"].includes(n)||xS.test(n)||Lc(r,t+1)))}var SS=/gg_(?:sk|ct|fr|fv|gc)_[A-Za-z0-9_-]{20,}/,rr=gt.record(bS,Se).refine(e=>Object.keys(e).length<=20,"Too many parameters").refine(e=>!Lc(e)&&!SS.test(JSON.stringify(e)),"Credentials cannot be screen parameters");var Xm=gt.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Da=gt.array(gt.object({variable:Xm,componentId:Xm,required:gt.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"),s1=gt.object({bindings:Da,answers:nr,values:gt.record(gt.string(),Se).optional()}).strict();import{z as IS}from"zod";var Fa=IS.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/);var Uc=$e.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),ef=$e.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,128}$/),tf=rr.refine(e=>new TextEncoder().encode(JSON.stringify(e)).byteLength<=8192,"Task data exceeds 8 KiB"),zc=$e.record(Uc,$e.enum(["string","number","boolean","strings"])).refine(e=>Object.keys(e).length<=20,"Too many output fields"),vS=Rn,nf=$e.strictObject({type:$e.literal("external_task"),endpointId:$e.uuid(),taskKey:Uc,inputs:$e.record(Uc,vS).refine(e=>Object.keys(e).length<=20),outputs:zc}),rf=$e.strictObject({maxAttempts:$e.number().int().min(1).max(5),retryDelaySeconds:$e.number().int().min(1).max(30),backoff:$e.enum(["fixed","exponential"]),requestTimeoutSeconds:$e.number().int().min(1).max(10),timeoutSeconds:$e.number().int().min(1).max(300)}).refine(e=>e.requestTimeoutSeconds<=e.timeoutSeconds,"Request timeout exceeds action deadline");var A1=$e.strictObject({outcome:$e.enum(["success","failure"]),data:tf});var y1=$e.discriminatedUnion("operation",[$e.strictObject({operation:$e.literal("signal"),runId:$e.uuid(),nodeId:ef,eventName:Fa,eventId:$e.uuid(),data:tf}),$e.strictObject({operation:$e.literal("read_results"),runId:$e.uuid()})]),b1=$e.strictObject({scope:je,runId:$e.uuid(),eventId:$e.uuid(),accepted:$e.boolean()}),wS=$e.record(ef,qc),x1=$e.strictObject({scope:je,runId:$e.uuid(),results:wS});var wn={flowNodes:500,logicNodes:480,pages:100,components:1500,actions:250,questions:40,documentBytes:1e6,conditionDepth:3,conditionChildren:20,conditionPredicates:100},of="00000000-0000-0000-0000-000000000000";import{z as J}from"zod";import{z as Ze}from"zod";var P1=Ze.enum(["local","remote"]),$c=Ze.strictObject({port:Ze.string().regex(/^[a-zA-Z0-9_.:-]{1,128}$/),value:Se.optional(),sticky:Ze.array(Ze.strictObject({expected:Mi.nullable(),next:Mi})).max(100),exposures:Ze.array(Se).max(100),features:Ze.array(Se).max(100)}),af=Ze.strictObject({type:Ze.literal("evaluate"),receiptId:Ze.uuid(),environmentId:Ze.uuid(),policyRevision:Ze.number().int().nonnegative(),attributes:xt,sticky:Ze.record(Ze.string(),Mi)}),sf=af.extend({runId:Ze.uuid(),versionId:Ze.uuid(),nodeId:Ze.string().min(1).max(64),visit:Ze.number().int().nonnegative(),revision:Ze.number().int().nonnegative()}),Gc=af.omit({type:!0,receiptId:!0}).extend({type:Ze.literal("evaluate_segment")}),cf=Ze.strictObject({nodeId:Ze.string().min(1).max(64),result:$c}),uf=Gc.extend({runId:Ze.uuid(),versionId:Ze.uuid(),nodeId:Ze.string().min(1).max(64),visit:Ze.number().int().nonnegative(),revision:Ze.number().int().nonnegative(),parameters:rr,answers:nr,variables:Ze.record(Ze.string(),Se)});import{z as ce}from"zod";var Kc=ce.array(ce.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"),Ma=ce.intersection(xt,ce.looseObject({tags:Kc.optional()})).refine(e=>!["id","externalUserId","createdAt","ageDays","subscription","parameters","answers","results"].some(t=>Object.hasOwn(e,t)),"Reserved customer attribute"),qa=ce.string().trim().max(80),Ba=ce.string().regex(/^\+[1-9]\d{1,14}$/).nullable(),Va=ce.union([ce.email().max(254),ce.literal("")]),La=ce.string().trim().min(1).max(255).refine(e=>!/\p{Cc}/u.test(e),"Fingerprint must not contain control characters"),lf=ce.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_"),"Reserved guest identity namespace"),df=ce.object({externalUserId:lf.optional(),name:qa.default(""),email:Va.default(""),phone:Ba.optional(),attributes:Ma.default({})}).strict().refine(e=>e.externalUserId!==void 0||e.email!=="","\u8BF7\u63D0\u4F9B\u4E1A\u52A1\u7528\u6237 ID \u6216\u90AE\u7BB1"),jr=ce.discriminatedUnion("type",[ce.strictObject({type:ce.literal("id"),value:ce.uuid()}),ce.strictObject({type:ce.literal("externalUserId"),value:lf})]),bi=ce.strictObject({name:qa.optional(),email:Va.optional(),phone:Ba.optional(),attributes:Ma.optional(),fingerprint:La.optional()}),Ua=e=>!e.customerData||e.customer?.type==="externalUserId",za="customerData requires an externalUserId customer",xi=ce.object({id:ce.uuid(),externalUserId:ce.string().min(1).max(255).nullable(),name:qa,email:Va,phone:Ba.optional(),attributes:Ma,createdAt:ce.iso.datetime()}).strict(),pf=ce.object({customer:xi,changed:ce.boolean(),replayed:ce.boolean()}).strict(),OS=ce.discriminatedUnion("type",[ce.object({type:ce.literal("id"),value:ce.uuid()}).strict(),ce.object({type:ce.literal("externalUserId"),value:ce.string().trim().min(1).max(255)}).strict()]),PS=ce.object({name:qa.optional(),email:Va.optional(),phone:Ba.optional(),attributes:Ma.refine(e=>!Object.hasOwn(e,"tags"),"Use incremental tagChanges").optional(),removeAttributes:ce.array(ce.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,127}$/)).max(128).refine(e=>!e.includes("tags")).optional(),tagChanges:ce.strictObject({add:Kc,remove:Kc}).optional()}).strict().refine(e=>Object.keys(e).length>0,"\u8BF7\u63D0\u4F9B\u9700\u8981\u4FEE\u6539\u7684\u5B57\u6BB5"),Hc=ce.object({lookup:OS}).strict(),mf=Hc.extend({requestId:ce.uuid(),patch:PS}).strict(),ff=ce.object({search:ce.string().trim().max(200).default(""),tag:ce.string().trim().max(40).default(""),planId:ce.string().max(200).default(""),versionId:ce.string().max(200).default(""),holdingStatus:ce.enum(["","active","scheduled","expired","unavailable","none"]).default(""),membershipStatus:ce.enum(["","active","trial","past_due","ended"]).default(""),createdFrom:ce.union([ce.iso.datetime(),ce.literal("")]).default(""),createdUntil:ce.union([ce.iso.datetime(),ce.literal("")]).default(""),offset:ce.coerce.number().int().min(0).max(1e5).default(0),limit:ce.coerce.number().int().min(1).max(100).default(50)}).strict(),gf=ce.object({customers:xi.array(),hasMore:ce.boolean(),total:ce.number().int().nonnegative().nullable(),evaluatedAt:ce.iso.datetime()}).strict();var co=J.discriminatedUnion("type",[J.strictObject({type:J.literal("literal"),value:Se}),J.strictObject({type:J.literal("variable"),key:yt,path:vn.optional()}),J.strictObject({type:J.literal("feature"),featureKey:J.string().min(1).max(128)})]),CS=J.strictObject({requestId:J.uuid(),decisionId:J.uuid(),customerId:J.uuid(),externalUserId:J.string().min(1).max(255).nullable(),versionId:J.uuid(),receiptId:J.uuid(),value:Se}),_S={funnelId:J.uuid(),requestId:J.uuid(),customer:jr,customerData:bi.optional(),attributes:xt.refine(e=>!["parameters","answers","results","variables"].some(t=>Object.hasOwn(e,t)),"parameters, answers, results and variables are reserved flow namespaces")},q1=J.discriminatedUnion("operation",[J.strictObject({operation:J.literal("decide"),..._S}).refine(Ua,za),J.strictObject({operation:J.literal("read_decision"),decisionId:J.uuid()}),J.strictObject({operation:J.literal("evaluate_decision"),decisionId:J.uuid(),requestId:J.uuid(),nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative(),revision:J.number().int().nonnegative(),receiptId:J.uuid(),policyRevision:J.number().int().nonnegative(),generation:J.string().min(1).max(256),result:$c}),J.strictObject({operation:J.literal("feature_config"),funnelId:J.uuid()}),J.strictObject({operation:J.literal("commit_decision_segment"),decisionId:J.uuid(),requestId:J.uuid(),nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative(),revision:J.number().int().nonnegative(),policyRevision:J.number().int().nonnegative(),generation:J.string().min(1).max(256),steps:J.array(cf).max(32),boundary:J.strictObject({nodeId:J.string().min(1).max(64),visit:J.number().int().nonnegative()}).optional()}),J.strictObject({operation:J.literal("segment_configuration"),funnelId:J.uuid(),versionId:J.uuid()}),J.strictObject({operation:J.literal("configuration"),funnelId:J.uuid(),versionId:J.uuid().optional()}),J.strictObject({operation:J.literal("local_configuration"),funnelId:J.uuid()}),J.strictObject({operation:J.literal("report_used"),decisionId:J.uuid(),eventId:J.uuid(),occurredAt:J.iso.datetime({offset:!0}),reference:J.string().min(1).max(128).optional()})]),B1=J.strictObject({scope:je,decisionId:J.uuid(),requestId:J.uuid(),status:J.enum(["pending","completed","failed"]),decision:CS.nullable(),evaluation:J.discriminatedUnion("type",[sf,uf]).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"),V1=J.strictObject({scope:je,decisionId:J.uuid(),eventId:J.uuid(),source:J.literal("caller_reported")});import{z as Nt}from"zod";var hf=Nt.strictObject({type:Nt.literal("bundle"),paywall:Rn.optional(),offering:Rn.optional(),coupons:Rn,data:Rn}),ES=e=>Nt.strictObject({type:Nt.literal(e),id:Nt.uuid()}),K1=Nt.strictObject({type:Nt.literal("bundle"),paywallVersionId:Nt.uuid().optional(),offeringVersionId:Nt.uuid().optional(),couponIds:Nt.array(Nt.uuid()).max(20).refine(e=>new Set(e).size===e.length),data:Se});var H1=Nt.strictObject({type:Nt.literal("bundle"),offering:ES("offering_version").nullable(),paywall:Nt.strictObject({versionId:Nt.uuid(),paywallId:Nt.uuid(),offeringVersionId:Nt.uuid()}).nullable(),coupons:Nt.array(qi).max(20),data:Se});import{z as On}from"zod";import{z as fn}from"zod";var Af=fn.union([fn.string(),fn.number().finite(),fn.boolean(),fn.null()]),RS=fn.union([Af,fn.array(Af).min(1).max(20)]),kS=fn.record(vn,RS).refine(e=>Object.keys(e).length<=10),yf=fn.strictObject({path:vn,type:fn.enum(["string","number","boolean","strings"]),nullable:fn.boolean().optional(),aggregation:fn.enum(["count","exists"]).optional(),where:kS.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 jS=["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"],bf=On.string().regex(/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/),TS=Rn,xf=On.discriminatedUnion("type",[nf,On.strictObject({type:On.literal("claim_offer"),coupon:Rn}),On.strictObject({type:On.literal("event"),event:bf}),On.strictObject({type:On.literal("api"),operation:On.enum(jS),inputs:On.record(vn,TS).refine(e=>Object.keys(e).length<=40),outputs:On.record(bf,yf).refine(e=>Object.keys(e).length<=20)})]);var at=Fa,NS=H.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/),cn={id:at,name:H.string().trim().min(1).max(80),position:H.strictObject({x:H.number().finite(),y:H.number().finite()}).optional()},DS={success:at,cancel:at,unavailable:at,failure:at},Qc=H.url().max(2048).refine(e=>{try{return new URL(e).protocol==="https:"}catch{return!1}},{message:"External pages require HTTPS"}),Jc=H.enum(["same_window","new_window"]),FS=H.discriminatedUnion("type",[H.strictObject({...cn,type:H.literal("entry"),next:at,triggers:H.array(Ym).max(20).refine(e=>new Set(e.map(t=>t.id)).size===e.length,"Entry trigger IDs must be unique").optional()}),H.strictObject({...cn,type:H.literal("screen"),screenId:at,presentation:Gn,outputs:H.record(at,at),offering:H.discriminatedUnion("source",[H.strictObject({source:H.literal("variable"),key:yt}),H.strictObject({source:H.literal("fixed"),versionId:H.uuid()})]).optional()}),H.strictObject({...cn,type:H.literal("offering"),configuration:H.discriminatedUnion("source",[H.strictObject({source:H.literal("fixed"),versionId:H.uuid()}),H.strictObject({source:H.literal("feature"),featureKey:H.string().min(1).max(128)})]),writes:H.strictObject({value:yt}),next:at}),H.strictObject({...cn,type:H.literal("coupon"),couponId:H.uuid(),writes:H.strictObject({value:yt}),next:at}),H.strictObject({...cn,type:H.literal("coupons"),couponIds:H.array(H.uuid()).max(20).refine(e=>new Set(e).size===e.length),writes:H.strictObject({value:yt}),next:at}),H.strictObject({...cn,type:H.literal("output"),value:H.discriminatedUnion("type",[...co.options,hf,H.strictObject({type:H.literal("selection"),screenId:at,offeringKey:yt})])}),H.strictObject({...cn,type:H.literal("condition"),cases:H.array(H.strictObject({condition:Jt,target:at})).min(1).max(50),default:at}),H.strictObject({...cn,type:H.literal("feature"),featureKey:H.string().min(1).max(128),writes:H.strictObject({value:yt}),next:at}),H.strictObject({...cn,type:H.literal("split"),experimentId:H.uuid(),applyPageExperiment:H.literal(!0).optional(),routes:H.record(NS,at).refine(e=>Object.keys(e).length>=2&&Object.keys(e).length<=20),notParticipating:at}),H.strictObject({...cn,type:H.literal("action"),...DS,execution:rf,action:xf,writes:dc.optional()}),H.strictObject({...cn,type:H.literal("external_page"),appManifest:Ta.optional(),url:Qc,openIn:Jc,opened:at,failed:at}),H.strictObject({...cn,type:H.literal("end"),outcome:H.enum(["completed","closed","ineligible","failed"]),output:co.optional()}),H.strictObject({...cn,type:H.literal("wait"),writes:dc.optional(),wait:H.discriminatedUnion("type",[H.strictObject({type:H.literal("duration"),delaySeconds:H.number().int().min(1).max(2592e3),elapsed:at}),H.strictObject({type:H.literal("event"),eventName:at,outputs:zc,timeoutSeconds:H.number().int().min(1).max(2592e3),received:at,timeout:at})])})]),Zc=H.strictObject({version:H.literal(5),entry:at,nodes:H.array(FS).min(1).max(wn.flowNodes)}),Wc=Zc.superRefine((e,t)=>{MS(e,n=>t.addIssue({code:"custom",message:n.message,path:n.path,params:{reason:n.reason}}))});function $a(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 MS(e,t){let n=[],r=new Map(e.nodes.map(l=>[l.id,l])),i=(l,f,m)=>{n.push(l),t?.({message:l,reason:f,path:m?["nodes",e.nodes.indexOf(m)]:[]})};r.size!==e.nodes.length&&i("Node identifiers must be unique","uniqueNodes"),(r.get(e.entry)?.type!=="entry"||e.nodes.filter(l=>l.type==="entry").length!==1)&&i("A flow has exactly one entry node","entry"),(e.nodes.filter(l=>l.type==="screen").length>wn.pages||e.nodes.filter(l=>!["screen","entry","end","output"].includes(l.type)).length>wn.logicNodes)&&i("Flow node limit exceeded","budget");let a=new Set;for(let l of e.nodes){for(let f of $a(l))f===e.entry&&i("An entry cannot be a transition target","entryTarget",l),r.has(f)||i(`Missing target ${f}`,"missingTarget",l);l.type==="screen"&&(a.has(l.screenId)&&i("Every screen has exactly one node owner","screenOwner",l),a.add(l.screenId))}let o=new Set,s=new Set,c=new Set;function u(l){if(o.has(l)){i("Flow edges must not form a cycle","cycle",r.get(l));return}if(!(s.has(l)||!r.has(l))){o.add(l),c.add(l);for(let f of $a(r.get(l)))u(f);o.delete(l),s.add(l)}}u(e.entry);for(let l of e.nodes)c.has(l.id)||i("Every node must be reachable from Entry","unreachable",l);return[...new Set(n)]}var Yc={maxTransitions:1e4,runTimeoutSeconds:2592e3};function Sf(e,t,n){let r=[...t].sort((s,c)=>c.length-s.length),i=new Set,a=(s,c=!1)=>{let u=r.find(l=>s===l||c&&s.startsWith(l+"."));i.add(u??s)};if(e.type==="condition"){let s=n?.startsWith("case_")?Number(n.slice(5)):e.cases.length-1;for(let c of e.cases.slice(0,s+1))for(let u of 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]}import{z as q}from"zod";var Si=q.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,127}$/),Ga=e=>q.record(q.string(),Se).refine(t=>an(t)<=e,"Funnel evidence exceeds its byte budget"),wE=q.enum(["local_segment","evaluation","presentation","timer","event","operation"]),eu=q.enum(["entry","presentation","decision","configuration","capability","wait","terminal"]),tu=q.discriminatedUnion("type",[q.strictObject({type:q.literal("flag"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("experiment"),id:q.uuid()}),q.strictObject({type:q.literal("saved_group"),id:q.uuid()}),q.strictObject({type:q.literal("config"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("constant"),key:q.string().min(1).max(128)}),q.strictObject({type:q.literal("paywall_version"),id:q.uuid()}),q.strictObject({type:q.literal("offering_version"),id:q.uuid()}),q.strictObject({type:q.literal("reward"),id:q.uuid()})]),uo=q.strictObject({schemaVersion:q.literal(1),kind:eu,selector:tu.nullable(),context:Ga(131072),contract:q.strictObject({version:q.number().int().positive(),evaluator:q.string().min(1).max(128),policyRevision:q.number().int().nonnegative()})}).refine(e=>an(e)<=131072,"Node input exceeds its byte budget"),If=q.strictObject({schemaVersion:q.literal(1),kind:eu,outcome:q.enum(["success","cancel","failure","unavailable","elapsed","received","timeout","not_participating"]),data:Ga(131072),route:q.string().regex(/^[a-zA-Z0-9_.-]{1,128}$/).nullable(),evidence:Ga(131072)}).refine(e=>an(e)<=131072,"Node result exceeds its byte budget"),OE=q.strictObject({schemaVersion:q.literal(1),operations:q.record(Si,q.strictObject({attempts:q.number().int().nonnegative(),maxAttempts:q.number().int().min(1).max(5),deadlineAt:q.iso.datetime({offset:!0}),retryAt:q.iso.datetime({offset:!0}).nullable(),error:q.string().regex(/^[a-z_]{1,64}$/).nullable(),reference:q.strictObject({type:Si,id:q.uuid()}).nullable()}))}).refine(e=>an(e)<=65536,"Execution state exceeds its byte budget"),Tr={receiptId:q.uuid()},Xc=q.iso.datetime({offset:!0}),PE=q.discriminatedUnion("type",[q.strictObject({type:q.literal("node_entered"),details:q.strictObject({kind:eu})}),q.strictObject({type:q.literal("presentation_shown"),details:q.strictObject({...Tr,source:q.literal("client"),occurredAt:Xc.optional()})}),q.strictObject({type:q.literal("decision_accepted"),details:q.strictObject(Tr)}),q.strictObject({type:q.literal("signal_received"),details:q.strictObject({signalId:q.uuid(),nodeId:Si,eventName:Si,data:Ga(8192),source:q.literal("server"),occurredAt:Xc})}),q.strictObject({type:q.literal("signal_consumed"),details:q.strictObject({...Tr,signalId:q.uuid()})}),q.strictObject({type:q.literal("wait_elapsed"),details:q.strictObject(Tr)}),q.strictObject({type:q.literal("wait_timeout"),details:q.strictObject(Tr)}),q.strictObject({type:q.literal("operation_completed"),details:q.strictObject({...Tr,operation:Si,reference:q.strictObject({type:Si,id:q.uuid()}).nullable()})}),q.strictObject({type:q.literal("execution_recovered"),details:q.strictObject({generation:q.number().int().positive(),reason:q.enum(["interrupted","expired_lease","delivery_failed"])})}),q.strictObject({type:q.literal("execution_failed"),details:q.strictObject({generation:q.number().int().positive(),code:q.string().regex(/^[a-z_]{1,64}$/)})}),q.strictObject({type:q.literal("run_completed"),details:q.strictObject({outcome:q.enum(["completed","ineligible","failed"])})}),q.strictObject({type:q.literal("run_closed"),details:q.strictObject({source:q.enum(["client","server","expiry"])})}),q.strictObject({type:q.literal("treatment_used"),details:q.strictObject({...Tr,source:q.enum(["client","server"]),occurredAt:Xc,reference:q.string().min(1).max(128).optional()})})]);var gn=z.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),qS=z.discriminatedUnion("type",[z.strictObject({id:gn,type:z.literal("owned"),publicData:qm.optional(),document:on.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")}),z.strictObject({id:gn,type:z.literal("paywall"),paywallVersionId:z.uuid()})]),nu={executionContract:$m.optional(),kind:z.literal("funnel"),schemaVersion:z.literal(4),screens:z.array(qS).max(wn.pages),references:z.record(gn,tu).refine(e=>Object.keys(e).length<=500),inputs:z.array(z.strictObject({variable:gn,screenId:gn,componentId:gn,required:z.boolean()})).max(wn.questions),variables:z.record(yt,ai).refine(e=>Object.keys(e).length<=wn.logicNodes),outputSchema:oi,execution:z.strictObject({runTimeoutSeconds:z.number().int().min(1).max(Yc.runTimeoutSeconds),maxTransitions:z.number().int().min(1).max(Yc.maxTransitions)})},KE=z.strictObject({...nu,graph:Zc});function BS(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 Ha(e){return Array.isArray(e)?e.some(Ha):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t==="productVersionId"?n===of:Ha(n))}function VS(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=Hm(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&&!to(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}),BS(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"&&Ha(i.value.value)||i.type==="end"&&i.output?.type==="literal"&&Ha(i.output.value))&&t.push({message:"Checkout outputs require a Product Version",reason:"product",path:a})}return t}function vf(e,t){for(let{message:n,reason:r,path:i}of VS(e))t.addIssue({code:"custom",message:n,path:i,params:{reason:r}})}function wf(e,t){let n=(h,d,A=[])=>t.addIssue({code:"custom",message:h,path:A,params:{reason:d}}),r=Object.values(e.references),i=new Map(e.screens.map(h=>[h.id,h])),a=(h,d)=>r.some(A=>A.type===h&&("id"in A?A.id:A.key)===d);i.size!==e.screens.length&&n("Screen identifiers must be unique","uniqueScreens");let o=e.graph.nodes.filter(h=>h.type==="screen");(o.length!==i.size||o.some(h=>!i.has(h.screenId)))&&n("Every screen belongs to exactly one presentation node","screenOwner");let s=new Map,c=Object.keys(e.variables);c.some(h=>c.some(d=>h!==d&&d.startsWith(h+".")))&&n("Variable paths must not overlap","variable");function u(h,d){Object.hasOwn(e.variables,h)||n("Every produced variable needs a declaration","variable",["graph","nodes",e.graph.nodes.indexOf(d)]);let A=s.get(h)??new Set;A.add(d.id),s.set(h,A)}for(let[h,d]of e.graph.nodes.entries()){let A=["graph","nodes",h],k=d.type==="feature"?d.featureKey:d.type==="offering"&&d.configuration.source==="feature"?d.configuration.featureKey:d.type==="output"&&d.value.type==="feature"?d.value.featureKey:d.type==="end"&&d.output?.type==="feature"?d.output.featureKey:null;k&&!a("flag",k)&&n("Flag selectors require an explicit GB resource reference","feature",A);let g=d.type==="feature"||d.type==="offering"||d.type==="coupon"||d.type==="coupons"||d.type==="action"&&d.action.type==="api"?["value"]:d.type==="action"&&d.action.type==="external_task"?Object.keys(d.action.outputs):d.type==="wait"&&d.wait.type==="event"?Object.keys(d.wait.outputs):[],y="writes"in d?d.writes??{}:{};(g.length!==Object.keys(y).length||g.some(w=>!Object.hasOwn(y,w))||new Set(Object.values(y)).size!==Object.values(y).length)&&n("Node writes must map every named output exactly once","variable",A);for(let[w,C]of Object.entries(y)){u(C,d);let j=e.variables[C],E=d.type==="offering"?"offering_version":d.type==="coupon"?"reward":d.type==="action"&&d.action.type==="api"?"json":d.type==="action"&&d.action.type==="external_task"?d.action.outputs[w]:d.type==="wait"&&d.wait.type==="event"?d.wait.outputs[w]:void 0;(j?.source.type!=="node"||E&&j.type!==E)&&n("Node writer source or output type does not match declaration","variable",A)}if(d.type==="coupons"){let w=e.variables[d.writes.value];(w?.type!=="array"||w.items?.type!=="reward"||w.items.nullable||w.nullable)&&n("Coupons output requires a non-null Reward array","variable",A);for(let C of d.couponIds)a("reward",C)||n("Coupons require Reward references","coupon",A)}if(d.type==="split"&&!a("experiment",d.experimentId)&&n("Experiment selectors require a GB resource reference","experiment",A),d.type==="coupon"&&!a("reward",d.couponId)&&n("Coupon selectors require a Reward reference","coupon",A),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="literal"){let w=d.action.coupon.value;(!w||typeof w!="object"||Array.isArray(w)||w.type!=="reward"||typeof w.id!="string"||Object.keys(w).length!==2||!a("reward",w.id))&&n("Coupon claims require a Reward reference","coupon",A)}if(d.type==="offering"&&d.configuration.source==="fixed"&&!a("offering_version",d.configuration.versionId)&&n("Offering selectors require an explicit Version reference","offering",A),d.type==="screen"&&d.offering?.source==="variable"&&e.variables[d.offering.key]?.type!=="offering_version"&&n("Screen Offering variable must be an Offering reference","offering",A),d.type==="action"&&d.action.type==="claim_offer"&&d.action.coupon.source==="variable"&&(e.variables[d.action.coupon.key]?.type!=="reward"||d.action.coupon.path)&&n("Coupon variable must be a complete Reward reference","coupon",A),d.type==="screen"){let w=i.get(d.screenId);if(d.offering?.source==="fixed"&&!a("offering_version",d.offering.versionId)&&n("Screen Offering requires an explicit Version reference","offering",A),w?.type==="paywall"&&d.offering&&n("Paywall owns its fixed Offering Version","offering",A),w?.type==="paywall"&&!a("paywall_version",w.paywallVersionId)&&n("Paywall screens require an explicit Version reference","paywall",A),w?.type==="owned"){let C=w.document.pages[0];if(!C){n("Owned screen requires a page","screen",A);continue}er(w.document).some(E=>!E.complete)&&n("Owned screens require complete local content","translations",A);let j=new Set(w.document.actions.map(E=>E.id));(j.size!==Object.keys(d.outputs).length||Object.keys(d.outputs).some(E=>!j.has(E)))&&n("Every screen action requires exactly one outcome route","buttonOutputs",A),$n(C.root,E=>{!d.offering&&(E.type==="plan_picker"||(E.type==="stack"||E.type==="button")&&E.bind?.plan||E.type==="customer_data"&&["customer_plans","credit_packs"].includes(E.data.source))&&n("Product presentation requires an Offering Version","offering",A),E.type==="customer_data"&&Object.values(E.data.outputs??{}).some(ae=>ae!==void 0&&!j.has(ae))&&n("Customer components require declared screen outcomes","componentOutput",A)})}}d.type==="end"&&["completed","ineligible"].includes(d.outcome)&&!d.output&&n("Completed and ineligible ends require a declared output","output",A),d.type==="end"&&d.output?.type==="literal"&&!pn(e.outputSchema,d.output.value)&&n("Terminal output does not match outputSchema","output",A),d.type==="output"&&d.value.type==="literal"&&!pn(e.outputSchema,d.value.value)&&n("Terminal output does not match outputSchema","output",A);let I=d.type==="output"?d.value:d.type==="end"?d.output:void 0;if(I?.type==="variable"&&!I.path){let w=e.variables[I.key];w&&!pc(w,e.outputSchema)&&n("Variable output does not match outputSchema","output",A)}if(d.type==="screen"){let w=i.get(d.screenId);if(w?.type==="owned")for(let C of gc(w.document))(/^(input|params)\./.test(C)||C.startsWith("variables.")&&!fc(C.slice(10),c))&&n("Screen values must reference registered variables","variable",A)}if(d.type==="condition")for(let w of d.cases){for(let C of Ln(w.condition))a("saved_group",C)||n("Conditions require explicit Saved Group references","savedGroup",A);for(let C of Zn(w.condition))C.startsWith("variables.")||n("Funnel conditions read registered variables only","variable",A)}if(d.type==="output"&&d.value.type==="bundle"){e.outputSchema.type!=="json"&&n("Bundle output requires a JSON outputSchema","output",A);for(let[w,C]of[["paywall","paywall_version"],["offering","offering_version"],["coupons","reward"]]){let j=d.value[w];if(j)if(j.source==="literal"){let E=w==="coupons"?j.value:[j.value];(!Array.isArray(E)||E.length>20||E.some(ae=>!pn({type:C,nullable:!1},ae)||!a(C,ae.id))||w==="coupons"&&new Set(E.map(ae=>ae.id)).size!==E.length)&&n("Bundle requires distinct scoped resource references",w==="coupons"?"coupon":w==="paywall"?"paywall":"offering",[...A,"value",w])}else{let E=e.variables[j.key];(j.path||!E||E.nullable||(w==="coupons"?E.type!=="array"||E.items?.type!=="reward"||E.items.nullable:E.type!==C))&&n("Bundle binding type does not match its slot","output",A)}}}}for(let[h,d]of e.graph.nodes.entries()){let A=d.type==="screen"?i.get(d.screenId):void 0,k=[...Sf(d,c),...A?.type==="owned"?fa(A.document).map(g=>fc(g,c)?.key??g):[]];for(let g of new Set(k)){let C=function(j){if(j===d.id)return!0;if(w.has(j))return!1;w.add(j);let E=e.graph.nodes.find(xe=>xe.id===j);return E?(I.has(j)?E.type==="action"?[E.cancel,E.unavailable,E.failure]:E.type==="wait"&&E.wait.type==="event"?[E.wait.timeout]:[]:$a(E)).some(C):!1};var m=C;if(!Object.hasOwn(e.variables,g)){n("Consumed variable is undeclared","variable",["graph","nodes",h]);continue}let y=e.variables[g];if(d.type==="screen"&&y.source.type==="input"&&e.inputs.some(j=>j.screenId===d.screenId&&j.variable===g)||y.source.type==="parameter"||y.source.type==="attribute")continue;let I=y.source.type==="input"?new Set(e.inputs.filter(j=>j.variable===g&&j.required).flatMap(j=>o.filter(E=>E.screenId===j.screenId).map(E=>E.id))):s.get(g)??new Set,w=new Set;(!I.size||C(e.graph.entry))&&n("Every path must produce the consumed variable","resultReference",["graph","nodes",h])}}(new Set(e.inputs.map(h=>h.variable)).size!==e.inputs.length||new Set(e.inputs.map(h=>`${h.screenId}:${h.componentId}`)).size!==e.inputs.length)&&n("Input keys and component bindings must be unique","inputKeys");for(let[h,d]of e.inputs.entries()){e.variables[d.variable]?.source.type!=="input"&&n("Input binding requires a registered input variable","inputBinding",["inputs",h]);let A=i.get(d.screenId),k=A?.type==="owned"?to(A.document,d.componentId):null;if((k?.type!=="stack"||!k.interaction||!["input","toggle","select","multiselect","tabs"].includes(k.interaction.type))&&n("Input requires an interactive control on its owned screen","inputBinding",["inputs",h]),k?.type==="stack"&&k.interaction){let g=k.interaction.type==="toggle"?"boolean":k.interaction.type==="multiselect"?"strings":"string";e.variables[d.variable]?.type!==g&&n("Input variable type does not match component","inputBinding",["inputs",h]);let y=e.variables[d.variable]?.enum;y&&!k.children.filter(I=>!I.hidden).every(I=>y.includes(I.id))&&n("Input choices must match the variable enum","inputBinding",["inputs",h])}}for(let[h,d]of Object.entries(e.variables))d.enum&&d.type!=="string"&&n("Only string variables support enum","variable",["variables",h]),d.source.type==="input"&&!e.inputs.some(A=>A.variable===h)&&n("Input variable requires a component binding","inputBinding",["variables",h]);let l=0,f=0;for(let h of e.screens)if(h.type==="owned"){for(let d of h.document.pages)$n(d.root,()=>{l++});f+=h.document.actions.length}(l>wn.components||f>wn.actions||an(e)>wn.documentBytes)&&n("Funnel document exceeds its budget","budget")}var LS=z.strictObject({...nu,graph:Wc}).superRefine(wf),Ii=z.strictObject({...nu,graph:Wc,displayName:z.string().trim().min(1).max(80)}).superRefine(wf),HE=Ii.superRefine(vf),QE=LS.superRefine(vf),Ka=z.string().regex(Et),lo={requestId:z.uuid(),nodeId:gn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),customerToken:Ka.optional()},US=z.discriminatedUnion("type",[z.strictObject({type:z.literal("screen"),output:gn,answers:nr,selection:z.record(gn,z.union([z.string().max(200),z.boolean(),z.number().int().min(0).max(1e4)])).optional()}),z.strictObject({type:z.literal("paywall_quote"),featureQuantities:z.record(z.uuid(),z.number().int().min(0).max(1e4)).refine(e=>Object.keys(e).length<=100).optional(),actionId:gn,productVersionId:z.uuid(),offerId:z.uuid().optional(),nativeOffer:ui.optional(),predecessor:z.strictObject({operationId:z.uuid().nullable(),generation:z.number().int().positive()}).optional()}),z.strictObject({type:z.literal("paywall_confirm"),operationId:z.uuid()}),z.strictObject({type:z.literal("paywall_cancel"),operationId:z.uuid()}),z.strictObject({type:z.literal("client_action"),receiptId:z.uuid(),outcome:z.enum(["success","cancel","failure","opened","failed"])})]),zS=z.object({nodeId:gn,visit:z.number().int().nonnegative(),revision:z.number().int().nonnegative(),components:z.record(gn,z.object({resourceKey:z.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),page:z.number().int().min(1).max(1e5),after:Na.nullable(),filter:z.enum(["all","purchase","refund","source","usage","debt","settlement","issued","reserved","redeemed","expired","revoked"])}).strict()).refine(e=>Object.keys(e).length<=150)}).strict(),It=z.discriminatedUnion("operation",[z.strictObject({operation:z.literal("start"),funnelId:z.uuid(),requestId:z.uuid(),customer:jr.optional(),customerData:bi.optional(),locale:z.string().min(1).max(35),parameters:rr}).refine(Ua,za),z.strictObject({operation:z.literal("get"),settlementRequestId:z.uuid().optional(),data:zS.optional(),purchase:z.strictObject({receiptId:z.uuid(),operationId:z.uuid()}).optional(),customerToken:Ka.optional()}),z.strictObject({operation:z.literal("resume"),requestId:z.uuid(),customerToken:Ka.optional()}),z.strictObject({operation:z.literal("submit"),...lo,input:US}),z.strictObject({operation:z.literal("back"),...lo}),z.strictObject({operation:z.literal("shown"),...lo}),z.strictObject({operation:z.literal("close"),...lo}),z.strictObject({operation:z.literal("commit_segment"),...lo,policyRevision:z.number().int().nonnegative(),generation:z.string().min(1).max(256)}),z.strictObject({operation:z.literal("review"),receiptId:z.uuid().optional(),customerToken:Ka.optional()})]);function Qa(e,t){let n=new Set,r=new Set,i=new Set,a=[],o=new Map,s=new Map,c=new Map;function u(d){for(let A of Ln(d))l(A)}function l(d){if(i.has(d)||!Object.hasOwn(t.savedGroups,d))return;let A=t.savedGroups[d];A&&(i.add(d),c.set(d,A),a.push(()=>{!Array.isArray(A)&&A.type==="condition"&&u(A.condition)}))}function f(d){for(let A of["hashAttribute","fallbackAttribute"])if(d[A]!==void 0&&Bc(d[A]))throw new Error(`Funnel GB ${A} uses a reserved flow namespace`);u(d.condition);for(let A of d.parentConditions??[])m(A.id),u(A.condition)}function m(d,A=!1){let k=Object.hasOwn(t.features,d)?t.features[d]:void 0;if(!k){if(A)throw new Error("Required GB Feature is unavailable");return}n.has(d)||(n.add(d),o.set(d,k),a.push(()=>{for(let g of k.rules??[]){f(g);for(let y of g.tracks??[])f(y.experiment)}}))}function h(d){let A=Object.hasOwn(t.experiments,d)?t.experiments[d]:void 0;if(!A)throw new Error("Required GB Experiment is unavailable");r.has(d)||(r.add(d),s.set(d,A),a.push(()=>f(A)))}for(let d of e.graph.nodes){d.type==="feature"&&m(d.featureKey,!0),d.type==="split"&&h(d.experimentId),d.type==="condition"&&d.cases.forEach(k=>u(k.condition)),d.type==="offering"&&d.configuration.source==="feature"&&m(d.configuration.featureKey,!0);let A=d.type==="output"?d.value:d.type==="end"?d.output:null;A?.type==="feature"&&m(A.featureKey,!0)}for(let d of a)d();return{...t,features:Object.fromEntries(o),experiments:Object.fromEntries(s),savedGroups:Object.fromEntries(c)}}import{z as ie}from"zod";function Of(e,t){let n=[],r={};Ut(e,i=>{if(i.hidden)return!1;if(i.type!=="quantity_picker")return;let a=i.bind?.plan?[i.bind.plan]:[];i.bind?.picker&&Ut(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 Pf(e,t,n,r){let i=r.plans[t];if(!i?.available)throw new Error("Selected Product is unavailable");let a={};if(Ut(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(l=>l.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}import{z as po}from"zod";var Cf=po.object({defaultLocale:yn,locales:po.record(yn,po.object({name:po.string().max(80),description:po.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 $S=["customer_data","coupon_code"],_f=ie.string().min(1).max(255).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),GS=ie.string().min(1).max(255).regex(/^[a-z0-9][a-z0-9-]*$/),Ja=(e,t)=>new Set(e.map(t)).size===e.length,KS=ie.strictObject({currency:be,amountMinor:ie.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)}),HS=ie.strictObject({featureId:ie.uuid(),name:ie.string().trim().min(1).max(120),allowance:ie.string().max(40).nullable(),access:ie.boolean()}),QS=ie.strictObject({stripe:ie.strictObject({prices:ie.array(KS).min(1).max(50)}).optional(),apple:ie.strictObject({productIds:ie.array(_f).min(1).max(10)}).optional(),google:ie.strictObject({products:ie.array(ie.strictObject({productId:_f,basePlanId:GS.nullable()})).min(1).max(10)}).optional()}).superRefine((e,t)=>{(e.stripe&&!Ja(e.stripe.prices,n=>n.currency)||e.apple&&!Ja(e.apple.productIds,n=>n)||e.google&&!Ja(e.google.products,n=>`${n.productId}:${n.basePlanId}`))&&t.addIssue({code:"custom",message:"Duplicate channel entry"})}),JS=ie.strictObject({name:ie.string().trim().min(1).max(80),interval:ie.enum(["free","week","month","year","one_time"]),intervalCount:ie.number().int().min(1).max(100),trial:ie.strictObject({days:ie.number().int().min(1).max(730),cardRequired:ie.boolean()}).nullable(),benefits:ie.array(HS).max(50).refine(e=>Ja(e,t=>t.featureId),"Duplicate benefit"),channels:QS,prepaid:ie.array(Wi).max(100).optional()}),ZS=ie.strictObject({digest:hi,content:ie.strictObject({discount:Wn,duration:nn,appliesTo:Ys,displayCopy:Cf.nullable(),firstPurchaseOnly:ie.boolean(),qualificationRequired:ie.boolean(),startsAt:ie.iso.datetime().nullable(),endsAt:ie.iso.datetime().nullable(),grantWindowHours:ie.number().int().positive(),perCustomerLimit:ie.number().int().positive()})}),WS=ie.discriminatedUnion("type",[ie.strictObject({type:ie.literal("checkout"),product:Ea}),ie.strictObject({type:ie.literal("close")}),ie.strictObject({type:ie.literal("action"),action:_c})]),Za=ie.strictObject({kind:ie.literal("paywall"),formatVersion:ie.literal(1),name:ie.string().trim().min(1).max(80),offeringVersionId:ie.uuid(),presentation:Gn,screen:on,products:_a,catalog:ie.record(ie.uuid(),JS),buttons:ie.record(Me,WS),coupons:ie.record(ie.uuid(),ZS)}).superRefine((e,t)=>{let n=A=>t.addIssue({code:"custom",message:A}),{screen:r}=e;Of(r,e.catalog).forEach(n),r.surface!=="paywall"&&n("Screen must be a Paywall"),Tc(r,$S).forEach(n),er(r).some(A=>!A.complete)&&n("Every published locale must be complete");let i=new Set,a=new Set,o=new Set;Ut(r,A=>{let k="bind"in A?A.bind:void 0;k?.promotionCode&&n("Promotion codes must not be published"),k?.plan&&i.add(k.plan),k?.coupon&&a.add(k.coupon),A.type==="plan_picker"&&(A.planIds?.forEach(g=>i.add(g)),A.defaultPlan&&i.add(A.defaultPlan)),A.type==="text"&&A.feature&&o.add(A.feature.id)});let s=e.products.items.map(A=>A.productVersionId),c=Object.keys(e.catalog);(s.length!==c.length||s.some(A=>!Object.hasOwn(e.catalog,A)))&&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 A of i)u.has(A)||n("Screen references a Product that is not displayed");for(let A of Object.values(e.catalog))!A.channels.stripe&&!A.channels.apple&&!A.channels.google&&n("A displayed Product needs at least one sales channel");let l=new Set(Object.values(e.catalog).flatMap(A=>A.benefits.map(k=>k.featureId)));for(let A of o)l.has(A)||n("Feature text must read a displayed benefit");let f=r.actions.filter(A=>A.type!=="navigate");r.actions.some(A=>A.type!=="event"&&A.type!=="navigate")&&n("Paywall actions are events or navigation"),(Object.keys(e.buttons).length!==f.length||f.some(A=>!Object.hasOwn(e.buttons,A.id)))&&n("Buttons must match the screen's actions");let h=!1;for(let A of Object.values(e.buttons)){if(A.type!=="checkout")continue;h=!0,(A.product.type==="fixed"?[A.product.productVersionId]:A.product.allowedProductVersionIds).some(g=>!u.has(g))&&n("Checkout may only sell displayed Products")}h||n("A Paywall needs a checkout button");let d=Object.keys(e.coupons);(d.length!==a.size||d.some(A=>!a.has(A)))&&n("Coupons must be exactly the bound Coupons")}),Ef=ie.strictObject({state:ie.enum(["published","archived"]),controlRevision:ie.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),currentVersionId:ie.uuid(),versions:ie.record(ie.uuid(),ie.strictObject({version:ie.number().int().positive(),artifact:ie.string().min(1),sourceDigest:ie.string().regex(/^[a-f0-9]{64}$/)}))}).refine(e=>Object.keys(e.versions).length>0,"Reviewed Paywall Versions are required");var Xt={manifestCdnSeconds:15,maxControlAgeMs:6e4,initializationMs:5e3,maxArtifactBytes:1048576,maxManifestBytes:524288,maxCacheBytes:32*1048576,retentionMs:7*864e5},ru=_e.string().regex(/^[a-f0-9]{64}$/),iu=_e.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),au=je.extend({environmentId:_e.uuid()}),Rf=_e.strictObject({features:_e.array(_e.string()).max(500),experiments:_e.record(_e.uuid(),_e.array(_e.string()).max(20)),savedGroups:_e.array(_e.string()).max(1e3)}),su=_e.strictObject({kind:_e.enum(["funnel","paywall","gb_features","gb_page_experiments"]),formatVersion:_e.number().int().positive(),url:_e.string().min(1).max(2048),sha256:ru,byteLength:_e.number().int().positive().max(Xt.maxArtifactBytes),generation:ru.optional()}),YS=_e.strictObject({state:_e.enum(["active","paused","archived"]),controlRevision:iu,evaluationMode:_e.enum(["local","remote"]),evaluationRevision:iu,currentVersionId:_e.uuid(),versions:_e.record(_e.uuid(),_e.strictObject({artifact:_e.string(),dependencies:Rf,definitionDigest:hi.optional(),couponDigests:_e.record(_e.uuid(),hi).optional()}))}),cu=_e.strictObject({kind:_e.literal("sdk_configuration"),schemaVersion:_e.literal(1),scope:au,revision:iu,generation:ru,policy:_e.strictObject({refreshIntervalSeconds:_e.number().positive().max(15),maxControlAgeSeconds:_e.number().positive().max(60)}),gb:_e.strictObject({features:_e.string().nullable(),pageExperiments:_e.string().nullable()}),artifacts:_e.record(_e.string(),su),funnels:_e.record(_e.uuid(),YS),paywalls:_e.record(_e.uuid(),Ef).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 vt(e){if(Array.isArray(e))return`[${e.map(vt).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)}:${vt(r)}`).join(",")}}`;let t=JSON.stringify(e);if(t===void 0)throw new Error("Configuration must contain JSON values");return t}function uu(e){return Zr(Wr(typeof e=="string"?new TextEncoder().encode(e):e))}function kf(e){return uu(vt(e))}var ou=class extends Error{constructor(n,r){super(n);Fe(this,"dependency",r)}};function jf(e,t){let n=l=>l.type==="feature"?l.featureKey:l.type==="end"&&l.output?.type==="feature"?l.output.featureKey:l.type==="output"&&l.value.type==="feature"?l.value.featureKey:void 0,r=(l,f)=>e.graph.nodes.find(m=>l==="experiment"?m.type==="split"&&m.experimentId===f:l==="feature"&&n(m)===f)?.name,i=(l,f,m=r(f.type,f.resource))=>new ou(l,{...f,...m?{step:m}:{}});for(let l of Object.values(e.references)){let f=l.type==="flag"?!Object.hasOwn(t.features,l.key)||t.remoteFeatures.includes(l.key)?{type:"feature",resource:l.key}:null:l.type==="experiment"?Object.hasOwn(t.experiments,l.id)?null:{type:"experiment",resource:l.id}:l.type==="saved_group"&&!Object.hasOwn(t.savedGroups,l.id)?{type:"saved_group",resource:l.id}:null;if(f)throw i("Funnel dependency is absent from GB public delivery",{reason:"unavailable",...f})}let a=Qa(e,{...t,evaluatedAt:new Date(0).toISOString(),expiresAt:null}),o=new Set(t.remoteFeatures);for(let l of e.graph.nodes){let f=n(l);if(!f)continue;let m=a.features[f],h=l.type==="feature"?e.variables[l.writes.value]:e.outputSchema,d={type:"feature",resource:f};if(!m||!h)throw i("Required public Feature declaration is unavailable",{reason:"unavailable",...d},l.name);if([m.defaultValue,...(m.rules??[]).flatMap(k=>[...Object.hasOwn(k,"force")?[k.force]:[],...k.variations??[],...(k.tracks??[]).flatMap(g=>g.experiment.variations)])].some(k=>k===void 0||!pn(h,k)))throw i("GB Feature values violate the Funnel type contract",{reason:"value_type",...d},l.name)}let s=new Set,c=(l,f)=>{for(let m of Ln(l)){if(s.has(m))continue;let h=t.savedGroups[m];if(!h)throw i("Required public Saved Group is unavailable",{reason:"unavailable",type:"saved_group",resource:m},f);s.add(m),!Array.isArray(h)&&h.type==="condition"&&c(h.condition,f)}},u=(l,f)=>{if(o.has(l)||!t.features[l])throw i("Local Funnel requires public Local prerequisites",{reason:"unavailable",type:"feature",resource:l},f)};for(let l of e.graph.nodes)if(l.type==="condition")for(let f of l.cases)c(f.condition,l.name);for(let[l,f]of Object.entries(a.features)){let m=r("feature",l);for(let h of f.rules??[]){c(h.condition,m);for(let d of[...h.parentConditions??[],...(h.tracks??[]).flatMap(A=>A.experiment.parentConditions??[])])u(d.id,m),c(d.condition,m);for(let d of h.tracks??[])c(d.experiment.condition,m)}}for(let[l,f]of Object.entries(a.experiments)){let m=r("experiment",l);c(f.condition,m);for(let h of f.parentConditions??[])u(h.id,m),c(h.condition,m)}for(let l of e.graph.nodes)if(l.type==="split"){let f=a.experiments[l.experimentId],m={type:"experiment",resource:l.experimentId};if(!f)throw i("Local Funnel requires a public Experiment",{reason:"unavailable",...m},l.name);for(let h of f.variations)if(typeof h!="string"||!Object.hasOwn(l.routes,h))throw i("Experiment variation has no declared Funnel route",{reason:"variation_route",...m},l.name)}return Rf.parse({features:Object.keys(a.features).sort(),experiments:Object.fromEntries(Object.entries(a.experiments).map(([l,f])=>[l,f.variations.map(String)])),savedGroups:[...s].sort()})}function Tf(e){return Ii.parse(e)}var Nf=wt.strictObject({processContext:Aa.optional(),...ci,selector:wt.discriminatedUnion("type",[wt.strictObject({type:wt.literal("paywall"),paywallId:wt.uuid()}),wt.strictObject({type:wt.literal("version"),versionId:wt.uuid()})]),customerId:wt.uuid().optional(),commerce:ri,locale:wt.string().min(1).max(35),requirement:Xn.optional()}),mo=wt.strictObject({id:wt.uuid(),paywallId:wt.uuid(),version:wt.number().int().positive(),document:gi.omit({requirement:!0,offeringId:!0}),offering:wt.strictObject({id:wt.uuid()}),content:wt.strictObject({environmentId:wt.uuid(),offeringVersionId:wt.uuid(),artifact:su.refine(e=>e.kind==="paywall"&&e.formatVersion===1)}).optional(),capabilities:ii,check:Or.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"})}),Nr=wt.strictObject(mo.shape).omit({document:!0,offering:!0}).extend({content:mo.shape.content.unwrap()});function Df(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 mo.parse({...e,capabilities:r,document:{schemaVersion:3,kind:n.kind,name:n.name,presentation:n.presentation,products:n.products,offeringVersionId:n.offeringVersionId,screen:n.screen,buttons:n.buttons},offering:{id:n.offeringVersionId}})}import{z as $t}from"zod";var Ff={requestId:$t.uuid(),sourceId:$t.uuid(),expectedAvailable:Lt},Mf=$t.discriminatedUnion("action",[$t.strictObject({...Ff,action:$t.enum(["add","subtract","set_remaining"]),amount:Ae}),$t.strictObject({...Ff,action:$t.literal("edit"),granted:Ae,expiresAt:$t.iso.datetime({offset:!0}).nullable(),nextResetAt:$t.iso.datetime({offset:!0}).nullable(),expectedRevision:$t.number().int().nonnegative()})]),lu=$t.strictObject({sourceId:$t.uuid(),available:Lt,held:Lt,spent:Lt,adjustmentGrantId:$t.uuid().nullable()}),qf=lu.extend({granted:Lt,expiresAt:$t.iso.datetime({offset:!0}).nullable(),nextResetAt:$t.iso.datetime({offset:!0}).nullable(),revision:$t.number().int().nonnegative()});import{z as un}from"zod";var Bf=un.discriminatedUnion("action",[un.object({action:un.literal("upsert"),externalId:un.string().min(1).max(128),name:un.string().trim().min(1).max(80)}).strict(),un.object({action:un.literal("archive"),entityId:un.uuid()}).strict()]),Vf=un.object({id:un.uuid(),externalId:un.string().min(1).max(128),name:un.string().min(1).max(80),archived:un.boolean()}).strict();import{z as Mt}from"zod";import{z as Fr}from"zod";var Uf=["input","output","cache_read","cache_write","reasoning","input_audio","output_audio"],Lf=Fr.string().regex(/.+\/.+/),du=Fr.number().min(-100),Dr=Fr.string().regex(/^(0|[1-9]\d{0,5})(\.\d{1,12})?$/),XS=Fr.strictObject({input:Dr,output:Dr,cache_read:Dr.optional(),cache_write:Dr.optional(),reasoning:Dr.optional(),input_audio:Dr.optional(),output_audio:Dr.optional()}),pu=(e,t)=>Fr.record(e,t).refine(n=>Object.keys(n).length<=100,"At most 100 AI overrides"),HR=Fr.strictObject({defaultMarkup:du,providerMarkups:pu(Fr.string().min(1),du),modelMarkups:pu(Lf,du),customModels:pu(Lf,XS.partial())});import{z as he}from"zod";var Mr=he.iso.datetime({offset:!0}),ir=he.string().regex(/^-?(0|[1-9]\d{0,23})(\.\d{1,12})?$/),e0=he.discriminatedUnion("kind",[he.object({kind:he.literal("absolute"),from:Mr,to:Mr}).strict(),he.object({kind:he.literal("last_days"),days:he.union([he.literal(1),he.literal(7),he.literal(30),he.literal(90)])}).strict(),he.object({kind:he.literal("billing_cycles"),membershipId:he.uuid(),count:he.number().int().min(1).max(12),includeCurrent:he.boolean()}).strict()]),zf=he.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"),t0=he.object({key:he.string().regex(/^[a-z][a-z0-9_]{0,63}$/),values:he.array(he.string().max(120)).min(1).max(20).refine(e=>new Set(e).size===e.length)}).strict(),qr=he.object({range:e0,timezone:zf,filterBy:he.array(t0).max(5).refine(e=>new Set(e.map(t=>t.key)).size===e.length),interval:he.enum(["hour","day","week","month"]),internal_feature_id:he.uuid().nullable(),entityId:he.uuid().nullable(),topN:he.number().int().min(1).max(50).nullable(),groupBy:he.union([he.enum(["customer","entity","entitlement","source","resource","dimension","plan"]),he.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:he.object({bucket:Mr,group:he.string().max(240),isOther:he.boolean(),internal_feature_id:he.uuid(),resourceId:he.uuid()}).strict().nullable(),limit:he.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)"})}),$f=he.object({from:Mr,to:Mr,interval:he.enum(["hour","day","week","month"]),timezone:zf,rows:he.array(he.object({bucket:Mr,group:he.string().max(240),isOther:he.boolean(),internal_feature_id:he.uuid(),resourceId:he.uuid(),consumedUnits:ir,refundedUnits:ir,reservedUnits:ir,charged:ir,refunded:ir,reserved:ir,netUnits:ir,netCharged:ir}).strict()).max(100),nextCursor:he.object({bucket:Mr,group:he.string().max(240),isOther:he.boolean(),internal_feature_id:he.uuid(),resourceId:he.uuid()}).strict().nullable()}).strict();var vi=Mt.string().regex(/^(0|[1-9]\d{0,29})$/),Gf=Mt.string().regex(/^(0|[1-9]\d{0,29})(\.\d{1,18})?$/),mu=Mt.strictObject({bucket:Mt.iso.datetime({offset:!0}),group:Mt.string().max(240),isOther:Mt.boolean(),internal_feature_id:Mt.uuid()}),Kf=Mt.strictObject({...qr.shape,groupBy:Mt.union([Mt.enum(["customer","entity","entitlement"]),Mt.string().regex(/^properties\.[a-z][a-z0-9_]{0,63}$/)]),after:mu.nullable()}).superRefine((e,t)=>{let n=qr.safeParse({...e,after:null});if(!n.success)for(let r of n.error.issues)t.addIssue({code:"custom",path:r.path,message:r.message})}),Hf=Mt.strictObject({from:Mt.iso.datetime({offset:!0}),to:Mt.iso.datetime({offset:!0}),interval:qr.shape.interval,timezone:qr.shape.timezone,rows:Mt.array(Mt.strictObject({...mu.shape,eventCount:vi,units:Gf,tokenEventCount:vi,tokens:Mt.strictObject(Object.fromEntries(Uf.map(e=>[e,vi]))),totalTokens:vi,providerCostEventCount:vi,providerCostUsd:Gf,invalidTelemetryEventCount:vi})).max(100),nextCursor:mu.nullable()});import{z as ht}from"zod";var Qf=ht.object({requestId:ht.uuid(),items:ht.array(ht.object({customerId:ht.uuid(),command:Gi.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"),Jf=ht.object({batchId:ht.uuid(),after:ht.number().int().min(-1).max(999),limit:ht.number().int().min(1).max(100)}).strict(),Zf=ht.object({batchId:ht.uuid(),status:ht.enum(["queued","complete"]),total:ht.number().int().min(1).max(1e3),processed:ht.number().int().min(0).max(1e3),items:ht.array(ht.object({position:ht.number().int().min(0).max(999),customerId:ht.uuid(),idempotencyKey:ht.string().min(1).max(120),status:ht.enum(["queued","accepted","rejected","failed"]),receipt:Ki.nullable(),errorCode:ht.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:ht.number().int().min(0).max(999).nullable()}).strict();import{z as R}from"zod";var n0=R.enum(["percentage_discount","fixed_discount","free_product","invoice_credits","feature_grant"]),Wf=R.enum(["draft","active","paused","archived"]),Yf=R.string().min(1).max(256),Xf=R.array(Yf).max(50).refine(e=>new Set(e).size===e.length,"Duplicate products"),r0=R.strictObject({duration:R.enum(["day","week","month","year"]),length:R.number().int().min(1).max(3660)}),i0=R.strictObject({internal_feature_id:R.uuid(),allowance:R.number().nonnegative().max(1e15).nullable(),expiry:r0.nullable()}),o0=R.discriminatedUnion("type",[R.strictObject({type:R.literal("feature_grant"),grants:R.array(i0).min(1).max(100).refine(e=>new Set(e.map(t=>t.internal_feature_id)).size===e.length,"Duplicate entitlement grants")}),R.strictObject({type:R.literal("free_product"),productId:Yf,duration:nn}),R.strictObject({type:R.literal("invoice_credits"),amount:R.number().positive().max(1e8),duration:nn,rollover:R.boolean(),productIds:Xf})]),a0=R.string().regex(/^[a-zA-Z0-9_-]{1,64}$/),eg=R.object({key:a0,name:R.string().trim().min(1).max(80),configuration:o0}).strict(),tg=R.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),fu=R.object({code:tg,maxUses:R.number().int().min(1).max(1e6).nullable(),firstPurchaseOnly:R.boolean()}).strict(),ng=R.object({key:R.string().regex(/^[a-z][a-z0-9_]{0,63}$/),name:R.string().trim().min(1).max(80),rewardId:R.uuid(),redeemOn:R.enum(["customer_creation","checkout"]),receivedBy:R.enum(["referrer","all"]),maxRedemptions:R.number().int().min(1).max(1e6).nullable(),productIds:Xf,excludeTrial:R.boolean()}).strict().refine(e=>e.redeemOn==="checkout"||e.productIds.length===0&&!e.excludeTrial,"Purchase restrictions require checkout trigger"),rg={id:R.uuid(),projectId:R.uuid(),environmentId:R.uuid(),revision:R.number().int().nonnegative(),status:Wf,createdAt:R.iso.datetime({offset:!0}),updatedAt:R.iso.datetime({offset:!0})},s0=eg.extend(rg).strict(),c0=ng.safeExtend(rg).strict(),sk=R.strictObject({id:R.uuid(),key:R.string(),name:R.string(),type:n0,status:Wf}),ck=R.discriminatedUnion("action",[R.object({action:R.literal("save"),id:R.uuid().nullable(),revision:R.number().int().nonnegative(),input:eg}).strict(),R.object({action:R.enum(["activate","pause","resume","archive","delete"]),id:R.uuid(),revision:R.number().int().nonnegative()}).strict()]),uk=R.discriminatedUnion("action",[R.object({action:R.literal("save"),id:R.uuid().nullable(),revision:R.number().int().nonnegative(),input:ng}).strict(),R.object({action:R.enum(["activate","pause","resume","archive","delete"]),id:R.uuid(),revision:R.number().int().nonnegative()}).strict()]),ig=R.object({id:R.uuid(),rewardId:R.uuid(),programId:R.uuid().nullable(),customerId:R.uuid(),referrerId:R.uuid().nullable(),status:R.enum(["pending","applied","unavailable"]),result:R.record(R.string(),R.unknown()).nullable(),createdAt:R.iso.datetime({offset:!0})}).strict(),og=R.object({code:tg,requestId:R.uuid()}).strict(),ag=R.strictObject({redemptionId:R.uuid(),currency:be,requestId:R.uuid(),accepted:R.literal(!0)}),u0=R.strictObject({type:R.literal("checkout"),orderId:R.uuid(),productVersionId:R.uuid(),currency:be,duration:nn,renewalAmountMinor:R.number().int().positive().max(1e8),status:R.enum(["created","pending","trialing","paid","cancelled","failed"]),url:R.url().nullable()}),sg=R.discriminatedUnion("type",[u0,R.strictObject({type:R.literal("subscription"),operationId:R.uuid(),membershipId:R.uuid(),productVersionId:R.uuid(),currency:be,duration:nn,renewalAmountMinor:R.number().int().positive().max(1e8),status:R.enum(["pending","running","applied","failed"])})]),cg=R.object({programId:R.uuid(),requestId:R.uuid()}).strict(),ug=R.object({id:R.uuid(),programId:R.uuid(),code:fu.shape.code,createdAt:R.iso.datetime({offset:!0})}).strict(),lk=R.object({rows:R.array(s0).max(100),nextCursor:R.uuid().nullable()}).strict(),dk=R.object({rows:R.array(c0).max(100),nextCursor:R.uuid().nullable()}).strict(),l0=fu.extend({id:R.uuid(),redemptions:R.number().int().nonnegative()}).strict(),d0=R.strictObject({id:R.uuid(),programId:R.uuid().nullable(),customerId:R.uuid().nullable(),referrerId:R.uuid().nullable(),code:R.string().nullable(),status:R.enum(["pending","triggered","applied"]),createdAt:R.iso.datetime({offset:!0})}),pk=R.object({codes:R.array(l0).max(100),redemptions:R.array(d0).max(100),customers:R.record(R.uuid(),R.string()),codesCursor:R.uuid().nullable(),redemptionsCursor:R.uuid().nullable()}).strict(),mk=R.discriminatedUnion("action",[R.object({action:R.literal("create"),rewardId:R.uuid(),revision:R.number().int().nonnegative(),input:fu}).strict(),R.object({action:R.literal("remove"),rewardId:R.uuid(),revision:R.number().int().nonnegative(),codeId:R.uuid()}).strict()]);import{z as v}from"zod";import{z as Z}from"zod";var kn={repositories:20,branches:4,keys:2e3,references:1e4,referencesPerKey:2e3,reportBytes:1048576,files:1e4,sourceBytes:1e8},fo=e=>new Set(e).size===e.length,gu=Z.string().regex(/^[a-zA-Z0-9_.:|-]{1,256}$/),p0=Z.string().max(512).regex(/^[\w.-]+(?:\/[\w.-]+){1,5}$/).refine(e=>!e.split("/").some(t=>t==="."||t==="..")),go=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"))),m0=Z.string().min(1).max(512).refine(e=>!/[\\\u0000-\u001f\u007f]/.test(e)&&!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t==="..")),lg=Z.string().min(1).max(256).regex(/^[a-zA-Z0-9_./*?-]+$/).refine(e=>!e.startsWith("/")&&!e.split("/").some(t=>!t||t==="."||t===".."));var dg=Z.strictObject({id:Z.uuid(),repo:p0,platform:Z.enum(["github","gitlab","bitbucket"]),branches:Z.array(go).min(1).max(4).refine(fo),workflow:Z.string().regex(/^\.github\/workflows\/[a-zA-Z0-9_-]+\.ya?ml$/),keyIds:Z.array(Z.uuid()).min(1).max(4).refine(fo),include:Z.array(lg).min(1).max(16),exclude:Z.array(lg).max(16),methods:Z.array(Z.string().regex(/^[a-zA-Z_$][\w$]{0,63}$/)).min(1).max(32).refine(fo),maxAgeHours:Z.number().int().min(1).max(720)}),pg=dg.extend({revision:Z.number().int().positive()}),hk=Z.strictObject({repository:dg,expectedRevision:Z.number().int().min(0)}).refine(({repository:e})=>e.platform==="gitlab"||e.repo.split("/").length===2,{path:["repository","repo"]}),mg=Z.strictObject({repositoryId:Z.uuid(),branch:go}),f0=Z.array(gu).max(kn.keys).refine(fo),fg=Z.strictObject({repository:pg.omit({keyIds:!0}),branch:go,keys:f0,keySetHash:Z.string().regex(/^[a-f0-9]{64}$/)}),g0=Z.strictObject({filePath:m0,startingLineNumber:Z.number().int().min(1).max(1e7)}),hu=Z.strictObject({protocol:Z.literal(1),repositoryId:Z.uuid(),branch:go,workflow:Z.string().max(200),configurationRevision:Z.number().int().positive(),keySetHash:Z.string().regex(/^[a-f0-9]{64}$/),commit:Z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),scanId:Z.uuid(),runNumber:Z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),runAttempt:Z.number().int().min(1).max(1e4),scannerVersion:Z.literal("1"),scannedAt:Z.iso.datetime({offset:!0}),coverage:Z.strictObject({complete:Z.literal(!0),files:Z.number().int().min(0).max(kn.files),sourceBytes:Z.number().int().min(0).max(kn.sourceBytes),unresolvedCalls:Z.number().int().min(0).max(1e6),unsupportedFiles:Z.number().int().min(0).max(kn.files)}),features:Z.array(Z.strictObject({key:gu,refs:Z.array(g0).max(kn.referencesPerKey)})).max(kn.keys)}).superRefine((e,t)=>{fo(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)>kn.references&&t.addIssue({code:"custom",path:["features"],message:"Reference budget exceeded"})}),Au=Z.strictObject({scanId:Z.uuid(),commit:Z.string(),receivedAt:Z.string(),references:Z.number().int().nonnegative(),removedReferences:Z.number().int().nonnegative()}),h0=Au.extend({repositoryId:Z.uuid(),branch:go,workflow:Z.string(),digest:Z.string(),configurationRevision:Z.number().int().positive(),runNumber:Z.number().int().positive(),runAttempt:Z.number().int().positive(),scannedAt:Z.string(),keySetHash:Z.string(),coverage:hu.shape.coverage}),A0=Z.strictObject({repositories:Z.array(pg).max(kn.repositories),scans:Z.array(h0).max(kn.repositories*kn.branches)}),y0=Z.strictObject({key:gu,references:Z.number().int().nonnegative(),coveredTargets:Z.number().int().nonnegative(),expiredTargets:Z.number().int().nonnegative(),uncertainTargets:Z.number().int().nonnegative()}),Ak=Z.strictObject({available:Z.boolean().default(!0),settings:A0,expectedTargets:Z.number().int().min(0).max(80),features:Z.array(y0).max(2001),truncated:Z.boolean()});import{z as Ot}from"zod";var b0=Ot.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"]),x0=Ot.strictObject({provider:Ot.literal("stripe"),accountId:Ot.string().regex(/^acct_[A-Za-z0-9]+$/),eventId:Ot.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,199}$/),type:b0,occurredAt:Ot.number().int().positive().max(Number.MAX_SAFE_INTEGER),data:Ot.record(Ot.string(),Ot.unknown()).and(Ot.object({id:Ot.string().min(1).max(255),object:Ot.enum(["checkout.session","subscription","invoice","discount","refund","charge"]),livemode:Ot.boolean()}))}),gg=Ot.union([x0,vl]),hg=Ot.strictObject({id:Ot.uuid(),eventId:Ot.string().min(1).max(200),source:Ot.literal("merchant"),providerVerified:Ot.literal(!1),outcome:Ot.string().min(1).max(100)});import{z as Gt}from"zod";var yg={customerId:Gt.uuid(),eventId:Gt.string().trim().min(1).max(200),grantId:Gt.uuid(),occurredAt:Gt.iso.datetime({offset:!0})},bg=Gt.strictObject({...yg,productVersionId:Gt.uuid(),subscriptionId:Gt.string().trim().min(1).max(255)}),xg=Gt.strictObject({...yg,merchandiseId:Gt.uuid()}),Sg=Gt.union([bg,xg]),Ag={id:Gt.uuid(),couponId:Gt.uuid(),status:Gt.literal("redeemed"),source:Gt.literal("merchant"),recordedAt:Gt.iso.datetime({offset:!0})},Ig=Gt.union([bg.extend(Ag),xg.extend(Ag)]);import{z as re}from"zod";var vg=Zp,S0=vg.extend({invoice_id:vg.shape.invoice_id.meta({description:"The Indiana invoice ID to void and replace.",example:"9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"})}),yu=re.strictObject({name:re.string().trim().min(1).max(255),memo:re.string().max(1e4).nullable().optional(),footer:re.string().max(1e4).nullable().optional(),net_terms_days:re.number().int().positive().nullable().optional()}),I0=yu.extend({id:re.string().min(1).max(255),created_at:re.number().nullable()}),wg=re.strictObject({items:re.array(I0).max(50),nextCursor:re.uuid().nullable()}),Pk=re.discriminatedUnion("action",[re.strictObject({action:re.literal("create"),requestId:re.uuid(),values:yu}),re.strictObject({action:re.literal("update"),id:re.string().min(1).max(255),values:yu}),re.strictObject({action:re.literal("delete"),id:re.string().min(1).max(255)})]),Og=re.discriminatedUnion("action",[re.strictObject({action:re.literal("create"),requestId:re.uuid(),params:li}),re.strictObject({action:re.enum(["finalize","send","pay","void"]),requestId:re.uuid(),invoiceId:re.uuid()}),re.strictObject({action:re.literal("reissue"),requestId:re.uuid(),invoiceId:re.uuid(),params:S0})]),bu=re.strictObject({id:re.uuid(),customerId:re.uuid(),providerInvoiceId:re.string().nullable(),status:re.enum(["draft","open","paid","void","uncollectible"]),currency:re.string(),totalMinor:re.string().regex(/^-?\d+$/),paidMinor:re.string().regex(/^\d+$/),refundedMinor:re.string().regex(/^\d+$/),hostedInvoiceUrl:re.url().nullable(),createdAt:re.number(),collectionMethod:re.enum(["send_invoice","charge_automatically"]).nullable()}),Pg=bu.extend({lines:re.array(re.strictObject({id:re.uuid(),description:re.string(),amountMinor:re.string().regex(/^-?\d+$/),netAmountMinor:re.string().regex(/^-?\d+$/),quantity:re.number().nullable(),periodStart:re.number().nullable(),periodEnd:re.number().nullable()})).max(1e3)}),wi=re.strictObject({taskId:re.uuid(),status:re.enum(["ready","running","done","dead"]),invoice:bu.nullable(),errorCode:re.string().nullable()}),Cg=re.strictObject({items:re.array(bu).max(50),nextCursor:re.uuid().nullable(),operations:re.array(wi).max(50),operationsLimited:re.boolean()});var v0=v.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"]),_g={scope:je,permissions:v.array(v0),expiresAt:v.iso.datetime().nullable()},yj=v.discriminatedUnion("kind",[v.object({..._g,kind:v.literal("server"),keyId:v.string().min(1)}),v.object({..._g,kind:v.literal("customer"),customerId:v.string().min(1),identityKind:v.enum(["identified","guest"]),expiresAt:v.iso.datetime()})]),L=v.object({requestId:v.uuid(),scope:je}).strict(),w0=df.safeExtend({fingerprint:La.optional()}).strict(),O0=L.extend({customer:xi,created:v.boolean()});function Eg(){return L.extend({offer:qi.nullable(),reason:_d.nullable()})}var O={sendMessage:{method:"POST",path:"messaging/send",permission:"messaging:write",audience:"server",request:yp,response:L.extend({message:v.object({messageId:v.uuid(),channel:Zi,acceptedAt:v.iso.datetime({offset:!0}),status:v.enum(["accepted","sending","completed","canceled"]),replayed:v.boolean()})})},readMessage:{method:"POST",path:"messaging/read",permission:"messaging:write",audience:"server",request:v.strictObject({messageId:v.uuid()}),response:L.extend({message:v.object({id:v.uuid(),channel:Zi,status:v.enum(["accepted","sending","completed","canceled"]),deliveries:v.array(v.object({id:v.uuid(),status:xp,attempts:v.number().int().nonnegative(),receipts:v.array(v.object({kind:Sp,occurredAt:v.iso.datetime({offset:!0}).nullable()}))}))})})},bindPushInstallation:{method:"POST",path:"push/installations/bind",permission:"messaging:write",audience:"customer",request:sl,response:L.extend({installation:Ar})},readPushInstallation:{method:"POST",path:"push/installations/read",permission:"messaging:write",audience:"customer",request:cl,response:L.extend({installation:Ar})},updatePushAddress:{method:"POST",path:"push/installations/address",permission:"messaging:write",audience:"customer",request:Ro,response:L.extend({installation:Ar})},readMessagingPreference:{method:"POST",path:"messaging/preferences/read",permission:"messaging:write",audience:"customer",request:v.strictObject({channel:Zi}),response:L.extend({preference:ys})},setMessagingPreference:{method:"POST",path:"messaging/preferences/set",permission:"messaging:write",audience:"customer",request:bp,response:L.extend({preference:ys})},listInvoiceTemplates:{method:"POST",path:"invoices/templates",permission:"billing:read",audience:"server",request:v.strictObject({cursor:v.uuid().optional()}),response:L.extend({templates:wg})},previewInvoice:{method:"POST",path:"invoices/preview",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),params:li}),response:L.extend({preview:yc})},createInvoice:{method:"POST",path:"invoices/create",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),requestId:v.uuid(),params:li}).refine(e=>e.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:wi})},manageInvoice:{method:"POST",path:"invoices/manage",permission:"billing:write",audience:"server",request:v.strictObject({customerId:v.uuid(),command:Og}).refine(e=>e.command.action!=="create"||e.command.params.preview!==!0,"Use previewInvoice for a side-effect-free preview"),response:L.extend({operation:wi})},readInvoiceOperation:{method:"POST",path:"invoices/operations/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),taskId:v.uuid()}),response:L.extend({operation:wi})},listInvoices:{method:"POST",path:"invoices/list",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),cursor:v.uuid().optional()}),response:L.extend({invoices:Cg})},getInvoice:{method:"POST",path:"invoices/read",permission:"billing:read",audience:"server",request:v.strictObject({customerId:v.uuid(),invoiceId:v.uuid()}),response:L.extend({invoice:Pg})},getCodeReferenceConfig:{method:"POST",path:"code-references/config",permission:"code-references:read",audience:"server",request:mg,response:L.extend({config:fg})},submitCodeReferences:{method:"POST",path:"code-references",permission:"code-references:write",audience:"server",request:hu,response:L.extend({receipt:Au})},getFeatures:{method:"GET",path:"features",permission:"features:read",audience:"mixed",request:v.strictObject({}),response:L.extend({payload:ao})},evaluateFeatures:{method:"POST",path:"features/evaluate",permission:"features:read",audience:"mixed",request:Lm,response:L.merge(ka)},trackEvents:{method:"POST",path:"events",permission:"events:write",audience:"mixed",request:Um,response:L.merge(zm)},readBalanceSource:{method:"POST",path:"balances/source/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),sourceId:v.uuid()}),response:L.extend({balance:qf})},adjustBalance:{method:"POST",path:"balances/source/adjust",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:Mf}),response:L.extend({balance:lu})},readAiPricing:{method:"POST",path:"ai/pricing/read",permission:"credits:read",audience:"server",request:v.strictObject({internal_feature_id:v.uuid(),customerId:v.uuid().optional(),entityId:v.uuid().optional()}).refine(e=>!e.entityId||!!e.customerId,"Entity pricing requires a customer"),response:L.extend({internal_feature_id:v.uuid(),config:Ts,model_markups:Lo})},readUsage:{method:"POST",path:"usage/read",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid(),query:aa}),response:L.extend({usage:Hi})},setUsage:{method:"POST",path:"usage/set",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:up}),response:L.extend({usage:Hi})},manageBalanceGrant:{method:"POST",path:"balances/grants/manage",permission:"credits:manage",audience:"server",request:v.strictObject({customerId:v.uuid(),command:rp}),response:L.extend({grant:nc})},listBalanceGrants:{method:"POST",path:"balances/grants/list",permission:"credits:read",audience:"server",request:ip,response:L.extend({grants:op})},restoreNativePurchase:{method:"POST",path:"subscriptions/native/restore",permission:"billing:write",audience:"mixed",request:v.union(Em.options.map(e=>e.extend({customerId:v.uuid().optional(),customerToken:v.string().regex(Et).optional()}))),response:L.extend({operation:Rm})},setupPayment:{method:"POST",path:"billing/setup-payment",permission:"billing:write",audience:"mixed",request:ym.extend({customerId:v.uuid().optional()}),response:L.extend({setup:vc})},readPaymentSetup:{method:"POST",path:"billing/payment-setup",permission:"billing:read",audience:"mixed",request:bm.extend({customerId:v.uuid().optional()}),response:L.extend({setup:vc})},previewSubscriptionBatch:{method:"POST",path:"subscriptions/batches/preview",permission:"billing:write",audience:"server",request:gm.safeExtend({customerId:v.uuid()}),response:L.extend({batch:ro})},confirmSubscriptionBatch:{method:"POST",path:"subscriptions/batches/confirm",permission:"billing:write",audience:"server",request:Ia.extend({customerId:v.uuid()}),response:L.extend({batch:ro})},readSubscriptionBatch:{method:"POST",path:"subscriptions/batches/read",permission:"billing:read",audience:"server",request:Ia.extend({customerId:v.uuid()}),response:L.extend({batch:ro})},abandonSubscriptionBatch:{method:"POST",path:"subscriptions/batches/abandon",permission:"billing:write",audience:"server",request:Ia.extend({customerId:v.uuid()}),response:L.extend({batch:ro})},manageSubscriptionTrial:{method:"POST",path:"subscriptions/trials/manage",permission:"billing:write",audience:"server",request:v.discriminatedUnion("action",[va.options[0].extend({customerId:v.uuid()}),va.options[1].extend({customerId:v.uuid()}),va.options[2].extend({customerId:v.uuid()})]),response:L.extend({trial:Ic})},readSubscriptionTrial:{method:"POST",path:"subscriptions/trials/read",permission:"billing:read",audience:"server",request:hm.extend({customerId:v.uuid()}),response:L.extend({trial:Ic})},listSubscriptions:{method:"POST",path:"subscriptions/list",permission:"billing:read",audience:"server",request:Pa,response:L.extend({subscriptions:Pm})},listPurchases:{method:"POST",path:"purchases/list",permission:"billing:read",audience:"server",request:Pa,response:L.extend({purchases:Cm})},listSubscriptionConflicts:{method:"POST",path:"subscriptions/conflicts/list",permission:"billing:read",audience:"server",request:vm,response:L.extend({conflicts:_m})},retrySubscriptionConflict:{method:"POST",path:"subscriptions/conflicts/retry",permission:"billing:write",audience:"server",request:wm,response:L.extend({resolution:Om})},verifySubscriptions:{method:"POST",path:"subscriptions/verify",permission:"billing:read",audience:"server",request:Sm,response:L.extend({verification:Im})},previewAttach:{method:"POST",path:"subscriptions/preview-attach",permission:"billing:read",audience:"mixed",request:sm.safeExtend({...ci,customerId:v.uuid().optional()}),response:L.extend({quote:di})},recordBillingEvent:{method:"POST",path:"billing/events/record",permission:"billing:write",audience:"server",request:gg,response:L.extend({record:hg})},attach:{method:"POST",path:"subscriptions/attach",permission:"billing:write",audience:"mixed",request:Rr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:pi})},readSubscriptionOperation:{method:"POST",path:"subscriptions/operations/read",permission:"billing:read",audience:"mixed",request:Rr.extend({customerId:v.uuid().optional()}),response:L.extend({operation:pi})},previewUpdate:{method:"POST",path:"subscriptions/preview-update",permission:"billing:read",audience:"mixed",request:lm.safeExtend({customerId:v.uuid().optional()}),response:L.extend({quote:pm})},update:{method:"POST",path:"subscriptions/update",permission:"billing:write",audience:"mixed",request:Rr.extend({customerId:v.uuid().optional(),intent:v.enum(["confirm","cancel"]).optional()}),response:L.extend({operation:bc})},readSubscriptionUpdate:{method:"POST",path:"subscriptions/updates/read",permission:"billing:read",audience:"mixed",request:Rr.extend({customerId:v.uuid().optional()}),response:L.extend({operation:bc})},previewRefund:{method:"POST",path:"subscriptions/refunds/preview",permission:"billing:read",audience:"server",request:mm.safeExtend({customerId:v.uuid()}),response:L.extend({quote:xc})},refund:{method:"POST",path:"subscriptions/refunds/confirm",permission:"billing:write",audience:"server",request:Rr.extend({customerId:v.uuid()}),response:L.extend({operation:Sa})},readRefund:{method:"POST",path:"subscriptions/refunds/read",permission:"billing:read",audience:"server",request:Rr.extend({customerId:v.uuid()}),response:L.extend({operation:Sa})},readBillingControls:{method:"POST",path:"billing/controls/read",permission:"billing:read",audience:"customer",request:Ud,response:L.extend({controls:ec})},prepareBillingAuthorization:{method:"POST",path:"billing/authorizations/prepare",permission:"billing:write",audience:"customer",request:Dd,response:L.extend({prepared:Md})},confirmBillingAuthorization:{method:"POST",path:"billing/authorizations/confirm",permission:"billing:write",audience:"customer",request:qd,response:L.extend({authorization:na})},setBillingCoupons:{method:"POST",path:"billing/coupons",permission:"billing:write",audience:"customer",request:Hd,response:L.extend({coupons:Qd})},revokeBillingAuthorization:{method:"POST",path:"billing/authorizations/revoke",permission:"billing:write",audience:"customer",request:Bd,response:L.extend({authorization:na})},listBillingInvoices:{method:"POST",path:"billing/invoices/read",permission:"billing:read",audience:"customer",request:Gd,response:L.extend({invoices:Kd})},prepareBillingAdjustment:{method:"POST",path:"billing/invoices/prepare-adjustment",permission:"billing:write",audience:"server",request:$d.extend({customerId:v.uuid()}),response:L.extend({operation:wi})},confirmBillingAdjustment:{method:"POST",path:"billing/invoices/confirm-adjustment",permission:"billing:write",audience:"customer",request:zd,response:L.extend({invoice:Li})},manageBillingLimits:{method:"POST",path:"billing/controls/manage",permission:"billing:write",audience:"server",request:v.object({customerId:v.uuid(),command:Ld}).strict(),response:L.extend({controls:ec})},manageUsageEntity:{method:"POST",path:"usage/entities",permission:"credits:manage",audience:"server",request:v.object({customerId:v.uuid(),command:Bf}).strict(),response:L.extend({entity:Vf})},readUsageAnalytics:{method:"POST",path:"usage/analytics",permission:"credits:read",audience:"server",request:v.strictObject({customerId:v.uuid().nullable(),query:Kf}),response:L.extend({analytics:Hf})},readCreditAnalytics:{method:"POST",path:"credits/analytics",permission:"credits:read",audience:"server",request:v.object({customerId:v.uuid().nullable(),query:qr}).strict(),response:L.extend({analytics:$f})},submitUsageBatch:{method:"POST",path:"usage/batch",permission:"credits:consume",audience:"server",request:Qf,response:L.extend({batchId:v.uuid()})},readUsageBatch:{method:"POST",path:"usage/batch/read",permission:"credits:read",audience:"server",request:Jf,response:L.extend({batch:Zf})},checkEntitlement:{method:"POST",path:"entitlements/check",permission:"entitlements:read",audience:"mixed",request:wp.extend({customerId:v.string().min(1).optional()}),response:L.extend({check:Or})},resolveContent:{method:"POST",path:"content/resolve",permission:"content:read",audience:"mixed",request:v.strictObject({kind:tr,selector:v.discriminatedUnion("type",[v.strictObject({type:v.literal("resource"),id:v.uuid()}),v.strictObject({type:v.literal("version"),id:v.uuid()})]),customerId:v.string().min(1).optional()}),response:L.extend({content:hc})},resolvePaywall:{method:"POST",path:"paywalls/resolve",permission:"entitlements:read",audience:"mixed",request:Nf,response:L.extend({paywall:Nr})},resolveOffering:{method:"POST",path:"offerings/resolve",permission:"entitlements:read",audience:"mixed",request:v.strictObject({processContext:Aa.optional(),...ci,selector:Nm,customerId:v.string().min(1).optional(),commerce:ri,requirement:Xn.optional()}),response:L.extend({offering:Dm,candidates:v.array(sc).max(20),availability:v.array(v.strictObject({productVersionId:v.uuid(),available:v.boolean(),reason:v.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:Or.nullable()})},readHoldings:{method:"POST",path:"customer-holdings",permission:"entitlements:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),entityId:v.uuid().optional()}).strict(),response:L.extend({holdings:lp})},readLedger:{method:"POST",path:"customer-ledger",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),query:pp}).strict(),response:L.extend({ledger:mp})},readBillingInvoice:{method:"POST",path:"billing/invoices/detail",permission:"billing:read",audience:"mixed",request:ap.extend({customerId:v.uuid().optional()}),response:L.extend({detail:sp})},readCreditStatement:{method:"POST",path:"credit-statements/read",permission:"credits:read",audience:"mixed",request:rc.safeExtend({customerId:v.uuid().optional()}),response:L.extend({statement:cp})},quoteBalance:{method:"POST",path:"balances/quote",permission:"credits:read",audience:"mixed",request:v.object({customerId:v.uuid().optional(),command:Gi.options[0]}).strict(),response:L.extend({quote:ep})},trackUsage:{method:"POST",path:"usage/track",permission:"credits:consume",audience:"server",request:v.strictObject({customerId:v.uuid(),command:v.union([v.strictObject({eventName:v.string().min(1),quantity:Ae.optional(),properties:bt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)}),v.strictObject({internal_feature_id:v.uuid(),quantity:Ae.optional(),properties:bt.optional(),entityId:v.uuid().optional(),idempotencyKey:v.string().min(1).max(120)})])}),response:L.extend({receipts:v.array(Ki).min(1)})},mutateBalance:{method:"POST",path:"balances/execute",permission:"credits:consume",audience:"server",request:v.object({customerId:v.uuid(),command:Gi.refine(e=>e.operation!=="quote","Use the quote endpoint for a read")}).strict(),response:L.extend({receipt:Ki})},redeemReward:{method:"POST",path:"rewards/redeem",permission:"offers:resolve",audience:"customer",request:og,response:L.extend({redemption:ig})},createReferralCode:{method:"POST",path:"rewards/referral-code",permission:"offers:resolve",audience:"customer",request:cg,response:L.extend({referralCode:ug})},claimRewardProduct:{method:"POST",path:"rewards/product/claim",permission:"offers:resolve",audience:"customer",request:ag,response:L.extend({checkout:sg})},readSeats:{method:"POST",path:"seats/list",permission:"customers:read",audience:"server",request:gp,response:L.extend({seats:ac})},manageSeat:{method:"POST",path:"seats/manage",permission:"billing:write",audience:"server",request:hp,response:L.extend({seats:ac})},createCustomer:{method:"POST",path:"customers",permission:"customers:write",audience:"server",request:w0,response:O0},getCustomer:{method:"POST",path:"customers/get",permission:"customers:read",audience:"server",request:Hc,response:L.extend({customer:xi})},listCustomers:{method:"POST",path:"customers/list",permission:"customers:read",audience:"server",request:ff,response:L.extend(gf.shape)},updateCustomer:{method:"POST",path:"customers/update",permission:"customers:write",audience:"server",request:mf,response:L.extend(pf.shape)},createSession:{method:"POST",path:"customer-sessions",permission:"sessions:create",audience:"server",request:v.object({customerId:v.uuid()}).strict(),response:L.extend(Kn.shape)},refreshSession:{method:"POST",path:"customer-sessions/refresh",permission:"sessions:create",audience:"refresh",request:v.strictObject({}),response:L.extend(Kn.shape)},revokeSessions:{method:"POST",path:"customer-sessions/revoke",permission:"sessions:create",audience:"server",request:v.strictObject({customerId:v.uuid(),sessionId:v.uuid().optional()}),response:L.extend({revoked:v.number().int().nonnegative()})},createGuestCustomer:{method:"POST",path:"customers/guests",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),fingerprint:La.optional()}),response:L.extend({customerId:v.uuid(),guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),guestExpiresAt:v.iso.datetime()})},resumeGuestSession:{method:"POST",path:"customers/guests/session",permission:"sessions:create",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/)}),response:L.extend(Kn.shape)},claimGuestCustomer:{method:"POST",path:"customers/guests/claim",permission:"customers:write",audience:"server",request:v.strictObject({guestToken:v.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),externalUserId:v.string().trim().min(1).max(255).refine(e=>!e.startsWith("gg_guest_")),requestId:v.uuid()}),response:L.extend({customer:xi,switched:v.boolean(),replayed:v.boolean()})},redeemCoupon:{method:"POST",path:"offers/redeem",permission:"offers:resolve",audience:"customer",request:v.strictObject({code:v.string().regex(/^[A-Z0-9][A-Z0-9_-]{2,31}$/),requestId:v.uuid()}),response:Eg()},listOffers:{method:"GET",path:"offers",permission:"offers:resolve",audience:"customer",request:v.object({}).strict(),response:L.extend({offers:v.array(qi)})},grantOffer:{method:"POST",path:"offers/grant",permission:"offers:grant",audience:"mixed",customerPermission:"offers:resolve",request:v.object({customerId:v.string().min(1).max(255).optional(),couponId:v.uuid(),...ci,requestId:v.uuid(),couponContentDigest:v.string().regex(/^[a-f0-9]{64}$/).optional()}).strict(),response:Eg()},recordCouponRedemption:{method:"POST",path:"offers/redemptions",permission:"billing:write",audience:"server",request:Sg,response:L.extend({receipt:Ig})}},bj={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};import{z as xu}from"zod";var ho=class extends Error{constructor(t){super(t),this.name="FunnelCalculationError"}};function Su(e,t,n){let r={},i,a,o,s="next",c;switch(e.type){case"entry":c=e.next;break;case"condition":{let u=e.cases.findIndex(l=>Wt(t.attributes??{},l.condition,t.savedGroups??{}));s=u<0?"default":`case:${u}`,c=u<0?e.default:e.cases[u].target;break}case"feature":if(!Object.hasOwn(t.features??{},e.featureKey))throw new ho("Required GB Feature is unavailable");i=Vn(e.featureKey,t),o=i.value,Object.assign(r,si(e,{value:o})),c=e.next;break;case"split":{let u=n[e.experimentId];if(!u)throw new ho("Required GB Experiment is unavailable");if(a=ea(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 ho("Experiment Variation has no published route");break}case"offering":{let u=e.configuration.source==="fixed"?e.configuration.versionId:Vn(e.configuration.featureKey,t).value;o={type:"offering_version",id:xu.uuid().parse(u)},Object.assign(r,si(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,si(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 Rg(e,t,n){xu.uuid().parse(e),xu.number().int().nonnegative().parse(t);let r=Zr(Wr(new TextEncoder().encode(JSON.stringify([e,t,n])))).slice(0,32);return`${r.slice(0,8)}-${r.slice(8,12)}-5${r.slice(13,16)}-a${r.slice(17,20)}-${r.slice(20)}`}import{z as K}from"zod";var or=K.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),P0=K.enum(["running","waiting","completed","closed","ineligible","failed"]),Iu=K.discriminatedUnion("type",[Gc,K.strictObject({type:K.literal("wait"),receiptId:K.uuid(),kind:K.enum(["timer","event","operation"]),deadline:K.iso.datetime({offset:!0}).nullable(),eventName:or.optional()}),K.strictObject({type:K.literal("open_url"),receiptId:K.uuid(),url:Qc,openIn:Jc}),K.strictObject({type:K.literal("event"),receiptId:K.uuid(),event:or})]),Wa=K.strictObject({type:K.literal("funnel"),id:K.uuid(),versionId:K.uuid()}),C0={id:or,presentation:Gn,outputs:K.array(or).max(250),inputs:Da,values:K.record(K.string(),Se).optional(),offeringKey:yt.optional(),capabilities:ii,customerData:kp,dataCursors:K.record(or,Na.nullable())},_0=K.strictObject({...C0,content:K.strictObject({type:K.literal("document"),document:on})}),Ao=K.strictObject({id:K.uuid(),source:Wa,revision:K.number().int().nonnegative(),visit:K.number().int().nonnegative(),nodeId:or,nodeType:K.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),status:P0,stopped:K.boolean(),canBack:K.boolean(),authenticated:K.boolean(),locale:K.string().min(1).max(35),answers:nr,parameters:rr,variables:K.record(K.string(),Se),output:Se.nullable(),screen:_0.nullable(),paywall:K.strictObject({receiptId:K.uuid(),resolution:K.union([mo,Nr]),quote:di.nullable(),operation:pi.nullable(),purchaseRequestId:K.uuid().nullable(),selectionGeneration:K.number().int().nonnegative().optional(),canReselect:K.boolean().optional()}).nullable(),instruction:Iu.nullable(),pendingRequest:K.strictObject({requestId:K.uuid(),authenticationRequired:K.boolean()}).nullable(),runExpiresAt:K.iso.datetime({offset:!0}),credentialExpiresAt:K.iso.datetime({offset:!0}).nullable()}),Ya=K.strictObject({scope:je,run:Ao,settlement:K.strictObject({requestId:K.uuid(),state:K.enum(["pending","unknown","settled"]),operationId:K.uuid().nullable(),receiptId:K.uuid().nullable().optional()}).optional(),purchase:K.strictObject({receiptId:K.uuid(),quote:di.nullable(),operation:pi.nullable(),canReselect:K.boolean().optional()}).optional(),review:K.strictObject({activeOperationId:K.uuid().nullable(),pages:K.array(K.strictObject({receiptId:K.uuid(),nodeId:or,visit:K.number().int().nonnegative()})).max(100),page:K.strictObject({receiptId:K.uuid(),nodeId:or,visit:K.number().int().nonnegative(),document:on,answers:nr,inputs:Da,values:K.record(K.string(),Se).optional()}).nullable(),coupons:K.array(K.strictObject({grantId:K.uuid(),status:K.enum(["issued","reserved","redeemed","expired","revoked","unknown"]),expiresAt:K.string().nullable()})).max(100),purchases:K.array(K.strictObject({receiptId:K.uuid(),operationId:K.uuid(),status:K.enum(["pending","complete","cancelled","failed","unknown"])})).max(100)}).optional(),runToken:K.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/).optional(),customerId:K.uuid().optional()}),kg=Ya.extend({run:Ao.extend({paywall:Ao.shape.paywall.unwrap().extend({resolution:Nr}).nullable()})});var jg="X-Indiana-Server-Key";import{z as oe}from"zod";import{z as ge}from"zod";import{z as Pt}from"zod";var E0=Pt.strictObject({selector:Pt.string().min(1).max(2048),action:Pt.enum(["set","append","remove"]),attribute:Pt.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:Pt.string().max(5e4).optional(),parentSelector:Pt.string().max(2048).optional(),insertBeforeSelector:Pt.string().max(2048).optional()}),R0=Pt.strictObject({variation:Pt.string().min(1).max(128),description:Pt.string().max(2e3).default(""),css:Pt.string().max(1e5).default(""),js:Pt.string().max(1e5).default(""),domMutations:Pt.array(E0).max(200).default([]),iam:Wm.optional(),renderGuard:ja.optional()}),vu=R0.omit({variation:!0,description:!0,iam:!0}),k0=Ai.omit({variations:!0,active:!0}).extend({changeId:Pt.string().regex(/^[a-f0-9]{64}$/),variations:Pt.tuple([vu,vu]).rest(vu).refine(e=>e.length<=20)}),Tg=Pt.strictObject({trackExposures:Pt.boolean(),environmentId:Pt.uuid(),generation:Pt.string().regex(/^[a-f0-9]{64}$/),experiments:Pt.array(k0).max(100),savedGroups:oo});var yo=ge.string().regex(/^[a-f0-9]{64}$/),Xj=ge.strictObject({iam:yo,executionContracts:ge.union([ge.tuple([ge.literal("funnel-run/1")]),ge.tuple([ge.literal("funnel-process/1")])]).default(["funnel-run/1"])}),j0=ge.strictObject({release:yo,render:ja,button:ge.strictObject({selector:ge.string().min(1).max(512),elementKey:ge.string().min(1).max(256),tag:ge.enum(["button","a","input"])}).nullable()}),eT=ge.strictObject({scope:je.extend({environmentId:ge.uuid()}),release:yo,validatedAt:ge.iso.datetime({offset:!0}),validUntil:ge.iso.datetime({offset:!0}),entries:ge.array(ge.strictObject({id:ge.uuid(),funnelId:ge.uuid(),versionId:ge.uuid(),event:ge.enum(["screen_enter","button_click"]),target:j0})).max(4e3)}),Ng=ge.strictObject({operation:ge.literal("entry_start"),funnelId:ge.uuid(),versionId:ge.uuid(),entryId:ge.uuid(),release:yo,requestId:ge.uuid(),locale:ge.string().min(1).max(35).default("en")}),Dg=ge.strictObject({scope:je,suppressed:ge.literal(!0),reason:ge.enum(["frequency","in_progress"]),retryAt:ge.iso.datetime({offset:!0}).nullable()}),tT=ge.strictObject({experimentId:ge.uuid(),splitNodeId:ge.string().min(1).max(128)}),T0=ge.strictObject({experimentId:ge.uuid(),experimentKey:ge.string().min(1).max(128),variationKey:ge.string().min(1).max(128),inExperiment:ge.boolean(),generation:ge.string().min(1).max(256)}),bo=ge.strictObject({operation:ge.literal("page_experiments"),release:yo,usedReceiptIds:ge.array(ge.uuid()).max(20).default([]),customerToken:ge.string().regex(Et).optional()}),Fg=ge.strictObject({scope:je,runId:ge.uuid(),assignments:ge.array(T0.extend({receiptId:ge.uuid()})).max(100),payload:Tg});var Pn=oe.literal(Gm),N0=oe.string().regex(/^gg_fr_[A-Za-z0-9_-]{43}$/),wu=oe.string().regex(/^gg_gc_[A-Za-z0-9_-]{43}$/),Mg=oe.discriminatedUnion("type",[oe.strictObject({type:oe.literal("guest"),guestToken:wu}),oe.strictObject({type:oe.literal("customer"),customer:jr,customerData:bi.optional()})]),Ou=oe.strictObject({id:oe.uuid(),runId:oe.uuid(),customerId:oe.uuid(),requestId:oe.uuid(),acceptedAt:oe.iso.datetime({offset:!0})}),D0=oe.strictObject({participantId:oe.uuid(),startedAs:oe.enum(["guest","identified"]),binding:Ou.omit({runId:!0,requestId:!0}).nullable()}),F0=oe.union([Iu,oe.strictObject({type:oe.literal("authentication_required"),reason:oe.enum(["customer_required","customer_experiment_required"]),nodeId:oe.string().min(1).max(64),visit:oe.number().int().nonnegative()})]),M0=Ao.omit({authenticated:!0}).extend({identity:D0,instruction:F0.nullable()}),q0=oe.discriminatedUnion("operation",[It.options[2].omit({customerToken:!0}),It.options[3].omit({customerToken:!0}),It.options[4].omit({customerToken:!0}),It.options[5].omit({customerToken:!0}),It.options[6].omit({customerToken:!0}),It.options[7].omit({customerToken:!0})]),Xa={contract:Pn,customerToken:oe.string().regex(Et)},qg={contract:Pn,requestId:oe.uuid(),runToken:N0,externalUserId:jr.options[1].shape.value},Bg=oe.discriminatedUnion("operation",[oe.strictObject({contract:Pn,operation:oe.literal("describe")}),oe.strictObject({contract:Pn,operation:oe.literal("start"),source:Mg,funnelId:It.options[0].shape.funnelId,requestId:oe.uuid(),locale:It.options[0].shape.locale,parameters:It.options[0].shape.parameters}),Ng.omit({operation:!0}).extend({contract:Pn,operation:oe.literal("entry_start"),source:Mg}),oe.strictObject({...qg,operation:oe.literal("bind_customer"),guestToken:wu,claimRequestId:oe.uuid(),expectedBindingId:oe.null()}),oe.strictObject({...qg,operation:oe.literal("binding_status"),guestToken:wu.optional()}),It.options[1].omit({operation:!0,customerToken:!0}).extend({...Xa,operation:oe.literal("get"),settlementBindingId:oe.uuid().nullable().optional()}),It.options[8].omit({operation:!0,customerToken:!0}).extend({...Xa,operation:oe.literal("review")}),bo.omit({customerToken:!0}).extend(Xa),oe.strictObject({...Xa,operation:oe.literal("command"),identity:oe.strictObject({bindingId:oe.uuid().nullable()}),command:q0})]),Pu=Ya.omit({run:!0}).extend({contract:Pn,run:M0,settlement:Ya.shape.settlement.unwrap().extend({accepted:oe.boolean().nullable().optional()}).optional()}),dT=Dg.extend({contract:Pn}),pT=oe.discriminatedUnion("operation",[Bg.options[1].omit({contract:!0,source:!0,requestId:!0}),Bg.options[2].omit({contract:!0,source:!0,requestId:!0})]),mT=Pu.extend({binding:Ou,outcome:oe.enum(["bound","already_bound"]),replayed:oe.boolean()}),fT=oe.discriminatedUnion("state",[oe.strictObject({contract:Pn,scope:je,state:oe.literal("not_accepted")}),oe.strictObject({contract:Pn,scope:je,state:oe.literal("conflict")}),oe.strictObject({contract:Pn,scope:je,state:oe.literal("bound"),binding:Ou})]),gT=oe.strictObject({contract:Pn,scope:je,keyId:oe.uuid(),operations:oe.array(oe.string()).max(20)});import{z as Ne}from"zod";var Oi=Ne.string().regex(/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/),Lg=Ne.strictObject({entry:Oi,nodes:Ne.array(Ne.strictObject({id:Oi,type:Ne.enum(["entry","screen","condition","split","feature","action","external_page","wait","end","offering","coupon","coupons","output"]),outputs:Ne.record(Ne.string(),Oi),writes:Ne.record(yt,yt),resources:Ne.strictObject({screenId:Oi.optional(),paywallVersionId:Ne.uuid().optional(),couponId:Ne.uuid().optional(),couponIds:Ne.array(Ne.uuid()).max(20).optional(),experimentId:Ne.uuid().optional(),featureKey:Ne.string().optional(),offeringVersionId:Ne.uuid().optional()})})).min(1).max(500)}),Vg={scope:je,funnelId:Ne.uuid(),versionId:Ne.uuid(),evaluationRevision:Ne.number().int().nonnegative(),expiresAt:Ne.iso.datetime({offset:!0}).nullable(),topology:Lg},es=Ne.discriminatedUnion("evaluationMode",[Ne.strictObject({...Vg,evaluationMode:Ne.literal("local"),growth:mn,conditions:Ne.record(Oi,Ne.array(Ne.strictObject({condition:Jt,port:Ne.string()})))}),Ne.strictObject({...Vg,evaluationMode:Ne.literal("remote")})]),B0=es.options[0].extend({evaluation:Ne.strictObject({maxTransitions:Ne.number().int().min(1).max(1e4),variables:Ne.record(yt,ai),outputSchema:oi,terminals:Ne.record(Oi,Ne.strictObject({outcome:Ne.enum(["completed","closed","ineligible","failed"]),output:co.nullable()}))})});function V0(e){return Lg.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=Ne.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 Cu(e){let t=Ii.parse(e.document),n=e.evaluationMode==="local"?mn.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:V0(t)};return es.parse(e.evaluationMode==="remote"?r:{...r,growth:Qa(t,n),conditions:Object.fromEntries(t.graph.nodes.filter(i=>i.type==="condition").map(i=>[i.id,i.cases.map((a,o)=>({condition:a.condition,port:`case:${o}`}))]))})}function Ug(e){let t=Cu(e);if(t.evaluationMode!=="local")throw new Error("Remote Funnel cannot disclose local rules");let n=Ii.parse(e.document);return B0.parse({...t,evaluation:{maxTransitions:n.execution.maxTransitions,variables:n.variables,outputSchema:n.outputSchema,terminals:Object.fromEntries(n.graph.nodes.flatMap(r=>{let i=r.type==="end"?r.output:r.type==="output"?r.value:void 0;return r.type!=="end"&&r.type!=="output"?[]:i&&i.type!=="literal"&&i.type!=="feature"&&i.type!=="variable"?[]:[[r.id,{outcome:r.type==="end"?r.outcome:"completed",output:i??null}]]}))}})}import{z as tt}from"zod";var zg=tt.string().regex(/^[a-f0-9]{64}$/),L0=Ai.omit({variations:!0,active:!0}).extend({changeId:zg,variations:tt.array(tt.strictObject({urlRedirect:tt.string().max(2048)})).min(2).max(20)}),$g=tt.strictObject({environmentId:tt.uuid(),trackExposures:tt.boolean(),generation:zg,experiments:tt.array(L0).max(100),savedGroups:oo}),U0=tt.strictObject({eventUuid:tt.uuid(),timestamp:tt.iso.datetime({offset:!0}).optional(),deviceId:tt.string().min(1).max(128),sessionId:tt.string().min(1).max(128).optional(),url:tt.url().max(2048),pageTitle:tt.string().max(512).optional(),experimentKey:tt.string().min(1).max(255),variationKey:tt.string().min(1).max(64)}),_T=tt.strictObject({events:tt.array(U0).min(1).max(20)}),ET=tt.strictObject({inserted:tt.number().int().nonnegative(),duplicates:tt.number().int().nonnegative(),skipped:tt.number().int().nonnegative(),rejected:tt.array(tt.strictObject({index:tt.number().int().nonnegative(),reason:tt.string()}))});import{z as st}from"zod";var Eu=32,z0=522240;function Ru(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=st.strictObject({nodeId:st.string().min(1).max(64),visit:st.number().int().nonnegative(),revision:st.number().int().nonnegative()}),_u=st.record(st.string(),Se),G0=st.strictObject({id:st.uuid(),nodeId:st.string().min(1).max(64),visit:st.number().int().nonnegative(),input:st.strictObject({schemaVersion:uo.shape.schemaVersion,kind:uo.shape.kind,selector:uo.shape.selector,contract:uo.shape.contract}),context:_u,removed:st.array(st.string()).max(100),attributes:_u,removedAttributes:st.array(st.string()).max(100),result:If,offeringVersionId:st.uuid().nullable(),events:st.strictObject({entered:st.string().regex(/^[1-9][0-9]{0,18}$/),decision:st.string().regex(/^[1-9][0-9]{0,18}$/).nullable()})}),DT=st.strictObject({schemaVersion:st.literal(1),mode:st.enum(["local","remote"]),versionId:st.uuid(),generation:st.number().int().positive(),base:$0,context:_u,steps:st.array(G0).min(1).max(Eu)}).refine(e=>an(e)<=z0,"Segment exceeds its byte budget");var K0=/^(parameters(?:\.|$)|answers(?:\.|$)|results(?:\.|$)|variables(?:\.|$)|funnelParticipantId$)/;function xo(e){return Array.isArray(e)?e.some(xo):!e||typeof e!="object"?!1:Object.entries(e).some(([t,n])=>t.startsWith("$")?["$and","$or","$nor","$not"].includes(t)&&xo(n):!K0.test(t))}function Gg(e,t,n,r){if(e.executionContract!=="funnel-process/1"||r)return null;if(["offering","coupon","coupons"].includes(t.type)||t.type==="action"&&t.action.type!=="event"||t.type==="screen"&&(t.offering||e.screens.some(s=>s.id===t.screenId&&s.type==="paywall")))return"customer_required";let i=t.type==="end"?t.output:t.type==="output"?t.value:void 0;if(i&&["bundle","selection","offering"].includes(i.type)||t.type==="condition"&&t.cases.some(s=>xo(s.condition)))return"customer_required";let a=JSON.stringify([t,t.type==="screen"?e.screens.find(s=>s.id===t.screenId):null]);for(let[s,c]of Object.entries(e.variables))if(c.source.type==="attribute"&&c.source.key!=="funnelParticipantId"&&(a.includes(`variables.${s}`)||a.includes(JSON.stringify(s))))return"customer_required";if(t.type==="split"){let s=n.experiments?.[t.experimentId];if((s?.hashAttribute??"id")!=="funnelParticipantId"||xo(s?.condition)||s?.parentConditions?.length)return"customer_experiment_required"}let o=t.type==="feature"?t.featureKey:i?.type==="feature"?i.featureKey:void 0;return o&&n.features?.[o]?.rules?.some(s=>(s.hashAttribute??"id")!=="funnelParticipantId"||xo(s.condition)||s.parentConditions?.length)?"customer_experiment_required":null}var ku=class extends Error{constructor(n,r){super(r);Fe(this,"code",n);this.name="FunnelLocalCalculationError"}},Kg=(e,t)=>new ku(e,t),H0=e=>({experiments:e.experiments,features:e.features});function Q0(e,t=Kg){let n=new Map(e.topology.nodes.map(o=>[o.id,o])),r=Yr(e.growth.savedGroups),i=H0(e.growth);function a(o,s){if(!Object.hasOwn(e.growth.features,o))throw t("INVALID_RESPONSE","Required GB Feature is unavailable");return Vn(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,l;if(c.type==="condition"){let m=e.conditions[c.id];if(!m)throw t("INVALID_RESPONSE","Local condition rules are unavailable");u=Su({id:c.id,name:c.id,type:"condition",cases:m.map(h=>({condition:h.condition,target:c.outputs[h.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");l=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 h=Su({id:c.id,name:c.id,type:"split",experimentId:c.resources.experimentId,routes:c.outputs,notParticipating:c.outputs.notParticipating},s,i.experiments);l=h.value,u=h.port}else if(["offering","end","output"].includes(c.type)&&c.resources.featureKey)l=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 f=c.outputs[u]??(u==="value"?c.id:void 0);if(!f)throw t("INVALID_RESPONSE","Evaluated node exit is unavailable");return{nodeId:o,port:u,target:f,...l===void 0?{}:{value:l}}}}}function J0(e,t){let n=es.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=Q0(n,t);return(o,s)=>(i(),Z0(a,o,s))}function Z0(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 W0(e,t,n){let r=[],i=[],a=[],o=e(t,{...n.attributes?{attributes:n.attributes}:{},stickyBucketAssignmentDocs:n.sticky,saveStickyBucketAssignmentDoc(s){let c=r.findIndex(f=>f.next.attributeName===s.attributeName&&f.next.attributeValue===s.attributeValue),u=s.attributeName+"||"+s.attributeValue,l={expected:n.sticky[u]??null,next:s};c<0?r.push(l):r[c]=l},onExperimentViewed(s,c){c.inExperiment&&c.hashUsed&&!c.passthrough&&i.push(Se.parse({key:s.key,variationId:c.variationId,keyUsed:c.key,hashAttribute:c.hashAttribute,hashValue:c.hashValue}))},onFeatureUsage(s,c){a.push(Se.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 Hg(e,t,n,r=Kg){let i=n,a=new Map(t.graph.nodes.map(k=>[k.id,k])),o=structuredClone(n.variables),s=structuredClone(i.sticky),c=[],u=n.nodeId,l=n.visit,f=!1,m,h=k=>Gg(t,k,e.evaluationMode==="local"?e.growth:{features:{},experiments:{}},i.attributes.funnelCustomerBound===!0),d=k=>(m??(m=J0(e,r)),W0(m,k,{attributes:Vc({declarations:t.variables,attributes:i.attributes,parameters:n.parameters,answers:n.answers,results:o,savedGroups:{}}),sticky:s}));for(let k=0;k<Eu;k++){let g=a.get(u);if(!g||!Ru(g)||h(g))break;if(l>=t.execution.maxTransitions&&(l>t.execution.maxTransitions||g.type!=="end"&&g.type!=="output")){if(!c.length)throw r("TRANSITION_LIMIT","Local Funnel transition budget exceeded");break}let y,I;if(["condition","feature","split"].includes(g.type)||g.type==="offering"&&g.configuration.source==="feature")y=d(g.id),g.type==="offering"&&(y.value={type:"offering_version",id:String(y.value)}),g.type==="condition"?I=y.port==="default"?g.default:g.cases[Number(y.port.slice(5))]?.target:g.type==="split"?I=y.port==="notParticipating"?g.notParticipating:g.routes[y.port]:(g.type==="feature"||g.type==="offering")&&(I=g.next);else if(y={port:"next",sticky:[],exposures:[],features:[]},(g.type==="entry"||g.type==="coupon"||g.type==="coupons")&&(I=g.next),g.type==="offering"&&g.configuration.source==="fixed"&&(y.value={type:"offering_version",id:g.configuration.versionId},I=g.next),g.type==="end"||g.type==="output"){let C=g.type==="end"?g.output:g.value;if(y=C?.type==="feature"?d(g.id):{...y,port:"value",value:C?.type==="literal"?C.value:C?.type==="variable"?mc({source:"variable",key:C.key,...C.path?{path:C.path}:{}},{declarations:t.variables,answers:n.answers,results:o,parameters:n.parameters,attributes:i.attributes,savedGroups:{}}):null},C&&(y.value===void 0||!pn(t.outputSchema,y.value)))throw r("INVALID_RESPONSE","Local terminal violates its declared output")}let w=[...c,{nodeId:u,result:y}];if(an({steps:w})>6e4){if(!c.length)throw r("INVALID_REQUEST","Local step exceeds its command budget");break}if(c.push({nodeId:u,result:y}),g.type==="feature"||g.type==="offering"||g.type==="coupon"||g.type==="coupons"){let C=g.type==="coupons"?g.couponIds.map(E=>({type:"reward",id:E})):g.type==="coupon"?{type:"reward",id:g.couponId}:y.value;if(C===void 0)throw r("INVALID_RESPONSE","Node output is missing");let j=si(g,{value:C});Mp(t.variables,g,j),Object.assign(o,j)}for(let C of y.sticky)s[`${C.next.attributeName}||${C.next.attributeValue}`]=structuredClone(C.next);if(g.type==="end"||g.type==="output"){f=!0;break}if(!I)throw r("INVALID_RESPONSE","Local pure exit is unavailable");u=I,l++}let A=a.get(u);return{steps:c,...!f&&A&&(!Ru(A)||h(A))?{boundary:{nodeId:u,visit:l}}:{}}}var b=class extends Error{constructor(n,r,i,a,o){super(r);Fe(this,"code",n);Fe(this,"status",i);Fe(this,"requestId",a);Fe(this,"commandRequestId");Fe(this,"retryable");Fe(this,"recovery");Fe(this,"retryAfterSeconds");Fe(this,"reason");this.name="IndianaError",this.reason=o?.reason;let s=ko(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 So=e=>{if(!Number.isSafeInteger(e)||e<0||e>=Number.MAX_SAFE_INTEGER)throw new b("INVALID_STATE","Installation sequence exhausted");return e+1},Y0=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 jn(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 b("INVALID_STATE","Installation journal is invalid");return t({...n})})}function Qg(e,t,n){let r=null,i=0,a=0,o=0,s=Promise.resolve(),c=!1;if(e&&(!n||je.parse(e.scope).projectId!==n.projectId||e.scope.environment!==n.environment))throw new b("SCOPE_MISMATCH","Push installation belongs to another scope");let u=()=>{if(c)throw new b("CLOSED","SDK client was destroyed");if(!e)throw new b("NOT_CONFIGURED","Configure this client's native Push host first");return e},l=I=>{if(I!==i)throw new b("IDENTITY_CHANGED","Identity changed during Push operation")};async function f(I){let w=u();if(!w.sha256&&!globalThis.crypto?.subtle)throw new b("NOT_CONFIGURED","Configure native SHA-256 for this Push host");let C=w.sha256?await w.sha256(Uint8Array.from(I,j=>j.charCodeAt(0))):await Y0(I);if(!/^[a-f0-9]{64}$/.test(C))throw new b("INVALID_STATE","Push credential digest is invalid");return C}function m(I){let w=Ar.parse(I);if(w.installationId.toLowerCase()!==u().installationId.toLowerCase())throw new b("INVALID_RESPONSE","Push response belongs to another installation");return w}async function h(I,w){let C=u(),j={installationId:C.installationId,publicKey:C.publicKey,issuedAt:new Date().toISOString(),...w},E=await C.sign(pl(I,C.scope,j));return{...j,signature:E}}let d=(I,w,C)=>t.requestWithCredential?t.requestWithCredential(I,w,C):t.request(I,w);async function A(){let I=u(),w=i,C=r?await(t.session?.access()??r):null,j=jn(I,ye=>ye),E;if(j.detachSeq!==null){let ye=j.detachSeq,mt=ul.parse(await h("detach",{sequence:ye,platform:I.platform}));try{let He=await t.request("push/installations/detach",{...I.scope,...mt},"POST",{installationDetach:!0});if(!He||typeof He!="object"||!("installation"in He))throw new b("INVALID_RESPONSE","Push detach acknowledgement is invalid");let ke=m(He.installation);if(ke.bound||ke.identitySeq!==ye)throw new b("INVALID_RESPONSE","Push detach acknowledgement does not match its intent")}catch(He){if(He instanceof b&&He.status===404)E=He;else if(!(He instanceof b)||He.status!==412)throw He}E||jn(I,He=>({...He,detachSeq:He.detachSeq===ye?null:He.detachSeq}))}if(l(w),!C){if(E)throw E;return null}let ae=O.bindPushInstallation,xe=ae.request.parse(await h("bind",{sequence:o,platform:I.platform,credentialDigest:await f(C)}));l(w);let Oe=ae.response.parse(await d(ae.path,xe,C));l(w);let Ee=m(Oe.installation);if(!Ee.bound||Ee.identitySeq!==o)throw new b("INVALID_RESPONSE","Push binding acknowledgement does not match its intent");return E&&j.detachSeq!==null&&o>j.detachSeq&&jn(I,ye=>({...ye,detachSeq:ye.detachSeq===j.detachSeq?null:ye.detachSeq})),Ee}async function k(){u();let I=i,w=r?await(t.session?.access()??r):null;if(!w)throw new b("NOT_IDENTIFIED","Identify before reading this installation");let C=O.readPushInstallation,j=C.request.parse(await h("read",{credentialDigest:await f(w)}));l(I);let E=C.response.parse(await d(C.path,j,w));return l(I),m(E.installation)}function g(I=A){let w=s.catch(()=>{}).then(I);return s=w,w.catch(C=>{try{e?.onError?.(C instanceof Error?C:new Error("Push synchronization failed"))}catch{}}),w}async function y(I,w,C){let j=u(),E=w.identity,ae=w.observation,xe=r?await(t.session?.access()??r):null;if(l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");if(!xe)throw new b("NOT_IDENTIFIED","Identify before recovering a Push address");if(!I.connectionId||!I.kind||!I.token||!["granted","provisional"].includes(I.permission))throw new b("INVALID_REQUEST","Recovery needs a provider token and notification permission");return await g(async()=>{if(l(E),await A(),l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let Oe=jn(j,ke=>C?ke:{...ke,addressSeq:So(ke.addressSeq)}),ye=await h(C?"recovery_confirm":"recovery_request",{...I,sequence:Oe.addressSeq,credentialDigest:await f(xe),...C?{challenge:C}:{}}),mt=C?dl.parse(ye):ll.parse(ye);if(l(E),ae!==a)throw new b("INVALID_STATE","Push observation changed during recovery");let He=await d(`push/installations/recovery/${C?"confirm":"request"}`,mt,xe);if(l(E),ae!==a||jn(j,ke=>ke).addressSeq!==Oe.addressSeq)throw new b("INVALID_STATE","Push observation changed during recovery");if(C){let ke=O.updatePushAddress.response.parse(He),Xe=m(ke.installation);if(!Xe.bound||Xe.identitySeq!==o||Xe.addressSeq!==Oe.addressSeq||Xe.connectionId!==I.connectionId||Xe.addressStatus!=="active")throw new b("INVALID_RESPONSE","Push recovery acknowledgement does not match its intent");return Xe}if(!He||typeof He!="object"||!("recovery"in He))throw new b("INVALID_RESPONSE","Push recovery acknowledgement is invalid");return As.parse(He.recovery)})}return{recoveryObserver(){u();let I={identity:i,observation:++a};return{async request(w){return As.parse(await y(w,I))},async confirm(w,C){return Ar.parse(await y(C,I,w))}}},identify(I){if(!e)return;o=jn(e,C=>({...C,identitySeq:So(C.identitySeq)})).identitySeq,r=I,i++,a++},reset(){if(e)try{jn(e,I=>{let w=So(I.identitySeq);return{...I,identitySeq:w,detachSeq:w}})}finally{r=null,i++,a++}},start(){e&&!c&&g()},destroy(){c=!0,r=null,i++,a++},async sync(){return await g()},read:k,async recover(){let I=u(),w=i,C=o;return a++,await g(async()=>{l(w);let j=await k();return l(w),o=jn(I,ae=>{if(ae.identitySeq!==C)throw new b("IDENTITY_CHANGED","A newer installation intent exists");return{...ae,identitySeq:So(Math.max(ae.identitySeq,j.identitySeq)),addressSeq:Math.max(ae.addressSeq,j.addressSeq)}}).identitySeq,await A()})},tokenObserver(){u();let I=++a,w=i;return async C=>{if(I!==a||w!==i)return null;let j=u(),E=r?await(t.session?.access()??r):null;if(!E)throw new b("NOT_IDENTIFIED","Identify before registering a Push token");if(await g(),l(w),I!==a)return null;let ae=jn(j,ye=>({...ye,addressSeq:So(ye.addressSeq)})),xe=O.updatePushAddress,Oe=xe.request.parse(await h("address",{...C,sequence:ae.addressSeq,credentialDigest:await f(E)}));if(l(w),I!==a)return null;let Ee=await d(xe.path,Oe,E);return l(w),I!==a||jn(j,ye=>ye).addressSeq!==ae.addressSeq?null:m(xe.response.parse(Ee).installation)}}}}import{ZodError as X0}from"zod";function Jg(e,t,n,r){try{return e.parse(t)}catch(i){throw r&&i instanceof X0?new b(n,r):i}}async function me(e,t,n,r={},i){let a=typeof r=="function"?{}:r,o=Jg(t.request,n,"INVALID_REQUEST",a.request);try{let s=await e(t.path,o,t.method,i),c=typeof r=="function"?r:r.parseResponse;return c?c(t.response,s):Jg(t.response,s,"INVALID_RESPONSE",a.response)}catch(s){throw s instanceof b&&o!==null&&typeof o=="object"&&"requestId"in o&&typeof o.requestId=="string"&&(s.commandRequestId??(s.commandRequestId=o.requestId)),s}}function Zg(e,t){let n={async preference(r){let i=O.readMessagingPreference;return(await me(e,i,{channel:r})).preference},async setPreference(r){let i=O.setMessagingPreference;return(await me(e,i,r)).preference}};return{messaging:n,push:{sync:t.sync,read:t.read,recover:t.recover,tokenObserver:t.tokenObserver,recoveryObserver:t.recoveryObserver,async preference(){return n.preference("push")},async setPreference(r){return n.setPreference({...r,channel:"push"})}}}}var Wg={name:"@tinkerlandai/longplay-sdk",version:"0.10.13",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 && tsc --noEmit -p tsconfig.test.json",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 Ke(e){return typeof e=="string"?e:String(e)}var tI=/[\ud800-\udbff](?![\udc00-\udfff])|(^|[^\ud800-\udbff])[\udc00-\udfff]/g;function nI(e){return e.replace(tI,"$1\uFFFD")}function Du(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 ah(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 Yg(e){let t;if(Array.isArray(e)){let n=e.map(Ke);if(n.length===2)return n}else if((t=ah(e))!=null){let n=Du(t.next()),r=Du(t.next());if(!n.done&&!r.done)return[Ke(n.value),Ke(r.value)]}throw new TypeError("Each query pair must be an iterable [name, value] tuple")}var Xg="0123456789ABCDEF",rI=/(?:%[0-9A-Fa-f]{2})+/g;function Tn(e){return`%${Xg[e>>4&15]}${Xg[15&e]}`}function sh(e,t,n=!1){return e>=55296&&e<=57343&&(e=65533),e<=127?n&&e===32?"+":t(e)?Tn(e):String.fromCharCode(e):e<=2047?Tn(192|e>>6)+Tn(128|63&e):e<=65535?Tn(224|e>>12)+Tn(128|e>>6&63)+Tn(128|63&e):Tn(240|e>>18)+Tn(128|e>>12&63)+Tn(128|e>>6&63)+Tn(128|63&e)}function Fu(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function Mu(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(rI,r=>{try{return decodeURIComponent(r)}catch{return"\uFFFD".repeat(r.length/3)}})}function wo(e){return e<=31||e>126}function iI(e){switch(e){case 32:case 34:case 60:case 62:case 96:return!0;default:return wo(e)}}function $u(e){switch(e){case 32:case 34:case 35:case 60:case 62:return!0;default:return wo(e)}}function oI(e){return $u(e)||e===39}function qu(e){switch(e){case 63:case 94:case 96:case 123:case 125:return!0;default:return $u(e)}}function os(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 qu(e)}}function eh(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 os(n)}})(e)}}function ch(e,t){return sh(e=e||0,t)}function Nn(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+=sh(o,t,n)}return i}function Gu(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([Mu(i.slice(0,a),!0),Mu(i.slice(a+1),!0)])}if(n=r+1,r===e.length)break}return t}function Bu(e){let t="";for(let n=0;n<e.length;n++){let r=Nn(e[n][0],eh,!0),i=Nn(e[n][1],eh,!0);t+=n!==0?`&${r}=${i}`:`${r}=${i}`}return t}var aI=[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],sI=[7296,7297,7298,7299,7300,7301,7302,7303,7304,42958,42962,42964,42993],cI=["\u0432","\u0434","\u043E","\u0441","\u0442","\u0442","\u044A","\u0463","\uA64B","\uA7CF","\uA7D3","\uA7D5","s"],uI=[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 lI(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[dI,pI,mI,th]=[[[],"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 fI(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 uh(e,t){for(let n=0;n<e.length;n+=2)if(t>=e[n]&&t<=e[n+1])return!0;return!1}function Io(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 gI(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&&uh(uI,t[n-1]))continue;if(r===8205)return!1;let i=n-1;for(;i>=0&&Io(th,t[i]);)i--;let a=n+1;for(;a<t.length&&Io(th,t[a]);)a++;if(!(i>=0&&a<t.length&&Io(pI,t[i])&&Io(mI,t[a])))return!1}return!0}var hI=/(?![\p{Mark}\p{Decimal_Number}])[\p{Script=Arabic}\p{Script=Hebrew}]/u,AI=/\p{Script=Latin}/u;function yI(e){return!hI.test(e)||!AI.test(e)}var ar=36,ns=1,Vu=26,bI=38,xI=700,SI=72,II=128,vI=2147483647;function nh(e){return String.fromCharCode(e+22+75*+(e<26))}function wI(e,t,n){let r=0;for(e=n?Math.floor(e/xI):e>>1,e+=Math.floor(e/t);e>(ar-ns)*Vu>>1;r+=ar)e=Math.floor(e/(ar-ns));return Math.floor(r+(ar-ns+1)*e/(e+bI))}function OI(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=SI;for(;r<t.length;){let c=vI;for(let u=0;u<t.length;u++){let l=t[u];l>=a&&l<c&&(c=l)}o+=(c-a)*(r+1),a=c;for(let u=0;u<t.length;u++){let l=t[u];if(l<a&&o++,l===a){let f=o;for(let m=ar;;m+=ar){let h=m<=s?ns:m>=s+Vu?Vu:m-s;if(f<h)break;n+=nh(h+(f-h)%(ar-h)),f=Math.floor((f-h)/(ar-h))}n+=nh(f),s=wI(o,r+1,r===i),o=0,r++}}o++,a++}return n}function ju(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=Fu(e.charCodeAt(r));if(i>=t||i<0)return-1;n=n*t+i}return n}function rh(e){switch(e){case".":case"%2e":case"%2E":return!0;default:return!1}}function lh(e,t){return(e>=65&&e<=90||e>=97&&e<=122)&&(t===58||t===124)}function dh(e){return e.length===2&&lh(e.codePointAt(0),e.codePointAt(1))}function ih(e){return e.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|<|>|\?|@|\[|\\|\]|\^|\|/u)!==-1}function dt(e){switch(e){case"ftp":case"http":case"https":case"ws":case"wss":case"file":return!0;default:return!1}}function ph(e){switch(e){case"ftp":return 21;case"http":case"ws":return 80;case"https":case"wss":return 443;default:return null}}function Lu(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,l=0,f=0;for(;f<4&&(u=Fu(c[s]))>=0;)l=(l<<4)+u,s++,f++;if(c[s]===46){if(f===0||o>6)return null;s-=f;let m=0;for(;c[s]!==void 0;){let h=0;if(m>0)if(c[s]===46&&m<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(h=10*h+Fu(c[s]),h>255)return null;s++}i[o]=256*i[o]+h,m++,m%2==0&&o++}if(m!==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]=l,o++}if(a!==null){let u=o-a;for(o=7;o!==0&&u>0;){let l=i[a+u-1];i[a+u-1]=i[o],i[o]=l,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 ih(r)?null:Nn(r,wo)})(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 l of u){let f=l.codePointAt(0);if(/[\p{Cn}\p{Co}\p{Cs}\p{Noncharacter_Code_Point}]/u.test(l)&&!uh(aI,f)||Io(dI,f))return!0}return!1})(i))return null;let s=(i=(function(u){let l="";for(let f of u){let m=f.codePointAt(0);if(m!==8204&&m!==8205&&/\p{Default_Ignorable_Code_Point}/u.test(f))continue;let h=fI(f,m);if(h){l+=h;continue}let d=sI.indexOf(m);l+=d<0?f:cI[d]}return l})(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 l=/[^\0-\x7f]/.test(u);if(lI(u)||l&&(/^\p{Mark}/u.test(u)||!gI(u)||!yI(u)||u.startsWith("xn--")))return null;l&&(s[c]=`xn--${OI(u)}`)}return(i=s.join("."))!==""?i:null})(e.indexOf("%")===-1?e:Mu(e));return n===null||ih(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(ju(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 l=ju(a[u]);if(l<0||l>255)return null;s+=l*(1<<8*(3-u))}let c=ju(a[o-1]);return c<0||c>=256**(5-o)?null:(s+=c,s)})(n):n}}function Uu(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,l=1,f=0;for(let m=0;m<s.length;++m)s[m]!==0?(f>l&&(c=u,l=f),u=-1,f=0):(u===-1&&(u=m),++f);return f>l?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 mh(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 fh(e){return e.username!==""||e.password!==""}function Tu(e){return e.host===null||e.host===""||e.scheme==="file"}var _=0,B="",ve="",Ve=null,V,rs=!1,is=!1,Br=!1,pt;function ln(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),_=0,B=e,ve="",Ve=n||null,V=t||{scheme:"",username:"",password:"",host:null,port:null,path:[],query:null,fragment:null,opaquePath:!1},rs=!1,is=!1,Br=!1,pt=r||0;let i=PI;switch(r){case 3:case 4:i=as;break;case 5:i=Hu;break;case 6:i=Vr;break;case 7:i=sr;break;case 8:i=Dn}return i(G(e,_))!==1?V:null}function Y(e,t){return _+=_===e?Cn(t):1,_<=B.length}function G(e,t){return t<e.length?e.codePointAt(t):void 0}function Cn(e){return e!=null&&e>65535?2:1}function gh(e){return e==null?"":e<=65535?String.fromCharCode(e):String.fromCodePoint(e)}var PI=e=>{let t=_;if(e!=null&&(e>=65&&e<=90||e>=97&&e<=122)){let n=_+1;for(e=B.charCodeAt(n);e===43||e===45||e===46||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57;)n++,e=B.charCodeAt(n);return ve=B.slice(_,n).toLowerCase(),_=n,CI(n<B.length?e:void 0)}else return pt?1:(--_,Y(t,e)?hh(G(B,_)):0)},CI=e=>{let t=_;if(e===58){if(pt){if(dt(V.scheme)!==dt(ve))return 0;if((fh(V)||V.port!==null)&&ve==="file")return 0;if(V.scheme==="file"&&V.host==="")return 0}return V.scheme=ve,pt?(V.port===ph(V.scheme)&&(V.port=null),0):(ve="",V.scheme==="file"?Y(t,e)?Qu(G(B,_)):0:dt(V.scheme)&&Ve!==null&&Ve.scheme===V.scheme?Y(t,e)?_I(G(B,_)):0:dt(V.scheme)?Y(t,e)?RI(G(B,_)):0:G(B,_+1)===47?(_++,Y(t,e)?EI(G(B,_)):0):(V.path=[""],V.opaquePath=!0,Y(t,e)?yh(G(B,_)):0))}else return pt?1:(ve="",_=-1,Y(t,e)?hh(G(B,_)):0)},hh=e=>{let t=_;return Ve===null||Ve.opaquePath&&e!==35?1:Ve.opaquePath&&e===35?(V.scheme=Ve.scheme,V.path=Ve.path.slice(),V.opaquePath=Ve.opaquePath,V.query=Ve.query,V.fragment="",Y(t,e)?Dn(G(B,_)):0):Ve.scheme==="file"?(_--,Y(t,e)?Qu(G(B,_)):0):(_--,Y(t,e)?Ku(G(B,_)):0)},_I=e=>{let t=_;return e===47&&G(B,_+1)===47?(++_,Y(t,e)?cs(G(B,_)):0):(_--,Y(t,e)?Ku(G(B,_)):0)},EI=e=>{let t=_;return e===47?Y(t,e)?Pi(G(B,_)):0:(_--,Y(t,e)?_n(G(B,_)):0)},Ku=e=>{let t=_;return V.scheme=Ve.scheme,e===47||dt(V.scheme)&&e===92?Y(t,e)?oh(G(B,_)):0:(V.username=Ve.username,V.password=Ve.password,V.host=Ve.host,V.port=Ve.port,V.path=Ve.path.slice(),V.query=Ve.query,e===63?(V.query="",Y(t,e)?sr(G(B,_)):0):e===35?(V.fragment="",Y(t,e)?Dn(G(B,_)):0):e!=null?(V.query=null,V.path.pop(),_--,Y(t,e)?_n(G(B,_)):0):Y(t,e)?Ku(G(B,_)):0)},oh=e=>{let t=_;return dt(V.scheme)&&(e===47||e===92)?Y(t,e)?cs(G(B,_)):0:e===47?Y(t,e)?Pi(G(B,_)):0:(V.username=Ve.username,V.password=Ve.password,V.host=Ve.host,V.port=Ve.port,_--,Y(t,e)?_n(G(B,_)):0)},RI=e=>{let t=_;return e===47&&G(B,_+1)===47?_++:_--,Y(t,e)?cs(G(B,_)):0},cs=e=>{let t=_;return e!==47&&e!==92?(_--,Y(t,e)?Pi(G(B,_)):0):Y(t,e)?cs(G(B,_)):0},Pi=e=>{let t=_;if(e!=null&&e!==64&&e!==35&&e!==47&&e!==63&&(e!==92||!dt(V.scheme))){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===64||r===35||r===47||r===63||r===92&&dt(V.scheme))break;n+=Cn(r)}return ve+=B.slice(_,n),_=n-1,Y(t,e)?Pi(G(B,_)):0}if(e===64){rs&&(ve=`%40${ve}`),rs=!0;for(let n=0;n<ve.length;n++){let r=ve.codePointAt(n);if(r===58&&!is){is=!0;continue}let i=ch(r,os);is?V.password+=i:V.username+=i,r!=null&&r>65535&&n++}return ve="",Y(t,e)?Pi(G(B,_)):0}else return e==null||e===35||e===47||e===63||e===92&&dt(V.scheme)?rs&&ve===""?1:(_-=ve.length+1,ve="",Y(t,e)?as(G(B,_)):0):(ve+=gh(e),Y(t,e)?Pi(G(B,_)):0)},as=e=>{let t=_;if(pt&&V.scheme==="file")return _--,Y(t,e)?Ju(G(B,_)):0;if(e!=null&&e!==58&&e!==35&&e!==47&&e!==63&&(e!==92||!dt(V.scheme))){let n=_+Cn(e);for(e===91?Br=!0:e===93&&(Br=!1);n<B.length;){let r=G(B,n);if(r==null||!Br&&r===58||r===35||r===47||r===63||r===92&&dt(V.scheme))break;r===91?Br=!0:r===93&&(Br=!1),n+=Cn(r)}return ve+=B.slice(_,n),_=n-1,Y(t,e)?as(G(B,_)):0}else if(e===58&&!Br){if(ve===""||pt===4)return 1;let n=Lu(ve,!dt(V.scheme));return n===null?1:(V.host=Uu(n),ve="",Y(t,e)?Hu(G(B,_)):0)}else if(e==null||e===35||e===47||e===63||e===92&&dt(V.scheme)){if(_--,dt(V.scheme)&&ve==="")return 1;if(pt&&ve===""&&(fh(V)||V.port!==null))return 1;let n=Lu(ve,!dt(V.scheme));return n===null?1:(V.host=Uu(n),ve="",pt?0:Y(t,e)?Vr(G(B,_)):0)}else return ve+=gh(e),Y(t,e)?as(G(B,_)):0},Hu=e=>{let t=_;if(e!=null&&e>=48&&e<=57){let n=_+1;for(;n<B.length;){let r=B.charCodeAt(n);if(r<48||r>57)break;n++}return ve+=B.slice(_,n),_=n-1,Y(t,e)?Hu(G(B,_)):0}else if(pt||e==null||e===35||e===47||e===63||e===92&&dt(V.scheme)){if(ve!==""){let n=parseInt(ve,10);if(n>65535)return 1;if(V.port=n===ph(V.scheme)?null:n,ve="",pt)return 0}return pt?1:(_--,Y(t,e)?Vr(G(B,_)):0)}else return 1};function Ah(e,t){let n=e.length-t;if(n<2)return!1;if(lh(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=_;return V.scheme="file",V.host="",e===47||e===92?Y(t,e)?kI(G(B,_)):0:Ve?.scheme==="file"?(V.host=Ve.host,V.path=Ve.path.slice(),V.opaquePath=Ve.opaquePath,V.query=Ve.query,e===63?(V.query="",Y(t,e)?sr(G(B,_)):0):e===35?(V.fragment="",Y(t,e)?Dn(G(B,_)):0):e!=null?(V.query=null,Ah(B,_)?V.path=[]:mh(V),_--,Y(t,e)?_n(G(B,_)):0):Y(t,e)?Qu(G(B,_)):0):(_--,Y(t,e)?_n(G(B,_)):0)},kI=e=>{let t=_;return e===47||e===92?Y(t,e)?Ju(G(B,_)):0:(Ve!==null&&Ve.scheme==="file"&&(!Ah(B,_)&&(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})(Ve.path[0])&&V.path.push(Ve.path[0]),V.host=Ve.host),_--,Y(t,e)?_n(G(B,_)):0)},Ju=e=>{let t=_;if(e!=null&&e!==47&&e!==92&&e!==63&&e!==35){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===47||r===92||r===63||r===35)break;n+=Cn(r)}return ve+=B.slice(_,n),_=n-1,Y(t,e)?Ju(G(B,_)):0}else if(e==null||e===47||e===92||e===63||e===35){if(_--,!pt&&dh(ve))return Y(t,e)?_n(G(B,_)):0;if(ve==="")return V.host="",pt?0:Y(t,e)?Vr(G(B,_)):0;{let n=Lu(ve,!dt(V.scheme));return n===null?1:(n==="localhost"&&(n=""),V.host=Uu(n),ve="",pt?0:Y(t,e)?Vr(G(B,_)):0)}}return 1},Vr=e=>{let t=_;return dt(V.scheme)?(e!==92&&e!==47&&_--,Y(t,e)?_n(G(B,_)):0):!pt&&e===63?(V.query="",Y(t,e)?sr(G(B,_)):0):!pt&&e===35?(V.fragment="",Y(t,e)?Dn(G(B,_)):0):e!=null?(e!==47&&_--,Y(t,e)?_n(G(B,_)):0):(pt&&V.host===null&&V.path.push(""),Y(t,e)?Vr(G(B,_)):0)},_n=e=>{let t=_;if(e!=null&&e!==47&&(!dt(V.scheme)||e!==92)&&(pt||e!==63&&e!==35)){let n=_+Cn(e);for(;n<B.length;){let r=G(B,n);if(r==null||r===47||dt(V.scheme)&&r===92||!pt&&(r===63||r===35))break;n+=Cn(r)}ve+=Nn(B.slice(_,n),qu),_=n,e=G(B,n)}if(e==null||e===47||dt(V.scheme)&&e===92||!pt&&(e===63||e===35)){let n=dt(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}})(ve)?(mh(V),e!==47&&!n&&V.path.push("")):rh(ve)&&e!==47&&!n?V.path.push(""):rh(ve)||(V.scheme==="file"&&V.path.length===0&&dh(ve)&&(ve=`${ve[0]}:`),V.path.push(ve)),ve="",e===63?(V.query="",Y(t,e)?sr(G(B,_)):0):e===35?(V.fragment="",Y(t,e)?Dn(G(B,_)):0):Y(t,e)?_n(G(B,_)):0}else return ve+=ch(e,qu),Y(t,e)?_n(G(B,_)):0},yh=e=>{let t=_;if(e===63)return V.query="",Y(t,e)?sr(G(B,_)):0;if(e===35)return V.fragment="",Y(t,e)?Dn(G(B,_)):0;if(e!=null){let n=_+Cn(e);for(;n<B.length;){let i=G(B,n);if(i===63||i===35)break;n+=Cn(i)}let r=B.slice(_,n);if(n<B.length&&r.charCodeAt(r.length-1)===32?V.path[0]+=Nn(r.slice(0,-1),wo)+"%20":V.path[0]+=Nn(r,wo),_=n,(e=G(B,n))===63)return V.query="",Y(t,e)?sr(G(B,_)):0;if(e===35)return V.fragment="",Y(t,e)?Dn(G(B,_)):0}return Y(t,e)?yh(G(B,_)):0},sr=e=>{let t=_,n=_;if(e!=null){if(pt)n=B.length;else{let i=B.indexOf("#",_);n=i===-1?B.length:i}let r=dt(V.scheme)?oI:$u;V.query+=Nn(B.slice(_,n),r)}return _=n,G(B,n)===35&&!pt?(V.fragment="",Y(t,e)?Dn(G(B,_)):0):Y(t,e)?sr(G(B,_)):0},Dn=e=>{let t=_;return e!=null&&(V.fragment+=Nn(B.slice(_),iI),_=B.length),Y(t,e)?Dn(G(B,_)):0};function zu(e){if(e.opaquePath)return e.path[0];{let t="";for(let n of e.path)t+=`/${n}`;return t}}function bh(e){switch(e.scheme){case"blob":{let t=ln(zu(e),null,null,0);return t===null||t.scheme!=="http"&&t.scheme!=="https"?"null":bh(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 Ge=Symbol("URLImpl"),hn=class e{constructor(t,n){if(t===void 0&&n===void 0)throw new TypeError('The "url" argument must be specified.');t=Ke(t),n!=null&&(n=Ke(n));let r=null;if(n!=null&&(r=ln(n,null,null,0),r==null))throw new TypeError(`Invalid base URL: ${n}`);let i=ln(t,null,r,0);if(i==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge]={url:i,query:null}}static createObjectURL(t){throw new TypeError("URL.createObjetURL is unsupported")}static revokeObjectURL(t){}static parse(t,n){t=Ke(t),n!==void 0&&(n=Ke(n));try{return new e(t,n)}catch{return null}}static canParse(t,n){t=Ke(t),n!==void 0&&(n=Ke(n));let r=null;return n!=null&&(r=ln(n,null,null,0),r==null)?!1:ln(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+=zu(n),n.query!==null&&(r+=`?${n.query}`),n.fragment!==null&&(r+=`#${n.fragment}`),r})(this[Ge].url)}set href(t){let n=ln(t=Ke(t),null,null,0);if(n==null)throw new TypeError(`Invalid URL: ${t}`);this[Ge].url=n,this[Ge].query&&Nu(this[Ge].query,n.query)}get origin(){return bh(this[Ge].url)}get protocol(){return`${this[Ge].url.scheme}:`}set protocol(t){ln(`${t=Ke(t)}:`,this[Ge].url,null,2)}get username(){return this[Ge].url.username}set username(t){t=Ke(t),Tu(this[Ge].url)||(function(r,i){r.username=Nn(i,os)})(this[Ge].url,t)}get password(){return this[Ge].url.password}set password(t){t=Ke(t),Tu(this[Ge].url)||(function(r,i){r.password=Nn(i,os)})(this[Ge].url,t)}get host(){let{url:t}=this[Ge];return t.host==null?"":t.port==null?t.host:`${t.host}:${t.port}`}set host(t){t=Ke(t),this[Ge].url.opaquePath||ln(t,this[Ge].url,null,3)}get hostname(){let{url:t}=this[Ge];return t.host!=null?t.host:""}set hostname(t){t=Ke(t),this[Ge].url.opaquePath||ln(t,this[Ge].url,null,4)}get port(){let{url:t}=this[Ge];return t.port!=null?`${t.port}`:""}set port(t){t=Ke(t);let{url:n}=this[Ge];Tu(n)||(t?ln(t,n,null,5):n.port=null)}get pathname(){return zu(this[Ge].url)}set pathname(t){t=Ke(t);let{url:n}=this[Ge];n.opaquePath||(n.path=[],ln(t,n,null,6))}get search(){let{url:t}=this[Ge];return t.query?`?${t.query}`:""}set search(t){t=Ke(t);let{url:n,query:r}=this[Ge];if(!t)n.query=null,r&&Nu(r,null);else{let i=t[0]==="?"?t.substring(1):t;n.query="",ln(i,n,null,7),r&&Nu(r,n.query)}}get searchParams(){let t=this[Ge],n=t.query;return n==null&&(n=t.query=(function(i,a){let o=new ss;return o[it].url=i,o[it].serialized=a==null,a&&(o[it].list=Gu(a)),o})(this,t.url.query)),n}get hash(){let{url:t}=this[Ge];return t.fragment?`#${t.fragment}`:""}set hash(t){t=Ke(t);let{url:n}=this[Ge];if(!t)n.fragment=null;else{let r=t[0]==="#"?t.substring(1):t;n.fragment="",ln(r,n,null,8)}}toJSON(){return this.href}toString(){return this.href}};Object.defineProperty(hn.prototype,Symbol.toStringTag,{value:"URL",configurable:!0});var it=Symbol("URLSearchParamsImpl"),jI=Symbol.dispose||Symbol.for("dispose");function Nu(e,t){t?e[it].list=Gu(t):e[it].list.length=0,e[it].serialized=t==null}function ts(e){if(e.url){let t=Bu(e.list);(function(r,i){r[Ge].url.query=i})(e.url,t||null),e.serialized=!0}}var TI=typeof Iterator<"u"?Iterator:Object,vo=class extends TI{constructor(t,n){super(),this[it]={ptr:t,map:n,index:0}}next(){let t=this[it];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}[jI](){}},ss=class{constructor(t){let n=this[it]={list:[],url:null,serialized:!0},r;if(Array.isArray(t))for(let i=0;i<t.length;i++)n.list.push(Yg(t[i]));else if((r=ah(t))!=null){let i;for(;!(i=Du(r.next())).done;)n.list.push(Yg(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=nI(o),c=Ke(t[o]),u=n.list.find(l=>l[0]===s);u?u[1]=c:n.list.push([s,c])}}else if(t!==void 0){let i=Ke(t);i=i[0]==="?"?i.substring(1):i,n.list=Gu(i)}}get size(){return this[it].list.length}append(t,n){t=Ke(t),n=Ke(n),this[it].list.push([t,n]);let r=this[it];r.url&&r.serialized?(function(a,o){let s=a[Ge].url;s.query=s.query?`${s.query}&${o}`:o})(r.url,Bu([[t,n]])):ts(r)}delete(t,n){t=Ke(t),n=n!=null?Ke(n):void 0;let{list:r}=this[it],i=0;for(;i<r.length;)r[i][0]===t&&(n==null||r[i][1]===n)?r.splice(i,1):i++;ts(this[it])}get(t){t=Ke(t);let{list:n}=this[it];for(let r=0;r<n.length;r++)if(n[r][0]===t)return n[r][1];return null}getAll(t){t=Ke(t);let n=[],{list:r}=this[it];for(let i=0;i<r.length;i++)r[i][0]===t&&n.push(r[i][1]);return n}has(t,n){t=Ke(t),n=n!=null?Ke(n):void 0;let{list:r}=this[it];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=Ke(t),n=Ke(n);let{list:r}=this[it],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&&ts(this[it])}sort(){this[it].list.sort((t,n)=>t[0]<n[0]?-1:t[0]>n[0]?1:0),ts(this[it])}forEach(t,n){if(typeof t!="function")throw new TypeError('The "callback" argument must be of type function');let{list:r}=this[it];for(let i=0;i<r.length;i++)t.call(n,r[i][1],r[i][0],this)}entries(){return new vo(this[it],t=>t)}keys(){return new vo(this[it],t=>t[0])}values(){return new vo(this[it],t=>t[1])}toString(){return Bu(this[it].list)}[Symbol.iterator](){return this.entries()}};Object.defineProperty(ss.prototype,Symbol.toStringTag,{value:"URLSearchParams",configurable:!0});var cr="https://api.longplayai.com";function xh(e){let t,n=()=>typeof t=="string"?t:t?.accessToken,r=0,i,a=new Map,o=()=>{for(let f of[...a.keys()])try{f()}catch{}};function s(f){let m=++r;i=void 0,t=void 0;for(let h of[...a.values()])try{h?.()}catch{}m===r&&(t=f,o())}let c=()=>s();function u(f,m=!1){let h=Kn.safeParse(f);if(!h.success||m&&Date.parse(h.data.expiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<=Date.now()||Date.parse(h.data.refreshExpiresAt)<Date.parse(h.data.expiresAt))throw new b("INVALID_RESPONSE","Invalid customer session credentials");return h.data}async function l(){if(i)return i;let f=typeof t=="object"?t:void 0,m=r;if(!f||Date.parse(f.refreshExpiresAt)<=Date.now())throw f&&c(),new b("UNAUTHENTICATED","Customer authentication is required",401);let h=(async()=>{try{let d=await e(f.refreshToken);if(m!==r)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");let A=u(d,!0);if(A.customerId!==f.customerId||A.sessionId!==f.sessionId)throw new b("SCOPE_MISMATCH","Refresh changed the customer session");return t=A,{...A}}catch(d){throw m!==r?new b("IDENTITY_CHANGED","Customer identity changed during refresh"):(d instanceof b&&d.status===401&&c(),d)}})();i=h;try{return await h}finally{i===h&&(i=void 0)}}return{identify(f){let m=typeof f=="string"?f:u(f),h=typeof m=="string"?m:m.accessToken;if(!h.trim()||/\s/.test(h)||h.length>4096)throw new b("INVALID_TOKEN","A server-issued token is required");s(m)},reset:c,subscribeIdentity(f,m){return a.set(f,m),()=>{a.delete(f)}},access(){let f=typeof t=="object"?t:void 0;if(f&&Date.parse(f.expiresAt)<=Date.now()+3e4){let h=r;return l().then(()=>{let d=n();if(h!==r||!d)throw new b("IDENTITY_CHANGED","Customer identity changed during refresh");return d})}let m=n();if(!m)throw new b("NOT_IDENTIFIED","Identify a customer session before making a request");return m},peek:n,snapshot:()=>typeof t=="object"?{...t}:void 0,refresh:l}}var Sh=Symbol("IndianaNoContent");function ur(e,t,n=hn){let r=e.configuration?.scope,i=e.scope??(r&&{projectId:r.projectId,environment:r.environment}),a=i?je.parse(i):void 0;if(a&&r&&(a.projectId!==r.projectId||a.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let o=new n(e.baseUrl??cr);if(o.username||o.password||o.search||o.hash)throw new b("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 b("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 b("INVALID_TIMEOUT","timeoutMs must be between 1 and 120000");let u=!1,l=0,f=null,m=new Set,h=e.session??xh(async y=>{let I=await g("customer-sessions/refresh",{},"POST",{},y);if(!I||typeof I!="object")throw new b("INVALID_RESPONSE","Invalid refresh response");let{requestId:w,scope:C,...j}=I;return j});function d(){l+=1,f=null;for(let y of m)y.abort();m.clear()}let A=h.subscribeIdentity(d);function k(){u||h.reset()}async function g(y,I={},w="POST",C={},j){let E=C.installationDetach===!0;if(E&&(y!=="push/installations/detach"||w!=="POST"))throw new b("INVALID_REQUEST","Installation authority only detaches this installation");if(!j&&!E)throw new b("NOT_IDENTIFIED","Call identify with a server-issued customer token first");let ae=l,xe=new AbortController;E||m.add(xe);let Oe=()=>!E&&ae!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):new b("TIMEOUT","Longplay request timed out"),Ee,ye=new Promise((ke,Xe)=>{Ee=()=>Xe(Oe()),xe.signal.addEventListener("abort",Ee,{once:!0})}),mt=setTimeout(()=>xe.abort(),C.timeoutMs??c),He=async()=>{let ke=await s(`${o.href.replace(/\/$/,"")}/api/v1/${y}`,{method:w,headers:{...C.headers,"Content-Type":"application/json",...E?{}:{Authorization:`Bearer ${j}`},[Is]:vs.current,[Al]:Wg.version,...a?{"X-Indiana-Project":a.projectId,"X-Indiana-Environment":a.environment}:{}},body:w==="POST"?JSON.stringify(I):void 0,signal:xe.signal,credentials:"omit",cache:"no-store",redirect:"error",...C.keepalive?{keepalive:!0}:{}});if(xe.signal.aborted)throw Oe();let Xe;try{Xe=ke.status===204?Sh:await ke.json()}catch{throw xe.signal.aborted?Oe():new b(ke.ok?"INVALID_RESPONSE":"HTTP_ERROR","The gateway returned an unreadable response",ke.status,ke.headers.get("X-Request-Id")??void 0)}if(xe.signal.aborted)throw Oe();if(!E&&ae!==l)throw new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight");if(!ke.ok){let ut=Ss.safeParse(Xe),Kt=ut.success&&(!qn.safeParse(ut.data.error.code).success||gl(ut.data.error.code,ke.status)),mr=Kt?ut.data.error.code:"HTTP_ERROR",fr=ko(mr,ke.status,{retryAfter:ke.headers.get("Retry-After"),recovery:Kt?ut.data.error.recovery:void 0,reason:Kt?ut.data.error.reason:void 0});throw new b(mr,Kt?ut.data.error.message:"Longplay request failed",ke.status,ke.headers.get("X-Request-Id")??(ut.success?ut.data.requestId:void 0),{...fr,...ut.success&&ut.data.error.retryable===!1?{retryable:!1}:{},...fr.retryAfterSeconds===void 0&&ut.success&&ut.data.error.retryAfterSeconds!==void 0?{retryAfterSeconds:ut.data.error.retryAfterSeconds}:{}})}if(ke.headers.get(Is)!==vs.current)throw new b("PROTOCOL_MISMATCH","Response protocol does not match this SDK");if(a&&Xe!==Sh){let ut=Xe&&typeof Xe=="object"&&"scope"in Xe?Xe:Xe&&typeof Xe=="object"&&"configuration"in Xe?Xe.configuration:null;if(!ut||typeof ut!="object"||!("scope"in ut))throw new b("INVALID_RESPONSE","Response is missing its App/environment scope");let Kt=je.safeParse(ut.scope);if(!Kt.success||Kt.data.projectId!==a.projectId||Kt.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Response scope does not match this SDK instance")}let Ur=ke.headers.get("X-Indiana-Telemetry-Subject");if(Ur){if(!/^[a-f0-9]{64}$/.test(Ur))throw new b("INVALID_RESPONSE","Invalid telemetry identity");f!==Ur&&(f=Ur,t?.(f))}return Xe};try{return await Promise.race([He(),ye])}catch(ke){throw!E&&ae!==l?new b("IDENTITY_CHANGED","Customer identity changed while the request was in flight"):ke instanceof b?ke:new b(xe.signal.aborted?"TIMEOUT":"NETWORK_ERROR",xe.signal.aborted?"Longplay request timed out":"Unable to read the Longplay response")}finally{clearTimeout(mt),xe.signal.removeEventListener("abort",Ee),m.delete(xe)}}return{session:h,requestWithCredential(y,I,w,C={}){return u?Promise.reject(new b("CLOSED","SDK client was destroyed")):g(y,I,"POST",C,w)},subjectKey:()=>f,identify(y){if(u)throw new b("CLOSED","SDK client was destroyed");if(a&&typeof y=="object"&&"scope"in y){let I=je.safeParse(y.scope);if(!I.success||I.data.projectId!==a.projectId||I.data.environment!==a.environment)throw new b("SCOPE_MISMATCH","Customer session belongs to another App/environment")}h.identify(y)},reset:k,dispose(){u||(u=!0,A(),d())},request(y,I={},w="POST",C={}){if(u)return Promise.reject(new b("CLOSED","SDK client was destroyed"));if(C.installationDetach)return g(y,I,w,C);let j=l;try{let E=h.access(),ae=xe=>{if(j!==l)throw new b("IDENTITY_CHANGED","Customer identity changed before dispatch");return g(y,I,w,C,xe)};return typeof E=="string"?ae(E):E.then(ae)}catch(E){return Promise.reject(E)}}}}function Ih(e,t,n={}){let r=!1;function i(){if(r)throw new b("CLOSED","SDK client was destroyed")}let a=new Set,o=c=>{for(let u of a)try{u(c)}catch{}},s=e.session.subscribeIdentity(()=>{o(!!e.session.peek()),n.afterChange?.()},()=>{t()});return{assertActive:i,isIdentified:()=>!r&&!!e.session.peek(),methods:{subscribeIdentity(c){return i(),a.add(c),()=>{a.delete(c)}},identify(c){i();let u=typeof c=="string"?c:c.accessToken;if(!Et.test(u))throw new b("INVALID_TOKEN","Browser SDK requires a customer session");n.beforeIdentify?.(u),e.identify(c)},reset(){if(!r)try{n.beforeReset?.()}finally{e.reset()}},destroy(){if(!r){r=!0,s(),a.clear();try{n.beforeDestroy?.(),t()}finally{e.dispose()}}}}}}function Le(e){if(e!==null&&typeof e=="object"&&"customerId"in e)throw new b("INVALID_REQUEST","Customer requests use the verified session identity")}var NI={...O.readHoldings,request:O.readHoldings.request.omit({customerId:!0})};function vh(e){return{async checkEntitlement(t){Le(t);let n=O.checkEntitlement;return me(e,n,t)},async readHoldings(t={}){return me(e,NI,t)}}}function wh(e){return{async readLedger(t){let n=O.readLedger;return me(e,n,{query:t})},async readCreditStatement(t){Le(t);let n=O.readCreditStatement;return me(e,n,t)},async quoteBalance(t){Le(t);let n=O.quoteBalance;return me(e,n,{command:t})}}}function Oh(e){return{async setupPayment(t){Le(t);let n=O.setupPayment;return me(e,n,t)},async readPaymentSetup(t){Le(t);let n=O.readPaymentSetup;return me(e,n,t)},async readBillingInvoice(t){Le(t);let n=O.readBillingInvoice;return me(e,n,t)},async readBillingControls(t={}){Le(t);let n=O.readBillingControls;return me(e,n,t)},async prepareBillingAuthorization(t){Le(t);let n=O.prepareBillingAuthorization;return me(e,n,t)},async confirmBillingAuthorization(t){Le(t);let n=O.confirmBillingAuthorization;return me(e,n,t)},async setBillingCoupons(t){Le(t);let n=O.setBillingCoupons;return me(e,n,t,{request:"Invalid billing coupon list",response:"Invalid billing coupon receipt"})},async revokeBillingAuthorization(t){Le(t);let n=O.revokeBillingAuthorization;return me(e,n,t)},async listBillingInvoices(t={after:null,limit:25}){Le(t);let n=O.listBillingInvoices;return me(e,n,t)},async confirmBillingAdjustment(t){Le(t);let n=O.confirmBillingAdjustment;return me(e,n,t)}}}function Ph(e){return{async previewUpdate(t){Le(t);let n=O.previewUpdate;return me(e,n,t)},async update(t){Le(t);let n=O.update;return me(e,n,t)},async readSubscriptionUpdate(t){Le(t);let n=O.readSubscriptionUpdate;return me(e,n,t)},async restoreNativePurchase(t){Le(t);let n=O.restoreNativePurchase;return me(e,n,t)},async previewAttach(t){Le(t);let n=O.previewAttach;return me(e,n,t)},async attach(t){Le(t);let n=O.attach;return me(e,n,t)},async readSubscriptionOperation(t){Le(t);let n=O.readSubscriptionOperation;return me(e,n,t)}}}function Ch(e){return{async redeemReward(t){return Le(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 Le(t),(await me(e,O.claimRewardProduct,t,{request:"Invalid reward product claim",response:"Invalid reward product checkout"})).checkout},async createReferralCode(t){return Le(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 _h(e){return{...vh(e),...wh(e),...Oh(e),...Ph(e),...Ch(e)}}function Eh(e){return{async resolveContent(t){Le(t);let n=O.resolveContent;return me(e,n,t)},async resolvePaywall(t){Le(t);let n=O.resolvePaywall;return me(e,n,t)},async resolveOffering(t){Le(t);let n=O.resolveOffering;return me(e,n,t)}}}var Zu=e=>new TextEncoder().encode(JSON.stringify(e)).length,Rh=16384;function kh(e,t){let n=0,r,i=d=>{r={config:structuredClone(d),until:Date.now()+3e4}},a=[],o=null,s;function c(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}function u(){s||!a.length||(s=setTimeout(()=>{s=void 0,f().catch(()=>{}).finally(u)},5e3),typeof s=="object"&&"unref"in s&&s.unref())}function l(d,A={},k={}){if(c(),r&&Date.now()<r.until&&!Bm(r.config,d))return;h();let g=O.trackEvents.request.parse({events:[{eventUuid:crypto.randomUUID(),timestamp:new Date().toISOString(),name:d,properties:A,...k}]}).events[0];if(Zu({events:[g]})>Rh)throw new b("INVALID_REQUEST","Event exceeds the delivery size limit");if(a.length>=500)throw new b("EVENT_QUEUE_FULL","Flush pending events before tracking more");a.push(structuredClone(g)),u()}async function f(d=!1){if(c(),o)return o;let A=n,k=(async()=>{let g={inserted:0,duplicates:0,rejected:0,skipped:0},y=a.length;for(;y&&A===n;){let I=[],w=Zu({events:[]});for(let E of a.slice(0,Math.min(y,100))){let ae=Zu(E)+(I.length?1:0);if(I.length&&w+ae>Rh)break;I.push(E),w+=ae}let C=O.trackEvents,j=await me(e,C,{events:I},void 0,{keepalive:d});if(A!==n)throw new b("IDENTITY_CHANGED","Event identity changed during delivery");if(j.inserted+j.duplicates+j.rejected+j.skipped!==I.length)throw new b("INVALID_RESPONSE","Incomplete event acknowledgement");i(j.analyticsConfig),a.splice(0,I.length),y-=I.length,g.inserted+=j.inserted,g.duplicates+=j.duplicates,g.rejected+=j.rejected,g.skipped+=j.skipped}return g})();o=k;try{return await k}finally{o===k&&(o=null)}}let m;function h(){if(m||typeof document>"u")return;let d=()=>{document.visibilityState==="hidden"&&t()&&a.length&&f(!0).catch(()=>{})};document.addEventListener("visibilitychange",d),m=()=>document.removeEventListener("visibilitychange",d)}return{rememberConfiguration:i,track:l,flush:f,reset(){n++,r=void 0,clearTimeout(s),s=void 0,a=[],o=null},detachVisibility(){m?.(),m=void 0}}}function Wu(e){let t=null,n=null,r=0,i=0,a=new Set,o=null,s=null,c=new Set,u=()=>{for(let g of c)try{g()}catch{}},l={attributes:xt.parse(e.attributes??{}),onFeatureUsage:e.onFeatureUsage?(g,y)=>{!a.has(g)&&(!t||!("analyticsConfig"in t)||t.analyticsConfig.featureUsageEnabled)&&e.onFeatureUsage(g,structuredClone(y),structuredClone(l.attributes))}:void 0,onExperimentViewed:e.onExperimentViewed?(g,y)=>(!t||!("analyticsConfig"in t)||t.analyticsConfig.experimentViewsEnabled)&&e.onExperimentViewed(structuredClone(g),structuredClone(y),structuredClone(l.attributes)):void 0,stickyBucketAssignmentDocs:structuredClone(e.stickyBucketAssignmentDocs),saveStickyBucketAssignmentDoc:e.saveStickyBucketAssignmentDoc?g=>e.saveStickyBucketAssignmentDoc(structuredClone(g)):void 0,trackedFeatureUsage:{},trackedExperiments:new Set},f=()=>({value:null,source:"unknownFeature",on:!1,off:!0,ruleId:""});function m(g,y=new Set){return a.has(g)?!o||!o.features[g]||["unknownFeature","cyclicPrerequisite"].includes(o.features[g].source):y.has(g)?!1:(y.add(g),(t?.features[g]?.rules??[]).some(I=>[...I.parentConditions??[],...(I.tracks??[]).flatMap(w=>w.experiment.parentConditions??[])].some(w=>m(w.id,y))))}let h=g=>{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 o?.expiresAt&&Date.parse(o.expiresAt)<=Date.now()&&(o=null,l.features=t.features),a.has(g)?!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now()?f():structuredClone(o.features[g]??f()):e.evaluateRemote&&(l.attributes?.merchandise||l.attributes?.merchandiseId)&&!o||m(g)?f():structuredClone(Vn(g,l))};async function d(){if(!t||!a.size&&!l.attributes?.merchandise&&!l.attributes?.merchandiseId)return;if(!e.evaluateRemote){if(a.size)throw new Error("Remote Feature evaluation requires a server loader");return}let g=i;if(s?.revision===g)return s.loading;let y=r,I=t,w=[...a],C=(async()=>{let j=ka.parse(await e.evaluateRemote({attributes:structuredClone(l.attributes),features:w}));if(!(y!==r||g!==i||I!==t)){if(e.assertUsable?.(I.generation),j.generation!==I.generation)throw new Error("Feature configuration changed; refresh before evaluation");if(w.some(E=>!Object.hasOwn(j.features,E))||Object.keys(j.features).some(E=>!a.has(E)))throw new Error("Invalid remote Feature results");if(l.attributes?.merchandise||l.attributes?.merchandiseId){if(!j.merchandiseContext)throw new Error("Server did not resolve merchandise context");l.attributes=xt.parse({...l.attributes,...j.merchandiseContext})}o=structuredClone(j),l.features={...I.features,...Object.fromEntries(Object.entries(o.features).map(([E,ae])=>[E,{defaultValue:ae.value}]))},u()}})();s={revision:g,loading:C};try{await C}finally{s?.loading===C&&(s=null)}}function A(){d().catch(g=>{try{e.onError?.(g)}catch{}})}async function k(){if(n)return n;let g=r,y=(async()=>{let I=await e.load(),w="remoteFeatures"in I?ao.parse(I):null,C=w??mn.parse(I);if(C.scope.projectId!==e.scope.projectId||C.scope.environment!==e.scope.environment)throw new Error("Feature payload scope changed");if(g!==r)throw new Error("Feature client was reset");if(e.assertUsable&&t?.generation===C.generation){let{evaluatedAt:E,expiresAt:ae,...xe}=t,{evaluatedAt:Oe,expiresAt:Ee,...ye}=C;if(vt(xe)!==vt(ye))throw new Error("Immutable Feature generation changed content");return t.evaluatedAt=C.evaluatedAt,t.expiresAt=C.expiresAt,u(),(!o||o.expiresAt&&Date.parse(o.expiresAt)<=Date.now())&&A(),structuredClone(t)}let j=new Set(w?.remoteFeatures??[]);if([...j].some(E=>Object.hasOwn(C.features,E)))throw new Error("Remote Feature definitions must not be delivered locally");return t&&"analyticsConfig"in t&&"analyticsConfig"in C&&!t.analyticsConfig.experimentViewsEnabled&&w?.analyticsConfig.experimentViewsEnabled&&l.trackedExperiments?.clear(),t=structuredClone(C),a=j,o=null,s=null,i++,l.features=t.features,l.savedGroups=Yr(t.savedGroups),l.trackedFeatureUsage={},u(),A(),structuredClone(t)})();n=y;try{return await y}finally{n===y&&(n=null)}}return{init:k,refresh:k,refreshRemote:d,get generation(){return t?.generation??null},get expiresAt(){return t?.expiresAt??null},subscribe(g){return c.add(g),()=>{c.delete(g)}},setAttributes(g){let y=xt.parse(g);(l.attributes?.merchandise||l.attributes?.merchandiseId||g.merchandise||g.merchandiseId)&&l.trackedExperiments?.clear(),l.attributes=y,i++,o=null,s=null,l.features=t?.features??{},l.trackedFeatureUsage={},u(),A()},evalFeature:h,isOn(g){return h(g).on},isOff(g){return h(g).off},getFeatureValue(g,y){let I=h(g).value;return structuredClone(I===null?y:I)},reset(){r++,i++,n=null,s=null,t=null,o=null,a.clear(),l.features={},l.savedGroups={},l.stickyBucketAssignmentDocs={},l.attributes={},l.trackedFeatureUsage={},l.trackedExperiments?.clear(),u()}}}function jh(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 DI(e){let t=jh(e),{merchandiseId:n,merchandise:r,...i}=e;return{...i,...t?{merchandise:t}:{}}}function Th(e,t,n,r,i){if(i&&r&&(i.scope.projectId!==r.projectId||i.scope.environment!==r.environment))throw new b("SCOPE_MISMATCH","Configuration belongs to another App/environment");let a=0,o=new Set;function s(){if(!t())throw new b("NOT_IDENTIFIED","Call identify before using Features or events")}async function c(u={}){i||s();let l=a,f=!1,m=async()=>{if(f||l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Oe=O.getFeatures,Ee=i?{scope:{projectId:i.scope.projectId,environment:i.scope.environment},payload:await i.features()}:await me(e,Oe,{});if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");if(r&&(Ee.scope.projectId!==r.projectId||Ee.scope.environment!==r.environment))throw new b("INVALID_RESPONSE","Feature response scope changed");return n.rememberConfiguration(Ee.payload.analyticsConfig),Ee},h=await m(),d=!0,A,k=Oe=>{try{u.onError?.(Oe)}catch{}},g=(Oe,Ee,ye)=>{try{let mt=jh(ye);n.track(Oe,Ee,mt?{merchandise:mt}:{})}catch(mt){k(mt)}},y=Wu({assertUsable:i?.assertFeatures,scope:h.scope,attributes:u.attributes,onError:u.onError,load:async()=>d?(d=!1,h.payload):(await m()).payload,evaluateRemote:async Oe=>{if(l!==a)throw new b("IDENTITY_CHANGED","Feature identity changed");let Ee=O.evaluateFeatures,ye=await me(e,Ee,{...Oe,attributes:DI(Oe.attributes)});if(ye.scope.projectId!==h.scope.projectId||ye.scope.environment!==h.scope.environment)throw new b("INVALID_RESPONSE","Remote Feature response scope changed");return{generation:ye.generation,evaluatedAt:ye.evaluatedAt,expiresAt:ye.expiresAt,features:ye.features,...ye.merchandiseContext?{merchandiseContext:ye.merchandiseContext}:{}}},onExperimentViewed:(Oe,Ee,ye)=>g("Experiment Viewed",{experimentId:Oe.key,variationId:Ee.key},ye),onFeatureUsage:(Oe,Ee,ye)=>g("Feature Evaluated",{feature:Oe,value:Ee.value,source:Ee.source,ruleId:Ee.ruleId,...Ee.experimentResult?{variationId:Ee.experimentResult.key}:{}},ye)}),I=y.refresh;function w(){clearTimeout(A),!i&&(f||l!==a||!y.expiresAt||(A=setTimeout(()=>{C().catch(k)},Math.min(2147483647,Math.max(1e3,Date.parse(y.expiresAt)-Date.now()))),typeof A=="object"&&"unref"in A&&A.unref()))}async function C(){try{return await I()}finally{w()}}let j=()=>{f||C().catch(k)},E=y.subscribe(w),ae=i?.subscribe(()=>{!f&&i.fresh&&C().catch(k)});function xe(){f||(f=!0,clearTimeout(A),typeof window<"u"&&window.removeEventListener("focus",j),E(),ae?.(),y.reset(),o.delete(xe))}o.add(xe);try{await y.init(),(u.attributes?.merchandise||u.attributes?.merchandiseId)&&await y.refreshRemote()}catch(Oe){throw xe(),Oe}return w(),!i&&typeof window<"u"&&window.addEventListener("focus",j),Object.assign(y,{refresh:C,destroy:xe})}return{features:c,reset(u){a++,u();for(let l of o)l()}}}import{z as FI}from"zod";function Nh(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=FI.object({funnelId:Wa.shape.id,funnelVersionId:Wa.shape.versionId.optional()}).safeParse(n);if(!r.success)throw new b("INVALID_REQUEST","A valid Funnel source is required");let i=Object.freeze(r.data);function a(o){if("customerId"in o)throw new b("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 b("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 Dh(e){let t=ur(e),n=t.request,r;try{r=Qg(e.push,t,e.scope??e.configuration?.scope)}catch(s){throw t.dispose(),s}let i=Ih(t,()=>{o.reset(a.reset),a.detachVisibility()},{beforeIdentify:r.identify,beforeReset:r.reset,afterChange:r.start,beforeDestroy:r.destroy}),a=kh(n,i.isIdentified),o=Th(n,i.isIdentified,a,e.scope,e.configuration);return{session:t.session,...Zg(n,r),..._h(n),...Eh(n),forFunnel(s){return i.assertActive(),Nh(n,s)},async features(s={}){return i.assertActive(),o.features(s)},track(s,c,u={}){return a.track(s,c,u)},flush(){return a.flush()},...i.methods}}function Ci(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)=>Ci(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)&&Ci(a,Reflect.get(t,i)))}function us(e,t){let n=kg.safeParse(t);if(!n.success)throw new b("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 b("SCOPE_MISMATCH","Funnel scope changed");return r}var _i=/^gg_sk_[A-Za-z0-9_-]{32,128}$/;function ls(e){let t=Et.test(e.apiKey);if(typeof window<"u"&&!t)throw new b("SERVER_ONLY","Funnel starts are issued by your backend");if(!t&&!_i.test(e.apiKey))throw new b("INVALID_TOKEN","A customer credential or server API key is required");return{async start(n){let r=It.safeParse({...n,operation:"start"});if(!r.success||r.data.operation!=="start"||(t?r.data.customer!==void 0:r.data.customer===void 0))throw new b("INVALID_REQUEST","Invalid current Funnel start");let i=r.data,a=ur({...e,timeoutMs:e.timeoutMs??35e3});try{e.session||a.identify(e.apiKey);let o=us(e,await a.request("funnels",i));if(!o.runToken)throw new b("INVALID_RESPONSE","Funnel start credentials are missing");if(o.run.source.id!==i.funnelId||o.run.locale!==(i.locale??"en")||!Ci(o.run.parameters,i.parameters??{})||(i.customer?!o.customerId||i.customer.type==="id"&&o.customerId!==i.customer.value:o.customerId!==void 0))throw new b("INVALID_RESPONSE","Funnel start contract changed");return{...o,runToken:o.runToken}}finally{a.dispose()}}}}async function Yu(e,t,n){if(Number(e.headers.get("content-length"))>t)throw e.body?.cancel().catch(()=>{}),n.error("limit");let r=e.body?.getReader();if(!r)throw n.error("missing");let i=[],a=0,o=!1,s=()=>{},c=new Promise((f,m)=>{s=()=>m(n.signal?.reason),n.signal?.addEventListener("abort",s,{once:!0}),n.signal?.aborted&&s()});try{for(;;){let f=await Promise.race([r.read(),c]);if(f.done){o=!0;break}if(a+=f.value.length,a>t)throw n.error("limit");i.push(f.value)}}finally{n.signal?.removeEventListener("abort",s),o||r.cancel().catch(()=>{}),r.releaseLock()}n.signal?.throwIfAborted();let u=new Uint8Array(a),l=0;for(let f of i)u.set(f,l),l+=f.length;return u}async function Fh(e,t,n){return new TextDecoder("utf-8",{fatal:!0}).decode(await Yu(e,t,n))}function ds(e,t){let n=typeof e=="string"?new TextEncoder().encode(e):e;return n.byteLength===t.byteLength&&uu(n)===t.sha256}async function ps(e,t){let n=Nr.parse(t),{artifact:r,environmentId:i}=n.content,a=new hn(e.baseUrl??cr).origin,o=new hn(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 b("INVALID_RESPONSE","Public Paywall locator is not trusted");let s=new AbortController,c,u=new Promise((f,m)=>{c=setTimeout(()=>{let h=new b("TIMEOUT","Public Paywall read timed out");s.abort(h),m(h)},Xt.initializationMs)}),l=(async()=>{let f=await(e.fetch??globalThis.fetch)(o,{method:"GET",credentials:"omit",redirect:"error",cache:"default",signal:s.signal});if(s.signal.aborted&&(f.body?.cancel().catch(()=>{}),s.signal.throwIfAborted()),!f.ok||!f.headers.get("content-type")?.toLowerCase().startsWith("application/json")||Number(f.headers.get("content-length"))>r.byteLength)throw f.body?.cancel().catch(()=>{}),new b("INVALID_RESPONSE","Public Paywall is unavailable");let m=await Yu(f,r.byteLength,{signal:s.signal,error:h=>new b("INVALID_RESPONSE",h==="missing"?"Public Paywall body is missing":"Public Paywall exceeds its byte limit")});if(!ds(m,r))throw new b("INVALID_RESPONSE","Public Paywall digest or size changed");return Df(n,JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(m)))})();try{return await Promise.race([l,u])}finally{clearTimeout(c)}}var Mh=(e,t)=>new b(e,t);async function Xu(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 b("CONFIGURATION_UNAVAILABLE","Local execution requires public configuration");if(e.scope.environmentId!==r.environmentId)throw new b("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=MI(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 MI(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=Cu({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:mn.parse(o)}),c=qI(s,n.document,{...t,...r}),u=c.steps.at(-1),l=c.boundary??(u?.result.port==="value"?{nodeId:u.nodeId,visit:t.visit+c.steps.length-1}:null);return l?{runId:t.id,from:{nodeId:t.nodeId,visit:t.visit,revision:t.revision},nodeId:l.nodeId,visit:l.visit,terminal:!c.boundary}:null}function qI(e,t,n){return Hg(e,t,n,Mh)}import{z as dn}from"zod";var qh=It.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 b("COMMAND_STORAGE_INVALID","Stored mutation required");return e}),Bh=dn.strictObject({schemaVersion:dn.literal(1),scope:je,runId:dn.uuid(),funnelId:dn.uuid(),versionId:dn.uuid(),processBindingIds:dn.record(dn.uuid(),dn.uuid().nullable()).optional(),command:qh.optional(),closeCommand:qh.refine(e=>e.operation==="close").optional(),purchase:dn.strictObject({receiptId:dn.uuid(),operationId:dn.uuid(),generation:dn.number().int().nonnegative()}).optional(),closed:dn.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"),Zt=()=>new b("COMMAND_STORAGE_CONFLICT","Another host changed this Run's pending command"),ms=(e,t)=>JSON.stringify(e)===JSON.stringify(t);function Vh(e){let t=0,n=null,r=u=>JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]),i=Promise.resolve();async function a(){let u=await e.read();if(!Number.isSafeInteger(u.revision)||u.revision<0)throw new b("COMMAND_STORAGE_INVALID","Invalid command storage revision");return{revision:u.revision,entry:u.entry===null?null:Bh.parse(u.entry)}}function o(u){let l=i.then(u);return i=l.catch(()=>{}),l}async function s(u){for(let l=0;l<4;l++){let f=await a();if(f.entry&&n!==null&&r(f.entry)!==n)throw Zt();let m=u(f.entry,f.revision);if(ms(f.entry,m)){t=f.revision;return}let h=await e.write(f.revision,m);if(h!==null){if(!Number.isSafeInteger(h)||h<=f.revision)throw Zt();t=h;return}}throw Zt()}function c(u,l){if(!u||!l)return u;if(u.processBindingIds&&Object.hasOwn(u.processBindingIds,l)){let f={...u.processBindingIds};delete f[l],u={...u,processBindingIds:f}}return u.command?.requestId===l?u.closeCommand?{...u,command:u.closeCommand,closeCommand:void 0}:u.purchase?{...u,command:void 0}:null:u.closeCommand?.requestId===l?{...u,closeCommand:void 0}:u}return{bind(u){let l=JSON.stringify([u.scope,u.runId,u.funnelId,u.versionId]);if(n!==null&&n!==l)throw Zt();n=l},async load(){let u=await a();return t=u.revision,n=u.entry?r(u.entry):null,u.entry},retain(u){let l=Bh.parse(u),f=l.command;return!f||n!==null&&r(l)!==n?Promise.reject(Zt()):(n??(n=r(l)),o(()=>s((m,h)=>{if(m&&!ms(r(m),r(l)))throw Zt();if(m&&l.processBindingIds){for(let[d,A]of Object.entries(l.processBindingIds))if(m.processBindingIds&&Object.hasOwn(m.processBindingIds,d)&&m.processBindingIds[d]!==A)throw Zt();m={...m,processBindingIds:{...m.processBindingIds,...l.processBindingIds}}}if(!m){if(h!==t&&f.operation!=="close")throw Zt();return l}if(!m.command)return{...m,command:f,...f.operation==="close"?{closed:!0}:{}};if(f.operation==="close"&&m.command.operation!=="close"){if(m.command.requestId===f.requestId||m.closeCommand&&!ms(m.closeCommand,f))throw Zt();return{...m,closeCommand:f,closed:!0}}if(!ms(m.command,f))throw Zt();return m})))},observePurchase(u,l,f,m){return o(()=>s((h,d)=>{if(!h&&d!==t||h&&r(h)!==r({...u,schemaVersion:1}))throw Zt();if(h?.purchase&&h.purchase.generation>l.generation)return c(h,m);if(h?.purchase&&h.purchase.generation===l.generation&&h.purchase.operationId!==l.operationId)throw Zt();return f?!h?.purchase||h.purchase.operationId!==l.operationId?c(h,m):c(h.command?{...h,purchase:void 0}:null,m):c({schemaVersion:1,...u,...h,purchase:l},m)}))},settle(u){return o(()=>s(l=>c(l,u)))}}}function Lh(e){let t,n,r=()=>new b("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??cr).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 b?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 Uh(e,t){let n=t&&{...t},r=null,i=0,a=new AbortController;function o(){i++,a.abort(new b("IDENTITY_CHANGED","Run identity changed")),a=new AbortController}let s=!1,c,u=0,l=new Set;return{get scope(){return n},bindScope(f){if(n&&(n.projectId!==f.projectId||n.environment!==f.environment))throw new b("SCOPE_MISMATCH","Run scope changed");n??(n={...f})},get view(){return r},get generation(){return i},get signal(){return a.signal},get disposed(){return s},get customerToken(){return c},get readSequence(){return u},nextRead(){return++u},assertCurrent(f,m="Run identity changed during the request"){if(f!==i||s)throw new b("IDENTITY_CHANGED",m)},assertRun(f){if(r&&(f.id!==r.id||f.source.type!==r.source.type||f.source.id!==r.source.id||f.source.versionId!==r.source.versionId||f.locale!==r.locale||!Ci(f.parameters,r.parameters)))throw new b("INVALID_RESPONSE","Run version changed");if(e&&f.source.id!==e)throw new b("INVALID_RESPONSE","Run belongs to another Funnel")},publish(f,m,h,d,A){if(!(f.operation==="review"&&r&&r!==h&&m.run.revision<=r.revision)&&!(r&&m.run.revision===r.revision&&d!==void 0&&d<u)&&(f.operation==="review"&&!m.run.stopped&&["running","waiting"].includes(m.run.status)&&r&&m.run.nodeId===r.nodeId&&m.run.visit===r.visit&&m.run.revision===r.revision&&(m.run.screen=r.screen,(r.paywall?.quote?.operationId===m.review?.activeOperationId||!r.paywall?.quote&&m.review?.activeOperationId===null)&&(m.run.paywall=r.paywall)),!(r?.paywall&&m.run.paywall&&r.paywall.receiptId===m.run.paywall.receiptId&&(m.run.paywall.selectionGeneration??0)<(r.paywall.selectionGeneration??0)))){if(!r||m.run.revision>=r.revision)r=m.run;else if(!A)return;if(r)for(let k of l)try{k(structuredClone(r))}catch{}}},identify(f){if(s)throw new b("IDENTITY_CHANGED","Controller was reset");if(!Et.test(f))throw new b("INVALID_TOKEN","Customer credential required");o(),c=f},subscribe(f){return l.add(f),()=>l.delete(f)},reset(){s||(s=!0,o(),c=void 0,r=null,l.clear())}}}function lr(e){let{customerToken:t,...n}=e;return n}var BI=e=>!(e instanceof b)||e.status===void 0||e.status>=500||[401,425].includes(e.status)||e.recovery==="recover_operation";function zh({journal:e,state:t,call:n,processIdentity:r}){let i=null,a=null,o=!1,s={command:null,close:null},c=new Set,u,l=null,f=e?e.load().then(g=>{if(t.disposed)throw new b("IDENTITY_CHANGED","Controller was reset during command restoration");if(l=g,!g)return;if(r){if([g.command,g.closeCommand].some(I=>I&&!Object.hasOwn(g.processBindingIds??{},I.requestId)))throw new b("COMMAND_STORAGE_INVALID","The original process identity is missing");r.restore(g.processBindingIds??{})}if(t.scope&&(g.scope.projectId!==t.scope.projectId||g.scope.environment!==t.scope.environment))throw new b("SCOPE_MISMATCH","Pending command belongs to another scope");if(u=g.purchase,o=g.closed===!0,!g.command)return;let y=g.command;i=y.operation==="close"?null:y,a=y.operation==="close"?y:g.closeCommand?.operation==="close"?g.closeCommand:null,a&&(o=!0);for(let I of[i,a])I&&c.add(I.requestId)}):Promise.resolve();f.catch(()=>{});async function m(g){e&&await f;let y=t.generation;if(e){if(!t.view||!t.scope)throw new b("COMMAND_STORAGE_INVALID","Read the original scoped Run before persisting a mutation");await e.retain({schemaVersion:1,scope:t.scope,runId:t.view.id,funnelId:t.view.source.id,versionId:t.view.source.versionId,command:lr(g),...r?{processBindingIds:{[g.requestId]:r.binding(g.requestId)}}:{}})}if(y!==t.generation||i!==g&&a!==g)throw new b("IDENTITY_CHANGED","Run changed before command dispatch");let I=c.has(g.requestId);c.add(g.requestId);try{return await n(g)}catch(w){throw y===t.generation&&(i===g||a===g)&&!I&&!BI(w)&&(e&&await e.settle(g.requestId),y===t.generation&&k(g)),w}}function h(g){let y=It.parse(g);if(y.operation==="start"||y.operation==="get"||y.operation==="review")throw new b("INVALID_REQUEST","Mutation required");if(o&&y.operation!=="close"){if(i?.requestId===y.requestId)return A(y.requestId);throw new b("COMMAND_PENDING","Close preserves the original recovery record; settle it by identity")}if(y.operation==="close"){if(i?.requestId===y.requestId)throw new b("INVALID_REQUEST","Close requires its own request identity");if(o=!0,a&&JSON.stringify(lr(a))!==JSON.stringify(lr(y)))throw new b("COMMAND_PENDING","Retry the original Close");return a??(a=y),s.close?s.close:d(a,"close")}if(i){if(JSON.stringify(lr(i))!==JSON.stringify(lr(y)))throw new b("COMMAND_PENDING","Retry the original command before sending another");if(s.command)return s.command}else i=y;return d(i,"command")}function d(g,y){let I=m(g);s[y]=I;let w=()=>{s[y]===I&&(s[y]=null)};return I.then(w,w),I}function A(g){return n({operation:"get",settlementRequestId:g})}function k(g){return!g||i!==g&&a!==g?!1:(i===g&&(i=null),a===g&&(a=null),c.delete(g.requestId),!i&&!a&&(l=null),!0)}return{ready:f,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(g){if(l&&(g.run.id!==l.runId||g.run.source.id!==l.funnelId||g.run.source.versionId!==l.versionId))throw new b("SCOPE_MISMATCH","Stored command belongs to another Run or Version")},async observe(g,y,I,w){let C=g.operation==="get"?g.settlementRequestId:"requestId"in g&&g.operation!=="start"?g.requestId:void 0,j=C&&y.settlement?.state==="settled"&&y.run.pendingRequest?.requestId!==C&&(g.operation==="get"||!o||g.operation==="close"||!["running","waiting"].includes(y.run.status))?C:void 0,E=i?.requestId===j?i:a?.requestId===j?a:void 0;e?.bind({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId});let ae=y.run.paywall,xe=ae??y.purchase,Oe=xe?.operation,Ee=y.settlement&&(!ae||ae.purchaseRequestId===y.settlement.requestId)&&(!u||u.operationId===y.settlement.operationId)?y.settlement:void 0,ye=Oe?.operationId??xe?.quote?.operationId??Ee?.operationId,mt=xe?.receiptId??Ee?.receiptId,He=ae?.selectionGeneration??u?.generation??0;if(e&&ye&&mt&&g.operation!=="review"&&(!t.view||y.run.revision>=t.view.revision)&&(w===void 0||w>=t.readSequence)&&(!u||He>=u.generation)){let ke={receiptId:mt,operationId:ye,generation:He},Xe=Oe?.status==="complete"||xe?.canReselect===!0;await e.observePurchase({scope:y.scope,runId:y.run.id,funnelId:y.run.source.id,versionId:y.run.source.versionId},ke,Xe,j),t.assertCurrent(I),(!u||ke.generation>=u.generation)&&(w===void 0||w>=t.readSequence)&&(Xe?u?.operationId===ke.operationId&&(u=void 0):u=ke)}else e&&j&&await e.settle(j);return t.assertCurrent(I),j?k(E):!1},stop(){o=!0},submit:h,settle:A,reset(){o=!0,i=null,a=null,u=void 0,l=null,s.close=null,c.clear(),s.command=null}}}function dr(e){if(e={...e},typeof e.runToken!="string"||!/^gg_fr_[A-Za-z0-9_-]{43}$/.test(e.runToken))throw new b("INVALID_TOKEN","Run credential required");if(e.serverKey&&(typeof window<"u"||!_i.test(e.serverKey)))throw new b("SERVER_ONLY","Run Server-Key proof belongs to the merchant backend");if(e.serverKey&&e.session)throw new b("INVALID_REQUEST","Choose Customer session or Server-Key proof for this Run");let t=ur({...e,session:void 0,timeoutMs:e.timeoutMs??35e3}),n=Uh(e.funnelId,e.scope??e.configuration?.scope),r=e.session?.subscribeIdentity(u),i=null,a=e.funnelCommandStorage??(typeof window<"u"&&window.isSecureContext?Lh(e):void 0),o=a&&Vh(a),s=zh({journal:o,state:n,call:l,processIdentity:e.process});async function c(y){if(e.process)return e.process.request(y);let I=n.generation;n.assertCurrent(I);let w=performance.now()+(e.timeoutMs??35e3),C=n.customerToken??("customerToken"in y?y.customerToken:void 0);if(e.session){let ae=n.signal,xe,Oe=()=>{},Ee=new Promise((ye,mt)=>{Oe=()=>mt(ae.reason),ae.addEventListener("abort",Oe,{once:!0}),xe=setTimeout(()=>mt(new b("TIMEOUT","Longplay request timed out")),Math.max(1,w-performance.now()))});try{C=await Promise.race([Promise.resolve().then(()=>(n.assertCurrent(I),e.session.access())),Ee])}finally{clearTimeout(xe),ae.removeEventListener("abort",Oe)}}n.assertCurrent(I);let j={...y,...C?{customerToken:C}:{}},E=y.operation==="page_experiments"?bo.parse(j):It.parse(j);return t.requestWithCredential("funnels",E,e.runToken,{headers:e.serverKey&&!C?{[jg]:e.serverKey}:void 0,timeoutMs:Math.max(1,w-performance.now())})}function u(){r?.(),n.reset(),s.reset(),i=null,t.dispose()}async function l(y,I){let w=n.generation,C=()=>n.assertCurrent(w);o&&await s.ready,C();let j=n.view,E=us(e,await c(y));if(y.operation==="review"&&!E.review)throw new b("INVALID_RESPONSE","Historical projection is missing");if(C(),E.runToken&&E.runToken!==e.runToken)throw new b("INVALID_RESPONSE","Run credential changed");let ae=y.operation==="get"?y.settlementRequestId:"requestId"in y&&y.operation!=="start"?y.requestId:void 0;if(ae&&E.settlement?.requestId!==ae)throw new b("INVALID_RESPONSE","Exact command settlement is missing or belongs to another command");s.assertBinding(E),n.assertRun(E.run),n.bindScope(E.scope);let xe=await s.observe(y,E,w,I);return!E.run.stopped&&["running","waiting"].includes(E.run.status)&&y.operation==="get"&&y.settlementRequestId||(C(),["running","waiting"].includes(E.run.status)||s.stop(),n.publish(y,E,j,I,xe)),E}let f=s.submit,m=null,h=new WeakMap;function d(y){let I=h.get(y);if(I)return I;let w=k(y);return h.set(y,w),w}let A=!1;async function k(y){let I=await y;if(I.run.instruction?.type!=="evaluate_segment")return I;if(m)return m;A=!0;let w=n.generation,C=(async()=>{for(let j=0;j<32&&I.run.instruction?.type==="evaluate_segment";j++){if(s.pending||s.closeRequested)return I;let E=I.run;if(I.run.instruction?.type==="evaluate_segment"){let{advance:xe}=await Xu(e.configuration,E,{predict:!1});if(w!==n.generation)throw new b("IDENTITY_CHANGED","Run identity changed during segment calculation");if(s.pending||s.closeRequested)return I;if(n.view&&(n.view.revision!==E.revision||n.view.visit!==E.visit||n.view.nodeId!==E.nodeId))return l({operation:"get"});let Oe=!0;Xu(e.configuration,E).then(({prediction:Ee})=>{Oe&&w===n.generation&&!s.closeRequested&&n.view?.id===E.id&&!n.view.stopped&&n.view.nodeId===E.nodeId&&n.view.visit===E.visit&&n.view.revision===E.revision&&(i=Ee)}).catch(()=>{});try{I=await f({operation:"commit_segment",requestId:Rg(E.id,E.visit,`segment:${E.revision}`),nodeId:E.nodeId,visit:E.visit,revision:E.revision,...xe})}finally{Oe=!1,i=null}}}return I})();m=C;try{return await C}finally{m===C&&(m=null)}}let g={get configuration(){return A?e.configuration:void 0},get configurationReady(){return!0},get view(){return n.view?structuredClone(n.view):null},get pendingCommand(){let y=s.closing??s.pending;return y?structuredClone(lr(y)):null},get pendingCommands(){return[s.pending,s.closing].filter(y=>y!==null).map(y=>structuredClone(lr(y)))},get pendingPurchase(){return s.purchase?structuredClone(s.purchase):null},get prediction(){let y=n.view;return i&&y&&!y.stopped&&["running","waiting"].includes(y.status)&&y.id===i.runId&&y.nodeId===i.from.nodeId&&y.visit===i.from.visit&&y.revision===i.from.revision&&!s.closeRequested?structuredClone(i):null},settle:s.settle,get webViewUrl(){return"bundled"},resolvePaywall(y){return ps(e,y)},async pageExperiments(y,I=[]){let w=n.generation;n.assertCurrent(w);let C=n.view?.id;if(!C)throw new b("INVALID_REQUEST","Read the Run before its page experiments");let j=Fg.parse(await c(bo.parse({operation:"page_experiments",release:y,usedReceiptIds:I})));if(n.assertCurrent(w),j.runId!==C||j.scope.projectId!==n.scope?.projectId||j.scope.environment!==n.scope?.environment)throw new b("SCOPE_MISMATCH","Page experiment Run changed");return j},review(y){return l({operation:"review",...y?{receiptId:y}:{}},n.nextRead())},async get(y,I){o&&await s.ready,I??(I=s.purchase&&{receiptId:s.purchase.receiptId,operationId:s.purchase.operationId});let w=n.nextRead();return d(l({operation:"get",...y?{data:y}:{},...I?{purchase:I}:{}},w))},resume(y=n.view?.pendingRequest?.requestId){return y?s.closeRequested?g.settle(y):s.pending?.requestId===y?d(f(s.pending)):d(f({operation:"resume",requestId:y})):Promise.reject(new b("INVALID_REQUEST","No interrupted command is available"))},submit(y){return d(f(y))},retry(){return s.closeFlight?s.closeFlight:s.closing?f(s.closing):s.closeRequested&&s.pending?g.settle(s.pending.requestId):s.inFlight?d(s.inFlight):s.pending?d(f(s.pending)):Promise.reject(new b("INVALID_REQUEST","No command is pending"))},identify(y){n.identify(y),i=null,t.reset()},subscribe:n.subscribe,reset:u};return g}function $h(e){if(!Et.test(e.customerToken))throw new b("INVALID_TOKEN","A customer credential is required");if(!e.scope)throw new b("INVALID_REQUEST","An explicit App and environment scope is required");let t=ls({...e,scope:e.scope,apiKey:e.customerToken});return{async start(n){let r=await t.start(n),i=dr({...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 Gh(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 Kh(e,t,n){if(e.operationId!==t.operationId||t.currency!==void 0&&e.currency!==t.currency)throw new b("INVALID_RESPONSE",n)}function Hh(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 b("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 b("INVALID_RESPONSE",n)}function Qh(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 Jh(e,t){if(!Et.test(t.customerToken))throw new b("INVALID_TOKEN","A verified Customer credential is required");if(e.session&&e.session.peek()!==t.customerToken)throw new b("SCOPE_MISMATCH","Paywall credential does not match the shared session");let n=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}:{}}),r=ur(e);e.session||r.identify(t.customerToken);let i=null,a=!1,o=null,s=null,c=null,u=null;function l(){if(a)throw new b("IDENTITY_CHANGED","Paywall is closed")}async function f(){l();let A=O.resolvePaywall,k=await me(r.request,A,{...n,selector:i?{type:"version",versionId:i.id}:n.selector}),g=await ps(e,k.paywall);if(l(),t.paywallVersionId?g.id!==t.paywallVersionId:g.paywallId!==t.paywallId)throw new b("INVALID_RESPONSE","The requested Paywall changed");if(i&&(!Gh(g,i)||g.paywallId!==i.paywallId))throw new b("INVALID_RESPONSE","The pinned Paywall or Offering Version changed");return i=g,structuredClone(i)}async function m(A){if(l(),u&&A!=="read")throw new b("COMMAND_PENDING","Wait for the original quote");if(!o)throw new b("INVALID_REQUEST","A quoted purchase is required");let k=o,g=A==="read"?O.readSubscriptionOperation:O.attach,y=await me(r.request,g,{operationId:k.operationId,...A==="read"?{}:{intent:A}});return Kh(y.operation,{operationId:k.operationId,currency:n.commerce.currency},"The purchase operation changed"),l(),o?.operationId!==k.operationId?structuredClone(y.operation):(s=Qh(s,y.operation),structuredClone(s))}let h={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:f,async preview(A){if(l(),!i)throw new b("INVALID_REQUEST","Load the Paywall first");let k=i.document.buttons[A.actionId];if(k?.type!=="checkout")throw new b("INVALID_REQUEST","Choose an authored purchase action");let g=Fm(k.product,A.selection,i.capabilities);if(!g)throw new b("PRODUCT_UNAVAILABLE","Choose an available Product");let y=Pf(i.document.screen,g,A.selection,i.capabilities),I=O.previewAttach.request.parse({funnelId:n.funnelId,funnelVersionId:n.funnelVersionId,requestId:A.requestId,plans:[{productVersionId:g,...Object.keys(y).length?{featureQuantities:y}:{}}],provider:n.commerce.provider,currency:n.commerce.currency,...A.offerId?{offerId:A.offerId}:{},...A.nativeOffer?{nativeOffer:A.nativeOffer}:{}}),w=JSON.stringify(I);if(c&&c!==w&&(u||!s||s.status==="pending"))throw new b("COMMAND_PENDING","Finish or cancel the original purchase before changing it");if(c===w){if(u)return u;if(o)return structuredClone(o)}c!==w&&(o=null,s=null),c=w;let C=(async()=>{let j=O.previewAttach,E=await me(r.request,j,I);return l(),Hh(E.quote,{productVersionId:g,featureQuantities:y,currency:n.commerce.currency,provider:n.commerce.provider},"The purchase quote changed its selected Product or presentment"),o=E.quote,s=null,structuredClone(o)})();u=C;try{return await C}finally{u===C&&(u=null)}},confirm:()=>m("confirm"),cancel:()=>m("cancel"),read:()=>m("read"),destroy(){a||(a=!0,d?.(),r.dispose(),i=null,o=null,s=null,c=null)}},d=e.session?.subscribeIdentity(h.destroy);try{return await f(),h}catch(A){throw h.destroy(),A}}function Zh(e,t){let n,r=0,i=-1,a,o=!1,s=()=>{if(o)throw new b("CLOSED","Native host was destroyed");if(!e.nativeModule)throw new b("CAPABILITY_UNAVAILABLE","Link IndianaBridge and supply nativeModule");return e.nativeModule},c=()=>new b("IDENTITY_CHANGED","Customer identity changed during the native operation"),u=t.subscribeIdentity(()=>{r++,i=-1;let h=r;n&&e.nativeModule&&n.then(d=>e.nativeModule.reset(d,h)).catch(()=>{})}),l=e.nativeEvents?.(h=>{!n||!e.nativeModule||typeof h?.requestId!="string"||(async()=>{let d=await n;if(h.instanceId!==d)return;if(h.kind==="credential"){let g=r,y=null;try{if(!o&&h.revision===g){let I=await t.access();!o&&r===g&&(y=I)}}finally{await e.nativeModule.provideCredential(d,h.requestId,y)}return}let A=!1,k=r;try{if(o||h.revision!==k||!e.onNativeAction)throw c();await e.onNativeAction(h.action),A=!o&&r===k}finally{await e.nativeModule.acknowledge(d,h.requestId,A)}})().catch(()=>{})});async function f(h,d={}){let A=s();if(t.snapshot()&&!e.nativeEvents)throw new b("CAPABILITY_UNAVAILABLE","Supply nativeEvents to share credential refresh with the native host");let k=r,g=await t.access();if(o||r!==k)throw c();if(!n){let w=A.create(JSON.stringify({baseUrl:e.baseUrl??"https://api.longplayai.com",scope:e.scope,timeout:(e.timeoutMs??15e3)/1e3,credentialEvents:!!e.nativeEvents}));n=w,w.catch(()=>{n===w&&(n=void 0)})}let y=await n;if(o||r!==k)throw c();if(i!==k){if(!a||a.epoch!==k){let C=(async()=>{if(await A.identify(y,JSON.stringify({revision:k,credentials:g})),o||r!==k)throw await A.reset(y,k),c();i=k})();a={epoch:k,task:C}}let w=a;try{await w.task}finally{a===w&&(a=void 0)}}let I=await A.invoke(y,h,JSON.stringify(d));if(o||r!==k)throw c();try{return JSON.parse(I)}catch{throw new b("INVALID_RESPONSE","Native host returned invalid JSON")}}async function m(h,d){let A=await f(h,d);if(!A||typeof A!="object"||Array.isArray(A)||A.status!=="complete"&&A.status!=="dismissed")throw new b("INVALID_RESPONSE","Native presentation returned an invalid result");return A}return{showFunnel(h){return m("showFunnel",{runToken:h})},showPaywall(h){return m("showPaywall",h)},showContent(h){return m("showContent",h)},purchaseSubscription(h,d){return f("purchaseSubscription",{operationId:h,accepted:d})},switchSubscription(h,d){return f("switchSubscription",{operationId:h,accepted:d})},restorePurchases(){return f("restorePurchases")},manageSubscriptions(h){return f("manageSubscriptions",h?{productId:h}:{})},async dismiss(){r++,i=-1,n&&await s().reset(await n,r)},async destroy(){o||(o=!0,r++,u(),l?.(),n&&e.nativeModule&&await e.nativeModule.destroy(await n))}}}var VI=O.trackUsage.request.shape.command,LI=O.trackUsage.response;function UI(e){let t=je.parse(e.scope),n=Dh({...e,scope:t}),r={...e,scope:t,session:n.session},i=Zh(e,n.session),a=0,o=!1;n.subscribeIdentity(()=>{a++});let s=()=>{if(o)throw new b("CLOSED","SDK client was destroyed");let c=n.session.peek();if(!c)throw new b("UNAUTHENTICATED","Identify the Customer first");return c};return{...n,native:i,async destroy(){o||(o=!0,a++,n.destroy(),await i.destroy())},funnel(){return $h({...r,customerToken:s()})},resumeFunnel(c){return s(),dr({...r,runToken:c})},paywall(c){return Jh(r,{...c,customerToken:s()})},async trackUsage(c){if(s(),!e.usageReporter)throw new b("INVALID_REQUEST","Configure your authenticated backend usageReporter");let u=VI.parse(c),l=a,f;try{f=await e.usageReporter(u)}catch(h){throw l!==a?new b("IDENTITY_CHANGED","Customer identity changed during usage reporting"):h}if(l!==a)throw new b("IDENTITY_CHANGED","Customer identity changed during usage reporting");let m=LI.parse(f);if(m.scope.projectId!==t.projectId||m.scope.environment!==t.environment)throw new b("INVALID_RESPONSE","Usage response scope differs");return m}}}import{z as KI}from"zod";import{z as Oo}from"zod";var zI=Oo.record(Oo.string().regex(/^[a-f0-9]{64}$/),Oo.strictObject({at:Oo.number(),text:Oo.string()})),Lr=2*1048576,$I=100;function GI(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Wh(e,t){let n=t===void 0?GI():t,r=new Map,i=0,a=!1,o=!1,s,c;async function u(f){if(!n)return null;let m;try{let h=await Promise.race([Promise.resolve().then(()=>n.getItem(f)),new Promise(d=>{m=setTimeout(()=>d(null),$I)})]);return typeof h=="string"&&h.length<=Lr&&new TextEncoder().encode(h).byteLength<=Lr?h:null}catch{return null}finally{clearTimeout(m)}}function l(){if(c)return c;let f=(async()=>{try{let m=await u(`${e}:artifacts`);if(m)return zI.parse(JSON.parse(m))}catch{}return{}})();return c=f,f.finally(()=>{c===f&&(c=void 0)}),f}return{async readManifest(){return u(e)},writeManifest(f){!n||f.length>Lr||new TextEncoder().encode(f).byteLength>Lr||(s=f,!o&&(o=!0,Promise.resolve().then(async()=>{try{for(;s!==void 0;){let m=s;try{await n.setItem(e,m)}catch{}s===m&&(s=void 0)}}finally{o=!1}})))},async readArtifact(f){let m=(await l())[f],h=Date.now();return m&&h>=m.at&&h-m.at<=Xt.retentionMs?m.text:void 0},writeArtifact(f,m){if(!n||m.length>Lr)return;let h=r.get(f);if(h?.text===m||!h&&r.size>=128)return;let d=new TextEncoder().encode(m).byteLength;i-(h?.byteLength??0)+d>Lr||(r.set(f,{text:m,byteLength:d}),i+=d-(h?.byteLength??0),!a&&(a=!0,Promise.resolve().then(async()=>{try{for(;r.size;){let A=new Map(r);try{let k={...await l()},g=Date.now();for(let[C,j]of A)k[C]={at:g,text:j.text};let y={},I=2,w=0;for(let[C,j]of Object.entries(k).sort(([,E],[,ae])=>ae.at-E.at)){if(j.at>g||g-j.at>Xt.retentionMs)continue;let E=new TextEncoder().encode(JSON.stringify({[C]:j})).byteLength;I+E>Lr||w>=128||(y[C]=j,I+=E,w++)}await n.setItem(`${e}:artifacts`,JSON.stringify(y))}catch{}finally{for(let[k,g]of A)r.get(k)===g&&(r.delete(k),i-=g.byteLength)}}}finally{a=!1}})))}}}var we=(e,t)=>new b(e,t),pr=()=>performance.now(),Yh=e=>{typeof e=="object"&&"unref"in e&&e.unref()};function HI(e){let t=au.parse(e.scope),n=new hn(e.origin??cr);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 we("INVALID_URL","Configuration requires a trusted HTTPS origin");let r=new Set([n.origin,...(e.assetOrigins??[]).map(W=>{let Q=new hn(W);if(Q.protocol!=="https:"||Q.username||Q.password||Q.search||Q.hash||Q.pathname!=="/")throw we("INVALID_URL","Invalid configuration asset origin");return Q.origin})]),i=e.fetch??globalThis.fetch.bind(globalThis),a=`/api/v1/configuration/${t.environmentId}`,o=`indiana:configuration:1:${n.origin}:${vt(t)}`,s=Wh(o,e.storage),c,u=0,l=0,f=!1,m=!1,h=0,d=0,A,k,g,y,I=0,w=new Set,C=new Set,j=new Map,E=new Map,ae=0,xe=!1;function Oe(){for(let W of w)try{W()}catch{}}function Ee(W){try{e.onError?.(W)}catch{}}let ye=()=>!m&&!f&&!!c&&pr()<u&&Date.now()<l;function mt(){if(!ye())throw we("CONFIGURATION_EXPIRED","Refresh configuration before using it")}function He(W,Q,ue){if(!j.has(W)){for(;j.size&&(j.size>=128||ae+ue>Xt.maxCacheBytes);){let le=j.entries().next().value;ae-=le[1].byteLength,j.delete(le[0])}j.set(W,{text:Q,byteLength:ue}),ae+=ue}}function ke(W,Q,ue){return Fh(W,Q,{signal:ue,error:le=>we("INVALID_RESPONSE",le==="missing"?"Configuration body is missing":"Configuration exceeds its byte limit")})}function Xe(W){let Q=new hn(W,n);if(!r.has(Q.origin)||Q.username||Q.password||Q.hash||Q.search)throw we("INVALID_URL","Configuration artifact origin is not trusted");return Q.href}async function Po(W,Q,ue=!1){let le=await i(Xe(W),{method:"GET",credentials:"omit",redirect:"error",cache:ue?"default":"no-cache",signal:Q,headers:{}});if(le.status===429){let We=le.headers.get("retry-after")??"";I=/^\d+$/.test(We)?Number(We)*1e3:Math.max(0,Date.parse(We)-Date.now())||15e3}if(!le.ok&&le.status!==304)throw we(`CONFIGURATION_HTTP_${le.status}`,"Configuration synchronization failed");return le}function Ur(W,Q,ue){let le=Date.parse(W.headers.get("x-indiana-config-validated-at")??""),We=Date.parse(W.headers.get("x-indiana-config-valid-until")??""),nt=Date.parse(W.headers.get("date")??""),Ue=W.headers.get("age"),en=Ue!==null&&/^\d+(\.\d+)?$/.test(Ue)?Number(Ue)*1e3:NaN;if(![le,We,nt,en].every(Number.isFinite)||We<=le||We-le>Xt.maxControlAgeMs||le>nt+1e3)throw we("INVALID_RESPONSE","Configuration freshness evidence is invalid");let Dt=Math.min(We-le,ue.maxControlAgeSeconds*1e3,Xt.maxControlAgeMs)-Math.max(en,nt-le,0)-(pr()-Q);if(Dt<=0)throw we("CONFIGURATION_EXPIRED","Configuration validation expired in transit");return pr()+Dt}function ut(){if(clearTimeout(g),clearTimeout(y),m||!w.size)return;ye()&&(y=setTimeout(()=>{ye()?ut():Oe()},Math.max(1,u-pr())),Yh(y));let W=d?Math.min(15e3,1e3*2**Math.min(d-1,4)):Math.min(15e3,(c?.policy.refreshIntervalSeconds??15)*1e3);g=setTimeout(()=>{Kt().catch(Ee)},Math.max(I,W*(.8+Math.random()*.2))),Yh(g)}async function Kt(){if(m)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");if(A)return A;let W=h,Q=new AbortController;k=Q;let ue=(async()=>{if(!xe){xe=!0;try{let _o=await s.readManifest();if(_o&&!c){let Mn=cu.parse(JSON.parse(_o));vt(Mn.scope)===vt(t)&&(c=Mn)}}catch{}}Q.signal.throwIfAborted();let Ue=c,en=pr(),qt=await Po(a,Q.signal);qt.status===304&&(!Ue||!qt.headers.has("x-indiana-config-validated-at")||!qt.headers.has("x-indiana-config-valid-until")||!qt.headers.has("age"))&&(qt=await Po(a,Q.signal));let Dt=qt.status===304?Ue:cu.parse(JSON.parse(await ke(qt,Xt.maxManifestBytes,Q.signal))),{generation:zr,...$r}=Dt,Fn=qt.headers.get("etag");if(vt(Dt.scope)!==vt(t)||kf($r)!==zr||Fn!==`"${zr}"`&&Fn!==`W/"${zr}"`)throw we("INVALID_RESPONSE","Configuration scope or content identity changed");if(Ue&&(Dt.revision<Ue.revision||Dt.revision===Ue.revision&&Dt.generation!==Ue.generation))throw we("INVALID_RESPONSE","Configuration revision moved backwards or changed identity");for(let[_o,Mn]of Object.entries(Ue?.funnels??{})){let hr=Dt.funnels[_o];if(hr&&(hr.controlRevision<Mn.controlRevision||hr.evaluationRevision<Mn.evaluationRevision||hr.controlRevision===Mn.controlRevision&&hr.state!==Mn.state||hr.evaluationRevision===Mn.evaluationRevision&&hr.evaluationMode!==Mn.evaluationMode))throw we("INVALID_RESPONSE","Funnel control revision changed identity")}let gr=Ur(qt,en,Dt.policy);if(Q.signal.throwIfAborted(),W!==h)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return c=Dt,u=gr,l=Date.now()+Math.max(0,gr-pr()),f=!1,d=0,I=0,s.writeManifest(vt(Dt)),Oe(),structuredClone(Dt)})(),le=setTimeout(()=>Q.abort(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Xt.initializationMs),We=new Promise((Ue,en)=>Q.signal.addEventListener("abort",()=>en(Q.signal.reason),{once:!0})),nt=Promise.race([ue,We]).catch(Ue=>{throw d++,(Ue instanceof KI.ZodError||Ue instanceof SyntaxError||Ue instanceof b&&["CONFIGURATION_HTTP_404","CONFIGURATION_HTTP_410","INVALID_RESPONSE"].includes(Ue.code))&&(u=0,f=!0,Oe()),Ue}).finally(()=>{clearTimeout(le),A===nt&&(A=void 0),ut()});return A=nt,nt}async function mr(W){let Q=W.sha256,ue=$r=>ds($r,W);Xe(W.url);let le=j.get(Q);if(le){if(le.byteLength!==W.byteLength)throw we("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return j.delete(Q),j.set(Q,le),le.text}let We=E.get(Q);if(We){if(We.byteLength!==W.byteLength)throw we("INVALID_RESPONSE","Configuration artifact digest or size mismatch");return We.promise}let nt=new AbortController;C.add(nt);let Ue=h,en=(async()=>{try{let gr=await s.readArtifact(Q);if(gr&&ue(gr)){if(nt.signal.throwIfAborted(),m||Ue!==h)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return He(Q,gr,W.byteLength),gr}}catch{}nt.signal.throwIfAborted();let $r=await Po(W.url,nt.signal,!0),Fn=await ke($r,W.byteLength,nt.signal);if(!ue(Fn))throw we("INVALID_RESPONSE","Configuration artifact digest or size mismatch");if(m||Ue!==h)throw we("CONFIGURATION_DISPOSED","Configuration scope changed");return He(Q,Fn,W.byteLength),s.writeArtifact(Q,Fn),Fn})(),qt=setTimeout(()=>nt.abort(we("CONFIGURATION_UNAVAILABLE","Configuration artifact timed out")),Xt.initializationMs),Dt=new Promise(($r,Fn)=>nt.signal.addEventListener("abort",()=>Fn(nt.signal.reason),{once:!0})),zr=Promise.race([en,Dt]).finally(()=>{clearTimeout(qt),C.delete(nt),E.delete(Q)});return E.set(Q,{promise:zr,byteLength:W.byteLength}),zr}async function fr(){return ye()||await Kt(),mt(),c}async function Ei(W){let Q,ue=new Promise((le,We)=>{Q=setTimeout(()=>We(we("CONFIGURATION_UNAVAILABLE","Configuration initialization timed out")),Xt.initializationMs)});try{return await Promise.race([W(),ue])}finally{clearTimeout(Q)}}function Ri(W,Q){if(mt(),c?.generation!==W.generation)throw we("CONFIGURATION_CHANGED","Configuration changed while preparing a snapshot");if(Q&&c.funnels[Q]?.state!=="active")throw we("FUNNEL_STOPPED","Funnel is paused or unavailable")}async function tl(W){let Q=W.gb.features;if(!Q)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");let ue=W.artifacts[Q];if(ue.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported public GB configuration format");let le=jc.parse(JSON.parse(await mr(ue)));if(vt(le.scope)!==vt({projectId:t.projectId,environment:t.environment})||le.generation!==ue.generation||le.remoteFeatures.some(We=>Object.hasOwn(le.features,We)))throw we("INVALID_RESPONSE","Public GB configuration scope or generation is invalid");return Ri(W),{...le,evaluatedAt:new Date().toISOString(),expiresAt:new Date(Date.now()+Math.max(0,u-pr())).toISOString()}}async function nl(W,Q){let ue=await fr(),le=ue.funnels[W];Q&&(!le||le.evaluationMode==="local"&&!le.versions[Q])&&(A&&await A,ue=await Kt()),Ri(ue,W);let We=ue.funnels[W];if(We.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel executes at Longplay; public graph loading is disabled");let nt=Q??We.currentVersionId,Ue=We.versions[nt];if(!Ue)throw we("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable");if(ue.artifacts[Ue.artifact].formatVersion!==3)throw we("UNSUPPORTED_SCHEMA","Unsupported public Funnel format");let[en,qt]=await Promise.all([mr(ue.artifacts[Ue.artifact]).then(Dt=>Tf(JSON.parse(Dt))),We.evaluationMode==="local"?tl(ue):void 0]);if(qt&&vt(jf(en,qt))!==vt(Ue.dependencies))throw we("INVALID_RESPONSE","Funnel and GB dependency contract do not match");return Ri(ue,W),{document:en,growth:qt,versionId:nt,control:structuredClone(We),manifest:structuredClone(ue)}}async function rl(W,Q){try{return await nl(W,Q)}catch(ue){if(!(ue instanceof b)||!(ue.code==="CONFIGURATION_CHANGED"||ue.code==="CONFIGURATION_HTTP_404"&&ye()))throw ue;let le=c?.generation;if(A&&await A,await Kt(),ue.code!=="CONFIGURATION_CHANGED"&&c?.generation===le)throw ue;return nl(W,Q)}}function fs(){f=!0,Oe(),Kt().catch(Ee)}let Co=()=>{(typeof document>"u"||document.visibilityState==="visible")&&fs()};function Xh(W){if(m)throw we("CONFIGURATION_DISPOSED","Configuration manager was destroyed");return w.add(W),w.size===1&&(typeof window<"u"&&(window.addEventListener("online",fs),window.addEventListener("focus",Co),document.addEventListener("visibilitychange",Co)),ut()),()=>{w.delete(W),w.size||(clearTimeout(g),clearTimeout(y),il())}}function il(){typeof window<"u"&&(window.removeEventListener("online",fs),window.removeEventListener("focus",Co),document.removeEventListener("visibilitychange",Co))}return{scope:Object.freeze({...t}),refresh:Kt,subscribe:Xh,assertFresh:mt,assertFeatures(W){mt();let Q=c.gb.features;if(!Q)throw we("CONFIGURATION_UNAVAILABLE","Public Feature delivery is disabled");if(W!==void 0&&c.artifacts[Q].generation!==W)throw we("CONFIGURATION_CHANGED","Refresh changed Feature configuration before evaluation")},get fresh(){return ye()},get snapshot(){return c?structuredClone(c):null},get remainingMs(){return ye()?Math.max(0,u-pr()):0},async features(){return Ei(async()=>tl(await fr()))},pageExperiments:()=>Ei(async()=>{let W=await fr(),Q=W.gb.pageExperiments;if(!Q)throw we("CONFIGURATION_UNAVAILABLE","Public page experiments are disabled");let ue=W.artifacts[Q];if(ue.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Unsupported page experiment format");let le=$g.parse(JSON.parse(await mr(ue)));if(le.environmentId!==t.environmentId||le.generation!==ue.generation)throw we("INVALID_RESPONSE","Page experiment scope or generation changed");return Ri(W),le}),funnel:(W,Q)=>Ei(()=>rl(W,Q)),paywall:(W,Q)=>Ei(async()=>{let ue=await fr(),le=ue.paywalls?.[W];if(!le||!Q&&le.state!=="published")throw we("PAYWALL_UNAVAILABLE","Published Paywall is unavailable");let We=Q??le.currentVersionId,nt=le.versions[We],Ue=nt&&ue.artifacts[nt.artifact];if(!Ue||Ue.kind!=="paywall"||Ue.formatVersion!==1)throw we("UNSUPPORTED_SCHEMA","Public Paywall format is unavailable");let en=Za.parse(JSON.parse(await mr(Ue)));return Ri(ue),{document:en,versionId:We,version:nt.version,control:structuredClone(le),manifest:structuredClone(ue)}}),async localFunnel(W,Q){let ue=await Ei(()=>rl(W,Q));if(!ue.growth)throw we("EVALUATION_MODE","This Funnel requires remote execution");let{analyticsConfig:le,remoteFeatures:We,...nt}=ue.growth;return Ug({scope:{projectId:t.projectId,environment:t.environment},funnelId:W,versionId:ue.versionId,evaluationMode:"local",evaluationRevision:ue.control.evaluationRevision,document:ue.document,payload:nt})},assertFunnel(W,Q,ue){mt();let le=c.funnels[W];if(!le||le.state!=="active")throw we("FUNNEL_STOPPED","Funnel is paused or unavailable");if(le.evaluationMode!=="local")throw we("EVALUATION_MODE","This Funnel now executes at Longplay");if(Q!==void 0&&le.controlRevision!==Q)throw we("RUN_RECONCILIATION_REQUIRED","Reconcile the original Run after a control change");if(ue!==void 0&&!le.versions[ue])throw we("CONFIGURATION_UNAVAILABLE","Pinned Funnel Version is unavailable")},destroy(){if(!m){m=!0,h++,u=0,k?.abort(we("CONFIGURATION_DISPOSED","Configuration manager was destroyed")),clearTimeout(g),clearTimeout(y),il(),Oe(),w.clear();for(let W of C)W.abort(we("CONFIGURATION_DISPOSED","Configuration manager was destroyed"));j.clear(),ae=0}}}}async function QI(e){e={...e};let t=e.configuration;if(!t)throw new b("CONFIGURATION_UNAVAILABLE","Local conditions require public configuration");let n={projectId:t.scope.projectId,environment:t.scope.environment};if(e.scope&&vt(n)!==vt(e.scope))throw new b("SCOPE_MISMATCH","Configuration and transport scopes differ");if((await t.funnel(e.funnelId)).control.evaluationMode!=="local")throw new b("EVALUATION_MODE","This Funnel uses Remote evaluation");let i=_i.test(e.credential);if(i?!e.customerId:e.customerId!==void 0)throw new b("INVALID_REQUEST","Only Server-Key starts name their Customer");let a=ls({...e,scope:n,apiKey:e.credential}),o=s=>{let c=dr({...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),l=await u.get();return{...c,...l,controller:u}},async restore(s){let c=o(s),u=await c.get();if(u.run.source.id!==e.funnelId)throw c.reset(),new b("SCOPE_MISMATCH","Run belongs to another Funnel");return{...u,runToken:s,controller:c}}}}function el(e,...t){try{Promise.resolve(e?.(...t)).catch(()=>{})}catch{}}function JI(e){if(!e.scope)throw new b("INVALID_CONFIGURATION","An explicit process App/environment scope is required");if(e.session!==void 0)throw new b("INVALID_CONFIGURATION","The merchant process adapter owns the session");let t=null,n,r=0,i=new Set,a=new Map,o=new Map;async function s(m){let h,d=new Promise((A,k)=>{h=setTimeout(()=>k(new b("TIMEOUT","Process bridge request timed out")),e.timeoutMs??35e3)});try{return await Promise.race([Promise.resolve().then(m),d])}finally{clearTimeout(h)}}function c(m){throw m instanceof b&&(m.status===401||m.reason==="CUSTOMER_BINDING_CONFLICT")&&(r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear()),m}function u(m,h){if(h!==r)throw new b("IDENTITY_CHANGED","Process was detached during a request");let d=Pu.parse(m);if(d.scope.projectId!==e.scope.projectId||d.scope.environment!==e.scope.environment)throw new b("SCOPE_MISMATCH","Process response belongs to another App/environment");if(t&&(t.run.id!==d.run.id||t.run.source.versionId!==d.run.source.versionId||t.run.source.id!==d.run.source.id||t.run.runExpiresAt!==d.run.runExpiresAt||t.run.identity.startedAs!==d.run.identity.startedAs||t.run.identity.participantId!==d.run.identity.participantId||t.run.identity.binding&&d.run.identity.binding&&t.run.identity.binding.id!==d.run.identity.binding.id))throw new b("INVALID_RESPONSE","The process changed its Run or Customer binding");if(!t||d.run.revision>=t.run.revision){if(t?.run.identity.binding&&!d.run.identity.binding)throw new b("INVALID_RESPONSE","The process lost its Customer binding");t=d;for(let j of i)el(j,d.run);d.run.instruction?.type==="authentication_required"&&el(e.onAuthenticationRequired,d.run)}d.settlement?.accepted!==void 0&&o.set(d.settlement.requestId,d.settlement.accepted);let{identity:A,instruction:k,...g}=d.run,{contract:y,settlement:I,...w}=d,C=I&&(({accepted:j,...E})=>E)(I);return{...w,run:{...g,authenticated:A.binding!==null,instruction:k?.type==="authentication_required"?null:k},...C?{settlement:C}:{}}}let l=m=>(a.has(m)||a.set(m,t?.run.identity.binding?.id??null),a.get(m));async function f(m){let h=r,d=t?.run.identity.binding?.id??null,A=g=>{if(d!==(t?.run.identity.binding?.id??null))throw g;return c(g)};if(m.operation==="page_experiments"){if(!e.adapter.pageExperiments)throw new b("CAPABILITY_UNAVAILABLE","Process page experiments are unavailable",501);return s(()=>e.adapter.pageExperiments(m.release,m.usedReceiptIds)).catch(A)}let k;if(m.operation==="get"){let{operation:g,customerToken:y,...I}=m;k=await s(()=>e.adapter.get({...I,...I.settlementRequestId?{settlementBindingId:l(I.settlementRequestId)}:{}})).catch(A)}else if(m.operation==="review")k=await s(()=>e.adapter.review(m.receiptId)).catch(A);else{if(m.operation==="start")throw new b("INVALID_REQUEST","Use process.open for entry");{let{customerToken:g,...y}=m;k=await s(()=>e.adapter.command(y,l(y.requestId))).catch(A)}}return u(k,h)}return{get view(){return t?.run??null},get controller(){return n},async open(m){let h=r,d=await s(()=>e.adapter.open(m)).catch(c);if(u(d,h),!n){n=dr({...e,runToken:d.runToken,process:{request:f,binding:l,restore(g){for(let[y,I]of Object.entries(g))a.set(y,I)}}});let A=n,k=A.submit;A.submit=async g=>{try{return await k(g)}catch(y){if(!(y instanceof b)||y.reason!=="IDENTITY_CONTEXT_CHANGED"||g.operation!=="submit"||g.input.type!=="screen"||a.get(g.requestId)!==null)throw y;await A.settle?.(g.requestId),await A.get();let I=A.view;if(o.get(g.requestId)!==!1||!I||I.id!==t?.run.id||I.nodeId!==g.nodeId||I.visit!==g.visit||!t?.run.identity.binding)throw y;return k({...g,requestId:crypto.randomUUID(),revision:I.revision})}}}await n.get();for(let A of n.pendingCommands??[])a.has(A.requestId)&&a.get(A.requestId)!==(t?.run.identity.binding?.id??null)&&await n.settle?.(A.requestId);return{run:t.run,controller:n}},async syncIdentity(){let m=r;u(await s(()=>e.adapter.syncIdentity()).catch(c),m),await n?.get();for(let h of n?.pendingCommands??[])a.has(h.requestId)&&a.get(h.requestId)!==(t?.run.identity.binding?.id??null)&&await n?.settle?.(h.requestId);return t.run},async detach(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),await s(()=>e.adapter.detach())},forProcess(m){if(!t?.run.identity.binding)throw new b("UNAUTHENTICATED","Sign in before a commercial operation",401);return{runId:t.run.id,bindingId:t.run.identity.binding.id,receiptId:m}},subscribe(m){return i.add(m),()=>{i.delete(m)}},destroy(){r++,n?.reset(),n=void 0,t=null,a.clear(),o.clear(),i.clear()}}}export{b as LongplayError,HI as createConfigurationSync,Wu as createFeatureClient,JI as createFunnelProcess,QI as createLocalFunnelClient,UI as createLongplayReactNative};